Fastest Way To Loop Through Every Pixel

nikie n.estner at gmx.de
Fri Jul 28 19:11:27 EDT 2006


Chaos wrote:

> As my first attempt to loop through every pixel of an image, I used
>
>         for thisY in range(0, thisHeight):
>             for thisX in range(0, thisWidth):
>                   #Actions here for Pixel thisX, thisY
>
> But it takes 450-1000 milliseconds
>
> I want speeds less than 10 milliseconds

Milliseconds don't mean much unless we knew how big your images are and
what hardware you're using.

Have you considered using NumPy? Assuming you can get the image into a
numpy array efficiently, the actual algorithm boils down to something
like this:

    grey = r*0.3 + g*0.59 + b*0.11
    index = grey.argmin()
    x,y = index%step, index/step
    v = grey[x,y]

where r,g,b and grey are numpy.ndarray objects; The arithmetic
operators and the argmin-function are implemented in C, so you can
expect decent performance. (the 4 lines above take about 80 ms for a
1000x1000 image on my PC)

If that's not enough, you might want to use some specially optimized C
library for this purpose. (I'd suggest Intel's IPP, but there are
others).




More information about the Python-list mailing list