Matplotlib:将绘图保存到 numpy 数组 [英] Matplotlib: save plot to numpy array

查看:63
本文介绍了Matplotlib:将绘图保存到 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 和 Matplotlib 中,很容易将绘图显示为弹出窗口或将绘图保存为 PNG 文件.我该如何将绘图保存到 RGB 格式的 numpy 数组中?

In Python and Matplotlib, it is easy to either display the plot as a popup window or save the plot as a PNG file. How can I instead save the plot to a numpy array in RGB format?

推荐答案

当您需要对保存的绘图进行像素到像素的比较时,这是单元测试等的一个方便的技巧.

This is a handy trick for unit tests and the like, when you need to do a pixel-to-pixel comparison with a saved plot.

一种方法是使用 fig.canvas.tostring_rgb,然后使用具有适当 dtype 的 numpy.fromstring.还有其他方法,但这是我倾向于使用的一种.

One way is to use fig.canvas.tostring_rgb and then numpy.fromstring with the approriate dtype. There are other ways as well, but this is the one I tend to use.

例如

import matplotlib.pyplot as plt
import numpy as np

# Make a random plot...
fig = plt.figure()
fig.add_subplot(111)

# If we haven't already shown or saved the plot, then we need to
# draw the figure first...
fig.canvas.draw()

# Now we can save it to a numpy array.
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))

这篇关于Matplotlib:将绘图保存到 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆