[SciPy-user] saving raw image

Zachary Pincus zachary.pincus at yale.edu
Wed Oct 15 10:20:44 EDT 2008


Hi Sahar,

Please send a minimal example of loading and saving an array that  
produces "garbage" output, if you could... (If you could send a small  
input file that would be helpful too.)

Also, does the garbage you see in ImageJ have some structure -- does  
it look streaky, like you can see rows of pixels that should be  
together, but the rows don't line up right?

One possible problem is that the array you are saving has been  
promoted to a different dtype (e.g. by participating in signed/float  
arithmetic), so the pixels you save are no longer uint16s. Unless you  
have an 'astype(uint16)' in your save code, this could be the issue,  
since the loading code you showed does immediately convert the array  
from uint16s. (This is why sending a complete example of the failure  
is useful...)

Another possible problem has to do with the order the pixels are read/ 
written out. Typically, images on disk are stored as rows of pixels  
next to one another -- this is "column major" or "fortran" order  
(going from one memory location to the next typically increments the x- 
value, except at row boundaries where the y-value is incremented, so  
it is said that the x-value "varies the fastest"). Typically, numpy  
arrays are created in row major or "C" order, where the y-value varies  
the fastest. When loading and manipulating images, you need either to  
make sure that the images are loaded in fortran-order, or reverse the  
x/y coordinates and shape.

So, e.g. when loading a 200x300 image:


s = file(path, 'rb').read()
raw = fromstring(s, uint16).astype(int)
image = raw.reshape((200,300), order='F')

now, image[30,40] gives the same pixel as coordinate (30,40) in ImageJ.

If you did:
image = raw.reshape((300,200), order='C')
then image[30,40] would give the same pixel as coordinate (40,30) in  
ImageJ.

Note that the 'C' order is default. So:
image = raw.reshape((200,300))
will give garbage, with the rows of pixels broken up along the wrong  
boundaries, giving rise to the "streaky" images I mentioned.

Finally, the tostring() method also takes an order option, so for  
saving images, you need:
raw = image.tostring(order='F')
(assuming that you reshaped the image as order 'F')

Zach Pincus



On Oct 15, 2008, at 4:49 AM, Sahar Vilan wrote:

> I used scipy for basic image processing of raw images, and I can't  
> save
> these images in the same format:
> To open image I use:
> 	s = file(path, 'rb').read()
>    	raw = fromstring(s, uint16).astype(int)
>
> I try to save this matrix as raw image again but I get some garbage  
> when I
> open it in some viewer (Image-J, for instance).
> Can anyone help me with this?
>
> Thanks,
> Sahar




More information about the SciPy-User mailing list