[Image-SIG] Re: Returning Colormap values for an image?

Fredrik Lundh fredrik at pythonware.com
Sat Sep 18 15:12:05 CEST 2004


Fredrik Lundh wrote:

>> Also, if the image I have is an RGB image (such as the result of an
>> ImageGrab), what is the best way to get the colours used? Is
>> converting to 'P' mode and then using the resize/convert method the
>> easiest/fastest?
>
> probably, as long as you're aware that you won't get exact results if
> the image contains more than 256 colors.

footnote: I just added a "getcolors" method to the 1.1.5 beta (out soon)
which returns an unsorted list of (count, color) tuples.  by default, it stops
counting and returns None if it finds more than 256 colors, but that limit
can be adjusted.

here's one way to use this method:

    if im.getcolors():
        # no more than 256 colors; we can make an exact conversion to P
        im = im.convert("P", dither=Image.NONE, palette=Image.ADAPTIVE)

here's another way:

    colors = im.getcolors(im.size[0]*im.size[1])
    colors.sort()
    print "the most common color is", colors[-1][1]

(but you probably shouldn't run the second example on very large
images, unless you have lots of memory)

</F> 





More information about the Image-SIG mailing list