我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是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')
其他回答
这使用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')
一个答案使用PIL(只是在情况下它是有用的)。
给定一个numpy数组" a ":
from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")
你可以用几乎任何你想要的格式替换“jpeg”。更多关于格式的细节请点击这里
为了将numpy数组保存为image,你有几个选择:
1)其他优点:OpenCV
进口cv2 cv2。Imwrite('扩展名为。jpg ', numpy_array)
2) Matplotlib
从matplotlib导入pyplot作为PLT plt。Imsave('扩展名为。jpg ', numpy_array)
3)药片
来自PIL import Image image = image .fromarray(numpy_array) 的形象。保存('扩展名为。jpg)')
4)...
您可以使用PyPNG。它是一个纯Python(无依赖)开源PNG编码器/解码器,它支持将NumPy数组写入图像。
如果你有matplotlib,你可以这样做:
import matplotlib.pyplot as plt
plt.imshow(matrix) #Needs to be in row,col order
plt.savefig(filename)
这将保存情节(而不是图像本身)。