Get RGB pixel using PIL

Is it possible to get the color of an RGB pixel using PIL? I am using this code:

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

However, it outputs only a number (e.g. 0 or 1 ), not three numbers (e.g. 60,60,60 for R, G, B). I guess I don’t understand anything about the function. I would like the explanation.

Thank you very much.

+76
python image pixel rgb python-imaging-library
Jun 16 2018-12-16T00:
source share
4 answers

Yes, in 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 got one value before pix[1, 1] is because GIF pixels belong to one of 256 values ​​in the GIF color palette.

See also this SO post: Python and PIL pixel values ​​that are different for GIF and JPEG , and this PIL Help page contains additional information about the convert() function.

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

+120
Jun 16 '12 at 15:52
source share

GIFs store colors as one of the x possible colors in the palette. Read about the limited gif color palette . Thus, PIL gives you the index of the palette, not the color information of the color of that palette.

Edit: The link to the solution for publishing on the blog in which there was a typo has been removed. Other answers do the same without a typo.

+3
Jun 16 '12 at 15:52
source share

Not PIL, but imageio.imread can still be interesting:

 import imageio im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB') im = imageio.imread('Figure_1.png', pilmode='RGB') print(im.shape) 

gives

 (480, 640, 3) 

the way it is (height, width, channels). So the pixel at position (x, y)

 color = tuple(im[y][x]) r, g, b = color 

outdated

scipy.misc.imread deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr !)

+2
Jul 24 '16 at 9:02
source share

An alternative to image conversion is to create an RGB index from the palette.

 from PIL import Image def chunk(seq, size, groupByList=True): """Returns list of lists/tuples broken up by size input""" func = tuple if groupByList: func = list return [func(seq[i:i + size]) for i in range(0, len(seq), size)] def getPaletteInRgb(img): """ Returns list of RGB tuples found in the image palette :type img: Image.Image :rtype: list[tuple] """ assert img.mode == 'P', "image should be palette mode" pal = img.getpalette() colors = chunk(pal, 3, False) return colors # Usage im = Image.open("image.gif") pal = getPalletteInRgb(im) 
+1
Jul 07 '16 at 20:11
source share



All Articles