我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。
当前回答
假设你想要一张灰度图像:
im = Image.new('L', (width, height))
im.putdata(an_array.flatten().tolist())
im.save("image.tiff")
其他回答
为了将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)...
下面的答案中有@Nima Farhadi在时间测量方面提出的方法。
最快的是CV2,但重要的是要改变颜色顺序从RGB到BGR。简单的是matplotlib。
重要的是要确保数组有unsigned integer format uint8/16/32。
代码:
#Matplotlib
from matplotlib import pyplot as plt
plt.imsave('c_plt.png', c.astype(np.uint8))
#PIL
from PIL import Image
image = Image.fromarray(c.astype(np.uint8))
image.save('c_pil.png')
#CV2, OpenCV
import cv2
cv2.imwrite('c_cv2.png', cv2.cvtColor(c, cv2.COLOR_RGB2BGR))
你可以在Python中使用'skimage'库
例子:
from skimage.io import imsave
imsave('Path_to_your_folder/File_name.jpg',your_array)
对于那些寻找一个直接的充分工作的例子:
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)
我附加了一个简单的例程来将npy转换为图像。
from PIL import Image
import matplotlib
img = np.load('flair1_slice75.npy')
matplotlib.image.imsave("G1_flair_75.jpeg", img)