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

Fredrik Lundh fredrik at pythonware.com
Mon Aug 23 13:46:44 CEST 2004


Alfred Milgrom wrote:

> The only problem (if you can call it that?) is that the colours
> actually used in the original image are not necessarily the first n
> values in the lut image, and so it is necessary to not only work out
> how many colours are used initially but also which indices are used.
>
> Is there an easier way to get a list of the indices used than something like:
>
> hist = im.histogram()
> coloursUsed = [i for i in range(len(hist)) if hist[i]]

not really: the histogram approach is the only efficient way to find out
what colors you have in an L or P-mode image.

> 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.

for best results, use:

    im = im.convert("P", dither=Image.NONE, palette=Image.ADAPTIVE)

(no dithering, adaptive palette.  if you need more control over the
process, you can use the undocumented quantize method, but you'll
have to read the source code to figure out how that works).

</F> 





More information about the Image-SIG mailing list