Retrieve a GIF's palette entries using Python Imaging Library (PIL)

S

Stuart

I am using the Python Imaging Library (PIL) to process GIF images. I
need to be able to retrieve the RGB values for each color palette entry.

I see that the 'Image' class has a 'palette' attribute which returns an
object of type 'ImagePalette'. However, the documentation is a bit
lacking regarding how to maniuplate the ImagePalette class to retrieve
the palette entries' RGB values. Can anyone point me to a short example?

Thanks!
 
A

and-google

Stuart said:
I see that the 'Image' class has a 'palette' attribute which returns an
object of type 'ImagePalette'. However, the documentation is a bit
lacking regarding how to maniuplate the ImagePalette class to retrieve
the palette entries' RGB values.

ImagePalette.getdata() should do it.

There seems to be some kind of bug, however, where Images lose their
ImagePalettes after being convert()ed to paletted images (eg. using
Image.ADAPTIVE). For this reason I personally use the getpalette()
method from the wrapped image object, which seems to contain the proper
raw palette data. For example to get a list of [r,g,b] colour lists:

def chunk(seq, size):
return [seq[i:i+size] for i in range(0, len(seq), size)]

palette= image.im.getpalette()
colours= [map(ord, bytes) for bytes in chunk(palette, 3)]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top