我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。
当前回答
与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')
其他回答
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.
一个答案使用PIL(只是在情况下它是有用的)。
给定一个numpy数组" a ":
from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")
你可以用几乎任何你想要的格式替换“jpeg”。更多关于格式的细节请点击这里
这个世界可能不需要另一个包来将numpy数组写入PNG文件,但对于那些无法满足的人,我最近在github上发布了numpngw:
https://github.com/WarrenWeckesser/numpngw
在pypi上:https://pypi.python.org/pypi/numpngw/
唯一的外部依赖项是numpy。
下面是存储库的examples目录中的第一个示例。基本路线很简单
write_png('example1.png', img)
其中img是一个numpy数组。该行之前的所有代码都是导入语句和创建img的代码。
import numpy as np
from numpngw import write_png
# Example 1
#
# Create an 8-bit RGB image.
img = np.zeros((80, 128, 3), dtype=np.uint8)
grad = np.linspace(0, 255, img.shape[1])
img[:16, :, :] = 127
img[16:32, :, 0] = grad
img[32:48, :, 1] = grad[::-1]
img[48:64, :, 2] = grad
img[64:, :, :] = 127
write_png('example1.png', img)
下面是它创建的PNG文件:
另外,我使用了numpngw。write_apng在Voronoi图表中创建动画。
这使用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')
对于那些寻找一个直接的充分工作的例子:
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)