Python: how do you create an array with information about each pixel from an image?

牧云@^-^@ 提交于 2019-12-02 12:14:29

问题


For example, a 3 pixel by 3 pixel jpeg image of a checkerboard should be something like

[[#000000, #FFFFFF, #000000],
[#FFFFFF, #000000, #FFFFFF],
[#000000, #FFFFFF, #000000]]

I feel like I may need to download PIL, but I cannot tell what the module does from their website. I also need to be able to generate images from these types of arrays. Thank you!


回答1:


Use the Image.getdata method. The method returns a generator that you can iterate over:

from PIL import Image
img = Image.open("a.png")
data = img.getdata()
for (r, g, b, a) in data:
    # do something with the pixel values

To go the other way you use Image.putdata. This generates a tiny checkerboard picture:

>>> img = Image.new("L", (3, 3))
>>> data = [0, 255, 0, 255, 0, 255, 0, 255, 0]
>>> img.putdata(data)
>>> img.save("checkerboard.png")

Here I created a grayscale image (only one "luminescence" channel) and so I just used a single integer value for each pixel.



来源:https://stackoverflow.com/questions/9143485/python-how-do-you-create-an-array-with-information-about-each-pixel-from-an-ima

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!