且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 14:40:34

快速修复



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

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')