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


当前回答

如果你碰巧已经在使用[Py]Qt,你可能会对qimage2ndarray感兴趣。从版本1.4(刚刚发布)开始,PySide也得到了支持,并且将有一个类似于scipy的微小imsave(文件名,数组)函数,但使用Qt而不是PIL。在1.3版本中,只需使用如下代码:

qImage = array2qimage(image, normalize = False) # create QImage from ndarray
success = qImage.save(filename) # use Qt's image IO functions for saving PNG/JPG/..

(1.4的另一个优点是它是一个纯python解决方案,这使得它更加轻量级。)

其他回答

matplotlib:

import matplotlib.image

matplotlib.image.imsave('name.png', array)

适用于matplotlib 1.3.1,我不知道低版本。从文档字符串:

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.

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

如果你有matplotlib,你可以这样做:

import matplotlib.pyplot as plt
plt.imshow(matrix) #Needs to be in row,col order
plt.savefig(filename)

这将保存情节(而不是图像本身)。

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

from PIL import Image
import matplotlib

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

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

使用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