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.
Click on the color selector icon (the eyedropper), and then click on the color of in- terest to select it, then click on 'edit color'. 3. The RGB values for that color will appear in a dialogue box.
Retrieving the pixel contents (ARGB values) of an image −Get the pixel value at every point using the getRGB() method. Instantiate the Color object by passing the pixel value as a parameter. Get the Red, Green, Blue values using the getRed(), getGreen() and getBlue() methods respectively.
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.
GIFs store colors as one of x number of possible colors in a palette. Read about the gif limited color palette. So PIL is giving you the palette index, rather than the color information of that palette color.
Edit: Removed link to a blog post solution that had a typo. Other answers do the same thing without the typo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With