Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 601
GermainZ Avatar asked Jun 16 '12 15:06

GermainZ


People also ask

How do I extract the RGB values from an image?

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.

How can we get an RGB of a pixel?

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.


2 Answers

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.

like image 157
Levon Avatar answered Oct 12 '22 23:10

Levon


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.

like image 29
KobeJohn Avatar answered Oct 12 '22 22:10

KobeJohn