我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。


当前回答

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

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

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

其他回答

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

这个世界可能不需要另一个包来将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图表中创建动画。

@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的高字节来工作。)

python有opencv(文档在这里)。

import cv2
import numpy as np

img = ... # Your image as a numpy array 

cv2.imwrite("filename.png", img)

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

你可以使用这段代码将你的Npy数据转换成图像:

from PIL import Image
import numpy as np
data = np.load('/kaggle/input/objects-dataset/nmbu.npy')
im = Image.fromarray(data, 'RGB')
im.save("your_file.jpeg")