一尘不染

Matplotlib图以图像作为一个numpy数组

python

我正在尝试从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”。


阅读 136

收藏
2020-12-20

共1个答案

一尘不染

为了获得图形内容作为RGB像素值,matplotlib.backend_bases.Renderer需要首先绘制画布的内容。您可以通过手动调用canvas.draw()

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.draw()       # draw the canvas, cache the renderer

image = np.fromstring(canvas.tostring_rgb(), dtype='uint8')

有关matplotlib
API的更多信息,请参见此处

2020-12-20