EDIT # 2
PIL.Image.frombytes('RGB',
fig.canvas.get_width_height(),fig.canvas.tostring_rgb())
与下面的 35/40ms 相比,大约需要 2ms。
这是迄今为止我能找到的最快的方法。
我今天也一直在看这个。
在 matplotlib 文档中 savefig 函数有这个。
pil_kwargsdict,可选传递的附加关键字参数
保存图形时到 PIL.Image.save 。仅适用于格式
使用 Pillow 保存的文件,即 JPEG、TIFF 和(如果关键字是
设置为非 None 值)PNG。
这一定意味着它在保存之前已经是一个 pil 图像,但我看不到它。
你可以按照这个
Matplotlib:将绘图保存到 numpy 数组 https://stackoverflow.com/questions/7821518/matplotlib-save-plot-to-numpy-array
将其放入 numpy 数组然后执行
PIL.Image.fromarray(array)
您可能需要使用数组将通道从 BGR 反转为 RGB[:, :, ::-1]
EDIT:
到目前为止我已经测试了每种方法。
import io
def save_plot_and_get():
fig.savefig("test.jpg")
img = cv2.imread("test.jpg")
return PIL.Image.fromarray(img)
def buffer_plot_and_get():
buf = io.BytesIO()
fig.savefig(buf)
buf.seek(0)
return PIL.Image.open(buf)
def from_canvas():
lst = list(fig.canvas.get_width_height())
lst.append(3)
return PIL.Image.fromarray(np.fromstring(fig.canvas.tostring_rgb(),dtype=np.uint8).reshape(lst))
Results
%timeit save_plot_and_get()
每个循环 35.5 ms ± 148 µs(7 次运行的平均值 ± 标准差,每次 10 个循环)
%timeit save_plot_and_get()
每个循环 35.5 ms ± 142 µs(7 次运行的平均值 ± 标准差,每次 10 个循环)
%timeit buffer_plot_and_get()
每个循环 40.4 ms ± 152 µs(7 次运行的平均值 ± 标准差,每次 10 个循环)