Fastest Way To Loop Through Every Pixel

Paul McGuire ptmcg at austin.rr._bogus_.com
Fri Jul 28 01:40:54 EDT 2006


"Chaos" <psnim2000 at gmail.com> wrote in message
news:1154055002.495073.171650 at i3g2000cwc.googlegroups.com...
>
>
> myCol = (0.3 * image.GetRed(thisX, thisY)) + (0.59 *
> image.GetGreen(thisX, thisY)) + (0.11 * image.GetBlue(thisX, thisY))
> if myCol < darkestCol:
>    darkestCol = myCol
>    possX = thisX
>    possY = thisY
>

Psyco may be of some help to you, especially if you extract out your myCol
expression into its own function, something like:

def darkness(img,x,y):
    return  (0.3 * img.GetRed(x,y)) + (0.59 * img.GetGreen(x,y)) + (0.11 *
img.GetBlue(x,y))

You may also be paying a penalty for the floating-point multiplications.
Since you are only concerned with the relative values, what if you scale up
all of your weighting coefficients, so that you only do integer multiplies?

def darkness(img,x,y):
    return  (30 * img.GetRed(x,y)) + (59 * img.GetGreen(x,y)) + (11 *
img.GetBlue(x,y))

You can also cut down on resolution of your GetXXX functions by saving them
to locals.

RedVal = Image.GetRed
GrnVal = Image.GetGreen
BluVal = Image.GetBlue
def darkness(img,x,y):
    return  (30 * RedVal(img,x,y)) + (59 * GreenVal(img,x,y)) + (11 *
BlueVal(img,x,y))

Even downer-and-dirtier, you could approximate 30 with 32, 59 with 64, and
11 with 8, and do bit-shifting instead of multiplying:

def darkness(img,x,y):
    return  (RedVal(img,x,y) << 5) + (GreenVal(img,x,y) << 6) +
(BlueVal(img,x,y) << 3)


-- Paul





More information about the Python-list mailing list