我有一个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解决方案,这使得它更加轻量级。)
其他回答
对于那些寻找一个直接的充分工作的例子:
from PIL import Image
import numpy
w,h = 200,100
img = numpy.zeros((h,w,3),dtype=numpy.uint8) # has to be unsigned bytes
img[:] = (0,0,255) # fill blue
x,y = 40,20
img[y:y+30, x:x+50] = (255,0,0) # 50x30 red box
Image.fromarray(img).convert("RGB").save("art.png") # don't need to convert
此外,如果你想要高质量的jpeg .save(file, subsampling=0, quality=100)
与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')
如果你在python环境Spyder中工作,那么它不能比在变量资源管理器中右键单击数组更容易,然后选择显示图像选项。
这将要求您将图像保存到dsik,主要是PNG格式。
在这种情况下不需要PIL库。
你可以在Python中使用'skimage'库
例子:
from skimage.io import imsave
imsave('Path_to_your_folder/File_name.jpg',your_array)
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.