How to count pixels of a color in an image?

Bengt Richter bokr at oz.net
Tue Mar 19 16:58:42 EST 2002


On 19 Mar 2002 12:33:36 -0800, jjv5 at yahoo.com (jjv5) wrote:

>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]
I suspect python will do the unpacking for you, assuming rgb pixels,
and you don't seem to be doing anything with i other than indexing.
>     green = green + (( b>r) and (g>r))
>     purple = purple + ((r>g) and (b>g))
These would seem to compute and add a lot of zeroes. Also r>g amd g>r
can't be true for both green and purple, so I'd reorder and get some
advantage from shortcut evaluation, e.g., combining the above, I'd try:

    # (untested)
    green=o
    purple=0
    dat = im.getdata()
    for r,g,b in dat:
        if g>r and b>r:
            green += 1
        elif r>g and b>g:
            purple += 1

After that maybe psyco, or maybe something in the histogram feature can be hooked?

>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?
>
>
HTH,

Regards,
Bengt Richter




More information about the Python-list mailing list