我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。
当前回答
为了将numpy数组保存为image,你有几个选择:
1)其他优点:OpenCV
进口cv2 cv2。Imwrite('扩展名为。jpg ', numpy_array)
2) Matplotlib
从matplotlib导入pyplot作为PLT plt。Imsave('扩展名为。jpg ', numpy_array)
3)药片
来自PIL import Image image = image .fromarray(numpy_array) 的形象。保存('扩展名为。jpg)')
4)...
其他回答
使用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
@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的高字节来工作。)
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)
我附加了一个简单的例程来将npy转换为图像。
from PIL import Image
import matplotlib
img = np.load('flair1_slice75.npy')
matplotlib.image.imsave("G1_flair_75.jpeg", img)
如果你有matplotlib,你可以这样做:
import matplotlib.pyplot as plt
plt.imshow(matrix) #Needs to be in row,col order
plt.savefig(filename)
这将保存情节(而不是图像本身)。