将numpy ndarray写入Imag

2024-06-28 19:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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

有什么办法吗?


Tags: 文件图像datapngtypenphandledtype
1条回答
网友
1楼 · 发布于 2024-06-28 19:22:16

Image需要无符号的字节,i1表示有符号的字节。如果符号不相关(所有值都在0到127之间),则这将起作用:

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

如果需要0-255的完整范围,则应始终使用'uint8'

相关问题 更多 >