1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, exactly what I was looking for. Only one question: how do I move to three color channels? I assume each pixel is a 3-tuple but what do put instead of "L"?
It's right there in the manual: you use RGB as the mode for three channels.
@user1189737: oh, sorry! I didn't see you were so new here :-) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.