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

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.

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

如果你在python环境Spyder中工作,那么它不能比在变量资源管理器中右键单击数组更容易,然后选择显示图像选项。

这将要求您将图像保存到dsik,主要是PNG格式。

在这种情况下不需要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的高字节来工作。)