Skip to content Skip to sidebar Skip to footer

Python: How Do You Create An Array With Information About Each Pixel From An Image?

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 f

Solution 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) indata:
    # 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.

Post a Comment for "Python: How Do You Create An Array With Information About Each Pixel From An Image?"