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


当前回答

下面的答案中有@Nima Farhadi在时间测量方面提出的方法。

最快的是CV2,但重要的是要改变颜色顺序从RGB到BGR。简单的是matplotlib。

重要的是要确保数组有unsigned integer format uint8/16/32。

代码:

#Matplotlib
from matplotlib import pyplot as plt
plt.imsave('c_plt.png', c.astype(np.uint8))

#PIL
from PIL import Image
image = Image.fromarray(c.astype(np.uint8))
image.save('c_pil.png')


#CV2, OpenCV
import cv2
cv2.imwrite('c_cv2.png', cv2.cvtColor(c, cv2.COLOR_RGB2BGR))

其他回答

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

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

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

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.

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

from PIL import Image
import matplotlib

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

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

如果你碰巧已经在使用[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解决方案,这使得它更加轻量级。)

一个答案使用PIL(只是在情况下它是有用的)。

给定一个numpy数组" a ":

from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")

你可以用几乎任何你想要的格式替换“jpeg”。更多关于格式的细节请点击这里