最近在做一个图片相关的训练任务,需要针对随机采样的图片做增强而生成batch,我遇到的一个实际问题便是,我在matplotlib的ax中增加了patches,所以想要获取到叠加了patches的图片数据,一种办法便是 plt.savefig,但是在训练过程中频繁存取图片文件带来效率的损失,于是看了下matplotlib官网,直接获取到未存储的fig图像作为2d的np array。
例子如下:
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
# make a Figure and attach it to a canvas.
fig = plt.Figure(figsize=(5, 5), dpi=128)
fig.set_tight_layout(True) # reduce the spaces from margin outside the axis
canvas = FigureCanvasAgg(fig)
# Do some plotting here
ax = fig.gca()
ax.plot([1, 2, 3])
#ax.set_axis_off()
# Retrieve a view on the renderer buffer
canvas.draw()
buf = canvas.buffer_rgba()
# convert to a NumPy array
X = np.asarray(buf)
plt.imshow(X)
通过FigureCanvasAgg 类的方法可以直接拿到buffer再转换。