Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write numpy ndarray to Image

I'm trying to read a binary file (8 bit RGB tuples) in Python, do some conversion on it and then write it as a png image. I'm doing the following:

typeinfo = np.dtype('>i1' ) #read single bytes data=np.fromfile(("f%05d.txt" %(files[ctr])),dtype=typeinfo) data=np.reshape(data,[linesperfile,resX,3]) #reshape to size/channels 

If I display the type information of data it says:

<type 'numpy.ndarray'> (512L, 7456L, 3L) 

Then I do some manipulation on the image (in-place), afterwards I want to write the Image to a file. Currently I use:

import PIL.Image as im svimg=im.fromarray(data) svimg.save(("im%05d"%(fileno)),"png") 

but it keeps giving me the following error:

line 2026, in fromarray raise TypeError("Cannot handle this data type") TypeError: Cannot handle this data type 

Any ideas how to do this?

like image 917
Cookie Avatar asked Dec 23 '14 14:12

Cookie


People also ask

How do I save a NumPy array in Python?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.


1 Answers

Image needs unsigned bytes, i1 means signed bytes. If the sign is irrelevant (all values between 0 and 127), then this will work:

svimg=im.fromarray(data.astype('uint8')) 

If you need the full range 0-255, you should use 'uint8' throughout.

like image 105
Alex Martelli Avatar answered Sep 25 '22 20:09

Alex Martelli