[SciPy-user] trying to use weave to access image data in C

Danial, Al (IIS) al.danial at ngc.com
Tue Sep 28 17:25:54 CDT 2004

I'm inspired by recent posts on using weave to include C code within
a Python program.  Does anyone have an example of how one would access 
the bytes of an image (as loaded with imread) within a weave C inline?

Here's a rough idea of what I'm trying to do

  from scipy import imread, weave 

  img = imread('image.pcx')
  rows, cols, colors = img.shape
  code = """
         for (int j=0; j < cols; j++)
             for (int i=0; i < rows; i++)
                 printf("img[%3d][%3d]=%3d %3d %3d\n", 
                         i, j, img[i][j][0], img[i][j][1], img[i][j][2]);

Of course I'm interested in actually doing some math on the R,G,B
values at each pixel, not just printing the values out.  At the moment 
I'm doing the loops over each pixel (indices i and j in the C code above)
in Python and it is pretty slow.

1. How should I declare the img variable in the C code so that it 
   correctly binds to the Python variable of the same name?
2. How would I step through the img variable in the C code?  For example 
   would the green value at pixel i,j be referenced as
      img[i + j*rows][2]
      img[(i + j*rows)*2]
3. This is the bonus round:  if I modify the img variable in the C code
   how can I get the modified value back to Python?  I'm studying 
   which explains the process scalar integers well.  Don't know how to
   extend that to the array type returned by imread though.

 -- Al 

More information about the SciPy-user mailing list