将numpy ndarray写入Image [英] write numpy ndarray to Image

查看:372
本文介绍了将numpy ndarray写入Image的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中读取二进制文件(8位RGB元组),对其进行一些转换,然后将其写为png图像.我正在执行以下操作:

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:

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的类型信息,则会显示:

If I display the type information of data it says:

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

推荐答案

Image需要 unsigned 个字节,i1表示 signed 个字节.如果该符号无关紧要(所有值都在0到127之间),那么它将起作用:

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'))

如果需要全范围0-255,则应始终使用'uint8'.

If you need the full range 0-255, you should use 'uint8' throughout.

这篇关于将numpy ndarray写入Image的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆