我有一个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))

其他回答

你可以在Python中使用'skimage'库

例子:

from skimage.io import imsave
imsave('Path_to_your_folder/File_name.jpg',your_array)

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

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

from PIL import Image
import matplotlib

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

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

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

与pygame

所以这应该是我测试的(如果你没有pygame,你必须安装pygame,使用pip -> pip install pygame(有时不工作,所以在这种情况下,你必须下载轮子或其他东西,但你可以在谷歌上查找):

import pygame


pygame.init()
win = pygame.display.set_mode((128, 128))
pygame.surfarray.blit_array(win, yourarray)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')

只要记住根据你的数组改变显示的宽度和高度

这是一个例子,运行这段代码:

import pygame
from numpy import zeros


pygame.init()
win = pygame.display.set_mode((128, 128))
striped = zeros((128, 128, 3))
striped[:] = (255, 0, 0)
striped[:, ::3] = (0, 255, 255)
pygame.surfarray.blit_array(win, striped)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')