GermainZ GermainZ - 3 years ago 127
Python Question

Get pixel's RGB using PIL

Is it possible to get the RGB color of a pixel using PIL?
I'm using this code:

im = Image.open("image.gif")
pix = im.load()
print(pix[1,1])


However, it only outputs a number (e.g.
0
or
1
) and not three numbers (e.g.
60,60,60
for R,G,B). I guess I'm not understanding something about the function. I'd love some explanation.

Thanks a lot.

Answer Source

Yes, this way:

im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))

print(r, g, b)
(65, 100, 137)

The reason you were getting a single value before with pix[1, 1] is because GIF pixels refer to one of the 256 values in the GIF color palette.

See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert() function.

By the way, your code would work just fine for .jpg images.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download