Write numpy ndarray to Image

I am 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 do 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 information about the data type, it says:

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

Then I do some manipulations with the image (in place), after which I want to write the image to a file. I am currently using:

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

but he continues to give 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?

+5
source share
1 answer

Image needs unsigned bytes, i1 means signed bytes. If the sign does not matter (all values ​​are from 0 to 127), then this will work:

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

If you need a full range of 0-255, you should use 'uint8' everywhere.

+9
source

Source: https://habr.com/ru/post/1209776/


All Articles