Number of colors in an image

Christos TZOTZIOY Georgiou tzot at
Sat Nov 27 00:25:30 CET 2004

On 26 Nov 2004 17:18:04 -0500, rumours say that David Bolen
<db3l at> might have written:

>        # Use a dictionary to count colors by constructing it with an
>        # iterator of tuples of (pixel,1).  The inner izip makes each
>        # pixel tuple out of the individual band values, and the outer
>        # izip combines it with the infinitely repeating 1 to generate
>        # the values for the dictionary constructor.
>        colors = dict(izip(izip(r,g,b), repeat(1)))
>        print 'Number of colors =', len(colors)

A set seems more appropriate in this case:

color_count = len(set(izip(r, g, b))) # untested code

>For a greyscale, or single banded image, it should be faster just to
>use the built-in PIL "histogram" method and take the length of the
>resulting list.

More like the count of non-zero elements in the histogram; I believe the
length of the resulting list will be constant (ie 256).
TZOTZIOY, I speak England very best,
"Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek

More information about the Python-list mailing list