我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。
当前回答
如果你在python环境Spyder中工作,那么它不能比在变量资源管理器中右键单击数组更容易,然后选择显示图像选项。
这将要求您将图像保存到dsik,主要是PNG格式。
在这种情况下不需要PIL库。
其他回答
使用cv2.imwrite。
import cv2
assert mat.shape[2] == 1 or mat.shape[2] == 3, 'the third dim should be channel'
cv2.imwrite(path, mat) # note the form of data should be height - width - channel
python有opencv(文档在这里)。
import cv2
import numpy as np
img = ... # Your image as a numpy array
cv2.imwrite("filename.png", img)
如果需要进行除保存以外的更多处理,则非常有用。
如果你在python环境Spyder中工作,那么它不能比在变量资源管理器中右键单击数组更容易,然后选择显示图像选项。
这将要求您将图像保存到dsik,主要是PNG格式。
在这种情况下不需要PIL库。
假设你想要一张灰度图像:
im = Image.new('L', (width, height))
im.putdata(an_array.flatten().tolist())
im.save("image.tiff")
这使用PIL,但是有些人可能会发现它很有用:
import scipy.misc
scipy.misc.imsave('outfile.jpg', image_array)
编辑:当前scipy版本开始规范化所有图像,使min(数据)变成黑色,max(数据)变成白色。如果数据应该是精确的灰色级别或精确的RGB通道,这是不需要的。解决方案:
import scipy.misc
scipy.misc.toimage(image_array, cmin=0.0, cmax=...).save('outfile.jpg')