Python 将 numpy ndarray 写入图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27622834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
write numpy ndarray to Image
提问by Cookie
I'm 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'm doing the following:
我正在尝试在 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:
如果我显示它的类型信息data
说:
<type 'numpy.ndarray'>
(512L, 7456L, 3L)
Then I do some manipulation on the image (in-place), afterwards I want to write the Image to a file. Currently I use:
然后我对图像进行一些操作(就地),之后我想将图像写入文件。目前我使用:
import PIL.Image as im
svimg=im.fromarray(data)
svimg.save(("im%05d"%(fileno)),"png")
but it keeps giving 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?
任何想法如何做到这一点?
回答by Alex Martelli
Image
needs unsignedbytes, i1
means signedbytes. If the sign is irrelevant (all values between 0 and 127), then this will work:
Image
需要无符号字节,i1
表示有符号字节。如果符号不相关(0 到 127 之间的所有值),那么这将起作用:
svimg=im.fromarray(data.astype('uint8'))
If you need the full range 0-255, you should use 'uint8'
throughout.
如果您需要 0-255 的全范围,则应'uint8'
始终使用。