我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。
当前回答
@ideasman42回答的附录:
def saveAsPNG(array, filename):
import struct
if any([len(row) != len(array[0]) for row in array]):
raise ValueError, "Array should have elements of equal size"
#First row becomes top row of image.
flat = []; map(flat.extend, reversed(array))
#Big-endian, unsigned 32-byte integer.
buf = b''.join([struct.pack('>I', ((0xffFFff & i32)<<8)|(i32>>24) )
for i32 in flat]) #Rotate from ARGB to RGBA.
data = write_png(buf, len(array[0]), len(array))
f = open(filename, 'wb')
f.write(data)
f.close()
所以你可以这样做:
saveAsPNG([[0xffFF0000, 0xffFFFF00],
[0xff00aa77, 0xff333333]], 'test_grid.png')
生产test_grid.png:
(透明性也可以通过减少0xff的高字节来工作。)
其他回答
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.
Matplotlib SVN有一个新函数,可以将图像保存为图像-没有轴等,这是一个非常简单的函数,如果你不想安装SVN(直接从Matplotlib SVN中的image.py复制,为了简洁,删除了文档字符串):
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None):
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False)
canvas = FigureCanvas(fig)
fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
fig.savefig(fname, dpi=1, format=format)
对于那些寻找一个直接的充分工作的例子:
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)
一个答案使用PIL(只是在情况下它是有用的)。
给定一个numpy数组" a ":
from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")
你可以用几乎任何你想要的格式替换“jpeg”。更多关于格式的细节请点击这里
Imageio是一个Python库,它提供了一个简单的接口来读取和写入广泛的图像数据,包括动画图像、视频、体积数据和科学格式。它是跨平台的,运行在Python 2.7和3.4+上,易于安装。
这是一个灰度图像的例子:
import numpy as np
import imageio
# data is numpy array with grayscale value for each pixel.
data = np.array([70,80,82,72,58,58,60,63,54,58,60,48,89,115,121,119])
# 16 pixels can be converted into square of 4x4 or 2x8 or 8x2
data = data.reshape((4, 4)).astype('uint8')
# save image
imageio.imwrite('pic.jpg', data)