How to count pixels of a color in an image?

Fredrik Lundh fredrik at pythonware.com
Tue Mar 19 17:27:13 EST 2002


"jjv5" wrote:

> I need to count the number of pixels that are purple or blue-green in
> a large image. I can do this with the Image module easily enough,
> but it is painfully slow.  I do something like this:
>
> green=0
> purple=0
> dat = im.getdata()
> for i in range(len(dat)):
>      r,g,b = dat[i][0],dat[i][1],dat[i][2]
>      green = green + (( b>r) and (g>r))
>      purple = purple + ((r>g) and (b>g))
>
> The slow part is the for loop over the image data. Even if the loop
> body is empty it still takes about 15 seconds on a fast computer. the
> getdata function takes about 3 seconds. Surely there is a better way.

this sounds like NumPy country, but some creative use
of the ImageChops stuff might help a bit:

from ImageChops import *

r, g, b = im.split()

pixels = im.size[0] * im.size[1]

green = pixels - darker(subtract(b, r), subtract(g, r)).histogram()[0]
purple = pixels - darker(subtract(r, g), subtract(b, g)).histogram()[0]

</F>





More information about the Python-list mailing list