我正在尝试在 Python 中读取二进制文件(8 位 RGB 元组),对其进行一些转换,然后将其写为 png 图像。我正在执行以下操作:
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
如果我显示 data
的类型信息,它会说:
<type 'numpy.ndarray'>
(512L, 7456L, 3L)
然后我对图像进行一些操作(就地),然后我想将图像写入文件。目前我使用:
import PIL.Image as im
svimg=im.fromarray(data)
svimg.save(("im%05d"%(fileno)),"png")
但它一直给我以下错误:
line 2026, in fromarray
raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type
任何想法如何做到这一点?
最佳答案
Image
需要 unsigned 字节,i1
表示 signed 字节。如果符号不相关(0 到 127 之间的所有值),那么这将起作用:
svimg=im.fromarray(data.astype('uint8'))
如果您需要完整的 0-255 范围,则应始终使用 'uint8'
。
关于python - 将 numpy ndarray 写入 Image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622834/