[Image-SIG] Saving 16bit tiffs
Scott Rifkin
scott.rifkin at yale.edu
Mon Feb 16 12:25:20 EST 2004
Following up my previous post with another question:
I tried using fromstring and tostring instead of putdata.
Here are the functions:
def image_to_array(image):
#returns a Numeric array from an Image using getdata
return reshape(array(image.getdata()), (image.size[1], image.size[0]))
def array_to_image(matrix, mode = 'I;16'):
#returns an Image from a Numeric array using fromstring(Image) and tostring(Numeric)
return Image.fromstring(mode, (matrix.shape[1], matrix.shape[0]), ravel(matrix.astype(Int)).tostring())
>>>mat=RandomArray.randint(0,60000,(6,4)) #an array of random ints 0-60000
>>>im=array_to_image(mat)
>>>mat_from_im=image_to_array(im)
now when I look at the matrices (or at the images) there are columns of
zeros interspersed. for example (I've substituted letters for the numbers
to make it more readable...there is no O, anything that looks like that is
a zero)
>>>mat
array([[A,B,C,D],
[E,F,G,H],
[I,J,K,L],
[M,N,P,Q],
[R,S,T,U],
[V,W,X,Y]])
>>>mat_from_image
array([[A,0,B,0],
[C,0,D,0],
[E,0,F,0],
[G,0,H,0],
[I,0,J,0],
[K,0,L,0]])
note that if I change the width of the array mat to an odd number (say a
6x3 matrix), the are no longer columns but are in positions
(0,1),(1,0),(1,2),(2,1)...every other number if you were to ravel it.
The problem is making the strings. When I look at what is returned by
mat.tostring(), I get a string like '\xe9\x98\x00\x00\x1c\x81\x00\x00...
I can make a new string by just cutting out all the \x00\x00 repeats and
then reconstruct the image using Image.fromstring(), and this gives me the
correct image.
My questions are, why is it padding wthe string ith the extra \x00\x00 in
the first place? What are these to/fromstring() functions doing? There
must be a more appropriate way to do this, how?
Thanks much.
Scott Rifkin
More information about the Image-SIG
mailing list