Matplotlib图形到图像的numpy数组

2024-09-30 20:21:13 发布

您现在位置: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”。


Tags: 文件fromimageimportoutputpngmatplotlibfig
3条回答

从文档中:

https://matplotlib.org/gallery/user_interfaces/canvasagg.html#sphx-glr-gallery-user-interfaces-canvasagg-py

fig = Figure(figsize=(5, 4), dpi=100)
# A canvas must be manually attached to the figure (pyplot would automatically
# do it).  This is done by instantiating the canvas with the figure as
# argument.
canvas = FigureCanvasAgg(fig)

# your plotting here

canvas.draw()
s, (width, height) = canvas.print_to_buffer()

# Option 2a: Convert to a NumPy array.
X = np.fromstring(s, np.uint8).reshape((height, width, 4))

为了将图形内容获取为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')

See here了解有关matplotlib API的更多信息。

要修复大边距的Jorge引用,请添加ax.margins(0)。有关详细信息,请参见here

相关问题 更多 >