我试图从Matplotlib图形中获取一个numpy数组图像,目前我正在通过保存到一个文件,然后读回该文件来完成,但我觉得必须有更好的方法。我现在要做的是:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
ax.text(0.0,0.0,"Test", fontsize=45)
ax.axis('off')
canvas.print_figure("output.png")
image = plt.imread("output.png")
我试过这个:
image = np.fromstring( canvas.tostring_rgb(), dtype='uint8' )
从我找到的一个例子中,它给了我一个错误,说“FigureCanvasAgg”对象没有属性“renderer”。
从文档中:
https://matplotlib.org/gallery/user_interfaces/canvasagg.html#sphx-glr-gallery-user-interfaces-canvasagg-py
为了将图形内容获取为RGB像素值,
matplotlib.backend_bases.Renderer
需要首先绘制画布的内容。您可以通过手动调用canvas.draw()
来完成此操作:See here了解有关matplotlib API的更多信息。
要修复大边距的Jorge引用,请添加
ax.margins(0)
。有关详细信息,请参见here。相关问题 更多 >
编程相关推荐