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

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

本文介绍了Matplotlib图以图像作为一个numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Matplotlib图中获取一个numpy数组图像,我目前正在通过保存到文件中,然后再读回文件的方式来完成此操作,但我觉得必须有一种更好的方法.这是我现在正在做的事情:

I'm trying to get a numpy array image from a Matplotlib figure and I'm currently doing it by saving to a file, then reading the file back in, but I feel like there has to be a better way. Here's what I'm doing now:

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'.

from an example I found but it gives me an error saying that 'FigureCanvasAgg' object has no attribute 'renderer'.

推荐答案

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

In order to get the figure contents as RGB pixel values, the matplotlib.backend_bases.Renderer needs to first draw the contents of the canvas. You can do this by manually calling 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的更多信息.

See here for more info on the matplotlib API.

这篇关于Matplotlib图以图像作为一个numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:23