plt.figure转为ndarray和PIL
本文内容是将matplotlib
生成的figure直接转换为可以操作的ndarray
或PIL
对象.
1. figure转np.ndarray
import numpy as np
def fig2im(fig):
'''
matplotlib.figure.Figure转为np.ndarray
'''
fig.canvas.draw()
w,h = fig.canvas.get_width_height()
buf_ndarray = np.frombuffer(fig.canvas.tostring_rgb(), dtype='u1')
im = buf_ndarray.reshape(h, w, 3)
return im
2. figure转PIL.Image.Image
import numpy as np
from PIL import Image
def fig2img(fig):
'''
matplotlib.figure.Figure转为PIL image
'''
fig.canvas.draw()
w,h = fig.canvas.get_width_height()
# 将Image.frombytes替换为Image.frombuffer,图像会倒置
img = Image.frombytes('RGB', (w,h), fig.canvas.tostring_rgb())
return img