python - 将 numpy ndarray 写入 Image

标签 python image numpy python-imaging-library

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

相关文章:

python - 带有 OMP : can't import module, undefined symbol GOMP_* 的 f2py

python - 如何反转 SQL 查询以到达其 Django 源?

python - C代码转换为python

python - Pandas Dataframe 合并多键

java - 图片太大 : OutOfMemory Exception

python - 根据条件在 numpy 数组中插入值

python - 在 Python 中将变量从一个函数传递到下一个函数

image - 在 Github gist 中查看图像文件的推荐步骤不起作用

r - 更改 image.plot 中的图例刻度

python - 混合 numpy 矩阵和数组的危险