[Tutor] quick PIL question

Tim Peters tim.peters at gmail.com
Fri Jun 3 01:11:48 CEST 2005

[Max Noel]
> ...
>     This is where the palette comes into play. Each 256-color image
> has a palette, which is basically an array of length 256, where each
> element is a (24-bit RGB) color. The color data for each pixel in the
> image is actually an index in this array.

Adding a bit of detail, in PIL getpalette() returns a list with 256*3
= 768 integers.  The first three are the red, green and blue intensity
levels (each in 0 thru 255) for "palette index 0", the next three are
the RGB values for palette index 1, and so on.  The "palette index" is
more conceptual here than directly reflected in the PIL data
structures.  In general, if p is a PIL palette, p[3*i : 3*i+3] returns
[R, G, B] for pixel index i.  Going back a level, if getpixel((x, y))
returns an integer i for a "P"-mode image, then
getpalette()[3*i:3*i+3] returns pixel (x, y)'s RGB values.

BTW, I didn't know this before I had to learn it to solve some of the
Python Challenge riddles.  If you like puzzles, these are an excellent
motivator to learn about some under-appreciated Python libraries! 
Highly recommended.

More information about the Tutor mailing list