Color count in PIL

David M. Cooke cookedm+news at physics.mcmaster.ca
Thu Jan 29 17:25:54 EST 2004


At some point, wrbt at email.com (Larry) wrote:

> wrbt at email.com (Larry) wrote in message news:<2ec1bc1c.0401271443.15f56742 at posting.google.com>...
>> I've been walking up, down, and around instances in the object model
>> of PIL trying to figure out how to easily calculate how many unique
>> colors are used in an image, specifically a bitmap (mode "P"). Am I
>> missing something?
>> 
>> Thanks python friends!
>
> So far I have: colors=len(sets.Set(list(im.getdata())))
>
> That makes me want to throw up.

Probably very inefficient. Have a look at im.histogram(). Something
like:

colours = sum( [ 1 for h in im.histogram() if h != 0 ] )

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list