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
Arguments:
*fname*:
A string containing a path to a filename, or a Python file-like object.
If *format* is *None* and *fname* is a string, the output
format is deduced from the extension of the filename.
*arr*:
An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.
46
如果你有matplotlib,你可以这样做:
import matplotlib.pyplot as plt
plt.imshow(matrix) #Needs to be in row,col order
plt.savefig(filename)
import cv2
import numpy as np
cv2.imwrite("filename.png", np.zeros((10,10)))
如果您需要进行除保存以外的更多处理,则非常有用 .
41
@ ideasman42答案的附录:
def saveAsPNG(array, filename):
import struct
if any([len(row) != len(array[0]) for row in array]):
raise ValueError, "Array should have elements of equal size"
#First row becomes top row of image.
flat = []; map(flat.extend, reversed(array))
#Big-endian, unsigned 32-byte integer.
buf = b''.join([struct.pack('>I', ((0xffFFff & i32)<<8)|(i32>>24) )
for i32 in flat]) #Rotate from ARGB to RGBA.
data = write_png(buf, len(array[0]), len(array))
f = open(filename, 'wb')
f.write(data)
f.close()
16 回答
如果你碰巧使用[Py] Qt,你可能会对qimage2ndarray感兴趣 . 从版本1.4(刚发布)开始,PySide也受支持,并且会有一个类似于scipy的小
imsave(filename, array)
函数,但是使用Qt而不是PIL . 使用1.3,只需使用以下内容:(1.4的另一个优点是它是一个纯粹的python解决方案,这使得它更轻巧 . )
如果您在python环境Spyder中工作,那么只需右键单击变量资源管理器中的数组就可以了,然后选择Show Image选项 .
这将要求您将图像保存到dsik,主要是PNG格式 .
在这种情况下不需要PIL库 .
使用
cv2.imwrite
.你可以使用PyPNG . 它是一个纯Python(无依赖关系)开源PNG编码器/解码器,并且它将NumPy数组写为图像supports .
这使用PIL,但也许有些人可能觉得它很有用:
EDIT :当前的
scipy
版本开始标准化所有图像,以便min(数据)变为黑色,max(数据)变为白色 . 如果数据应该是精确的灰度级或精确的RGB通道,则这是不希望的 . 解决方案:使用PIL的答案(以防它有用) .
给出一个numpy数组“A”:
您可以用几乎任何您想要的格式替换"jpeg" . 有关格式的更多详细信息here
纯Python(2和3),没有第三方依赖的片段 .
此函数写入压缩的真彩色(每像素4个字节)
RGBA
PNG ....数据应直接写入以二进制形式打开的文件,如:
Original source
参见:Rust Port from this question.
感谢@Evgeni Sergeev的示例用法:https://stackoverflow.com/a/21034111/432509
使用
matplotlib
:使用matplotlib 1.3.1,我不知道降低版本 . 从文档字符串:
如果你有matplotlib,你可以这样做:
这将保存绘图(不是图像本身) .
python(http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html)有
opencv
.如果您需要进行除保存以外的更多处理,则非常有用 .
@ ideasman42答案的附录:
所以你可以这样做:
制作
test_grid.png
:(透明度也可以,通过减少
0xff
的高字节 . )您可以在Python中使用'skimage'库
例:
matplotlib svn有一个新功能,可以将图像保存为图像 - 没有轴等等 . 如果你不想安装svn(直接从mat.lot中复制,直接从matplotlib svn复制,删除了文档字符串简洁):
世界可能没有足够的,我最近在github上放了
numpngw
:https://github.com/WarrenWeckesser/numpngw
并在pypi上:https://pypi.python.org/pypi/numpngw/
唯一的外部依赖是numpy .
这是存储库的
examples
目录中的第一个示例 . 基本路线很简单其中
img
是一个numpy数组 . 该行之前的所有代码都是import语句和代码来创建img
.这是它创建的PNG文件:
假设你想要一个灰度图像:
scipy.misc
给出了关于imsave
函数的弃用警告,并建议使用imageio
.