Number of colors in an image

David Bolen db3l at fitlinxx.com
Mon Nov 29 19:14:54 EST 2004


Christos "TZOTZIOY" Georgiou <tzot at sil-tec.gr> writes:

> A set seems more appropriate in this case:
> 
> color_count = len(set(izip(r, g, b))) # untested code

Well, while potentially premature optimization, I was trying for
performance in this case.  In Python 2.3, the sets module is coded in
Python, and just wraps a dictionary, and when handed an iterable, ends
up looping (in Python) with individual dictionary key assignments.
Although I didn't specifically test sets, when I did a loop like that
myself, it was 5-6 times slower than directly building the dictionary.

That might change in 2.4 with the built-in set - it's still a wrapper
around dict but knows it's just directly setting items to a true value
so can avoid dealing with the tuples that dict does (not to mention I
don't have to build the extra tuple).

Although I expect the direct support in PIL 1.1.5 that Fredrik posted
about will be best.

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

Oops, definitely yes.

-- David



More information about the Python-list mailing list