如何从Python中的像素值列表创建PNG图像文件? [英] How can I create a PNG image file from a list of pixel values in Python?
问题描述
我可以使用如下过程从现有图像文件生成像素值列表:
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图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!