How to count pixels of a color in an image?

jjv5 jjv5 at yahoo.com
Tue Mar 19 15:33:36 EST 2002


A simple question perhaps. Any help is appreciated.
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.
The image
is about 3800 by 3000 pixels. Any suggestions?


Jim



More information about the Python-list mailing list