Fastest Way To Loop Through Every Pixel

John Machin sjmachin at lexicon.net
Thu Jul 27 21:45:59 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

OT: you don't need the 0 in the range call. Taking it out doesn't make
it run faster, though.

>
> But it takes 450-1000 milliseconds
>
> I want speeds less than 10 milliseconds
>
> I have tried using SWIG, and pypy but they all are unsuccessfull in
> compiling my files.

Unsuccessful because .... what?
[I wasn't aware that swig was intended to compile Python scripts]

Sticking with Python:
With the "for thisX" try
(1) using xrange instead of range.
(2)     widthRange = range(thisWidth)
         for thisY in range(thisHeight):
             for thisX in widthrange:
and in general, hoist loop-invariants outside the loop.

Have you considered Pyrex?

It all depends on what "#Actions here for Pixel thisX, thisY" is doing.
Perhaps there is a library (PIL, pygame, ...) that does what you are
trying to do.
Perhaps if you show us what you are doing, we can give you better
advice.

HTH,
John




More information about the Python-list mailing list