Fastest Way To Loop Through Every Pixel

Simon Forman rogue_pedro at yahoo.com
Fri Jul 28 04:03:32 EDT 2006


Simon Forman wrote:
> Chaos wrote:
> > Simon Forman wrote:
> > > 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
> > > >
> > > > I have tried using SWIG, and pypy but they all are unsuccessfull in
> > > > compiling my files.
> > >
> > > You could try the PIL package.
> > >
> > > >From the docs at
> > > http://www.pythonware.com/library/pil/handbook/image.htm
> > >
> > > Image.eval(function, image) => image
> > >
> > > Applies the function (which should take one argument) to each pixel in
> > > the given image. If the image has more than one band, the same function
> > > is applied to each band. Note that the function is evaluated once for
> > > each possible pixel value, so you cannot use random components or other
> > > generators.
> > >
> > > HTH,
> > > ~Simon
> >
> > I have tried PIL. Not only that, but the Image.eval function had no
> > success either. I did some tests and I found out that Image.eval only
> > called the function a certain number of times either 250, or 255.
>
> It says "the function is evaluated once for each possible pixel value",
> so if it's only calling the function 250 or 255 times it's because your
> image only has 250 or 255 colors.
>
> Obviously Image.eval() caches the results of your function for each
> color/pixel-value and reuses them rather than recomputing them.
>
> I take it that whatever you're doing to those pixels involves more
> information than just the pixel values?  What are you doing to the
> pixels? That's probably wher you should look to improve the speed of
> the loop.
>
> Peace,
> ~Simon

Oops, sorry.  I didn't see where you had already posted the actions
you're taking on the pixels..

He is the code #Actions here

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

Hmm,  if you're just trying to find the darkest color and one of it's
pixel coordinates after applying your weighting calculation, and you
don't mind if the coordinates are of the first encountered pixel of
that color, then I think you might be able to use Image.eval() after
all.

What format are the images in?


Peace,
~Simon




More information about the Python-list mailing list