我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。


当前回答

我附加了一个简单的例程来将npy转换为图像。

from PIL import Image
import matplotlib

img = np.load('flair1_slice75.npy')

matplotlib.image.imsave("G1_flair_75.jpeg", img)

其他回答

scipy。Misc给出关于imsave函数的弃用警告,并建议使用imageio代替。

import imageio
imageio.imwrite('image_name.png', img)

如果你在python环境Spyder中工作,那么它不能比在变量资源管理器中右键单击数组更容易,然后选择显示图像选项。

这将要求您将图像保存到dsik,主要是PNG格式。

在这种情况下不需要PIL库。

这使用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')

您可以使用PyPNG。它是一个纯Python(无依赖)开源PNG编码器/解码器,它支持将NumPy数组写入图像。

对于那些寻找一个直接的充分工作的例子:

from PIL import Image
import numpy

w,h = 200,100
img = numpy.zeros((h,w,3),dtype=numpy.uint8) # has to be unsigned bytes

img[:] = (0,0,255) # fill blue

x,y = 40,20
img[y:y+30, x:x+50] = (255,0,0) # 50x30 red box

Image.fromarray(img).convert("RGB").save("art.png") # don't need to convert

此外,如果你想要高质量的jpeg .save(file, subsampling=0, quality=100)