首页 文章

将Numpy数组保存为图像

提问于
浏览
179

我有一个Numpy数组类型的矩阵 . 我如何将其作为图像写入磁盘?任何格式都有效(png,jpeg,bmp ......) . 一个重要的限制因素是PIL不存在 .

16 回答

  • 2

    如果你碰巧使用[Py] Qt,你可能会对qimage2ndarray感兴趣 . 从版本1.4(刚发布)开始,PySide也受支持,并且会有一个类似于scipy的小 imsave(filename, array) 函数,但是使用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解决方案,这使得它更轻巧 . )

  • 0

    如果您在python环境Spyder中工作,那么只需右键单击变量资源管理器中的数组就可以了,然后选择Show Image选项 .

    enter image description here

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

    在这种情况下不需要PIL库 .

  • 8

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

    你可以使用PyPNG . 它是一个纯Python(无依赖关系)开源PNG编码器/解码器,并且它将NumPy数组写为图像supports .

  • 2

    这使用PIL,但也许有些人可能觉得它很有用:

    import scipy.misc
    scipy.misc.imsave('outfile.jpg', image_array)
    

    EDIT :当前的 scipy 版本开始标准化所有图像,以便min(数据)变为黑色,max(数据)变为白色 . 如果数据应该是精确的灰度级或精确的RGB通道,则这是不希望的 . 解决方案:

    import scipy.misc
    scipy.misc.toimage(image_array, cmin=0.0, cmax=...).save('outfile.jpg')
    
  • 1

    使用PIL的答案(以防它有用) .

    给出一个numpy数组“A”:

    from PIL import Image
    im = Image.fromarray(A)
    im.save("your_file.jpeg")
    

    您可以用几乎任何您想要的格式替换"jpeg" . 有关格式的更多详细信息here

  • 0

    纯Python(2和3),没有第三方依赖的片段 .

    此函数写入压缩的真彩色(每像素4个字节) RGBA PNG .

    def write_png(buf, width, height):
        """ buf: must be bytes or a bytearray in Python3.x,
            a regular string in Python2.x.
        """
        import zlib, struct
    
        # reverse the vertical line order and add null bytes at the start
        width_byte_4 = width * 4
        raw_data = b''.join(
            b'\x00' + buf[span:span + width_byte_4]
            for span in range((height - 1) * width_byte_4, -1, - width_byte_4)
        )
    
        def png_pack(png_tag, data):
            chunk_head = png_tag + data
            return (struct.pack("!I", len(data)) +
                    chunk_head +
                    struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head)))
    
        return b''.join([
            b'\x89PNG\r\n\x1a\n',
            png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
            png_pack(b'IDAT', zlib.compress(raw_data, 9)),
            png_pack(b'IEND', b'')])
    

    ...数据应直接写入以二进制形式打开的文件,如:

    data = write_png(buf, 64, 64)
    with open("my_image.png", 'wb') as fd:
        fd.write(data)
    

  • 210

    使用 matplotlib

    import matplotlib
    
    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.
    

    enter image description here

  • 46

    如果你有matplotlib,你可以这样做:

    import matplotlib.pyplot as plt
    plt.imshow(matrix) #Needs to be in row,col order
    plt.savefig(filename)
    

    这将保存绘图(不是图像本身) .
    enter image description here

  • 27

    python(http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html)有 opencv .

    import cv2
    import numpy as np
    
    cv2.imwrite("filename.png", np.zeros((10,10)))
    

    如果您需要进行除保存以外的更多处理,则非常有用 .

  • 41

    @ 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

    Grid of red, yellow, dark-aqua, grey

    (透明度也可以,通过减少 0xff 的高字节 . )

  • 133

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

    例:

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

    matplotlib svn有一个新功能,可以将图像保存为图像 - 没有轴等等 . 如果你不想安装svn(直接从mat.lot中复制,直接从matplotlib svn复制,删除了文档字符串简洁):

    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)
    
  • 2

    世界可能没有足够的,我最近在github上放了 numpngw

    https://github.com/WarrenWeckesser/numpngw

    并在pypi上:https://pypi.python.org/pypi/numpngw/

    唯一的外部依赖是numpy .

    这是存储库的 examples 目录中的第一个示例 . 基本路线很简单

    write_png('example1.png', img)
    

    其中 img 是一个numpy数组 . 该行之前的所有代码都是import语句和代码来创建 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文件:

    example1.png

  • 4

    假设你想要一个灰度图像:

    im = Image.new('L', (width, height))
    im.putdata(an_array.flatten().tolist())
    im.save("image.tiff")
    
  • 26

    scipy.misc 给出了关于 imsave 函数的弃用警告,并建议使用 imageio .

    import imageio
    imageio.imwrite('image_name.png', img)
    

相关问题