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

后端 未结 1 1327
青春惊慌失措
青春惊慌失措 2021-01-25 10:43

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

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


        
相关标签:
1条回答
  • 2021-01-25 11:11

    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.

    0 讨论(0)
提交回复
热议问题