Get pixel's RGB using PIL Get pixel's RGB using PIL python python

Get pixel's RGB using PIL


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.


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

from PIL import Imagedef 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# Usageim = Image.open("image.gif")pal = getPalletteInRgb(im)