将numpy ndarray写入Image
收藏

我正在尝试在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

If I display the type information of data it says:

<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 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.

    公众号
    关注公众号订阅更多技术干货!