Image stats - going from Matlab to Python

Robert Kern rkern at ucsd.edu
Mon Jan 31 02:12:06 EST 2005


tjv at hotmail.com wrote:
> Hi all,
> I am working with images in python using PIL. I come from a MATLAB
> background so I am finding it to be sometimes frustrating to do things
> correctly and quickly.

Yup. That's the curse of changing toolsets.

> All I need to do is load an image and store a
> list of pixel coordinates at which the alpha channel is set to 1.
> In Matlab this would be easy...Lets say we have a 2x2x4 array that
> represents the image. I would just type something like:
> 
> indices = find(im(:,:,3)==1);
> 
> then work with indices to get xy coords. Is there a similar way to
> accomplish the same thing in python and PIL without having a nested for
> loop and checking every pixel?
> I would appreciate advice. Thanks very much for your attention!

One way would be to use Numeric or numarray, which you will probably 
want anyway if you are doing Matlab-type stuff. If you are dealing with 
large images or are dealing with raw data on disk (as opposed to PNGs or 
GIFs), numarray might be best for you.

A mildly tested example:

   import Numeric as N
   import Image

   filename = 'heavy_1.gif'
   img = Image.open(filename).convert('RGBA')
   data = img.tostring()

   arr = N.fromstring(data, N.UInt8)
   arr.shape = (img.size[1], img.size[0], 4)

   mask = (arr[:,:,3] == 255).flat

   idx = N.indices(arr.shape[:2])
   idx.shape = (2, len(mask))

   pixels = N.compress(idx, mask)
   # for all i, arr[pixels[0,i], pixels[1,i], 3] == 255

I'm sure there's some code floating around that makes these kinds of 
operations simpler.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter



More information about the Python-list mailing list