如何从Python中的像素值列表创建PNG图像文件?

编程入门 行业动态 更新时间:2024-10-28 02:27:13
本文介绍了如何从Python中的像素值列表创建PNG图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以使用如下过程从现有图像文件生成像素值列表:

I can generate a list of pixel values from an existing image file using a procedure like the following:

from PIL import Image image = Image.open("test.png") pixels = list(image.getdata()) width, height = image.size pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]

如何将此像素值列表转换回图像文件?

How could I convert this list of pixel values back to an image file?

推荐答案

快速修复

首先,你需要将你的像素元组放在一个非嵌套列表中:

Quick fix

First, you need to have your pixel tuples in a single un-nested list:

pixels_out = [] for row in pixels: for tup in row: pixels_out.append(tup)

接下来,使用输入图像的属性制作一个新的图像对象,并将数据放入其中:

Next, make a new image object, using properties of the input image, and put the data into it:

image_out = Image.new(image.mode,image.size) image_out.putdata(pixels_out)

最后,保存它:

image_out.save('test_out.png')

基本问题

列表推导生成列表列表,后者由切片生成(我*宽度:第(i + 1)*宽度)。您的理解可以更容易: pixels = [像素的像素数] 。显然,这会输出相同的列表 pixels ,但您可以使用这个想法对像素执行操作,例如 pixels = [像素的操作(像素)] 。

Fundamental issue

Your list comprehension generates a list of lists, the latter being generated by the slicing (i*width:(i+1)*width). Your comprehension can be much easier: pixels = [pixel for pixel in pixels]. Obviously this outputs the same list, pixels, but you can use the idea to perform an operation on the pixels, e.g. pixels = [operation(pixel) for pixel in pixels].

真的,你打败了它。您无需管理图像尺寸。获取列表中的像素,然后使用 putdata 将它们放入相同大小的图像中,因为它们按照PIL以相同的方式线性化。

Really, you overthought it. You don't have to manage the image dimensions. Getting the pixels in a list, and then putting them into an equal-sized image with putdata keeps the in order because they are linearized the same way by PIL.

简而言之,这就是你的原始代码片段:

In short, this is what your original snippet should have been:

from PIL import Image image = Image.open("test.png") image_out = Image.new(image.mode,image.size) pixels = list(image.getdata()) image_out.putdata(pixels) image_out.save('test_out.png')

更多推荐

如何从Python中的像素值列表创建PNG图像文件?

本文发布于:2023-06-08 14:28:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/583071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:像素   图像文件   列表   Python   PNG

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!