Matplotlib图像作为一个numpy数组

Joh*_*ord 15 python numpy matplotlib

我正在尝试从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")
Run Code Online (Sandbox Code Playgroud)

我试过这个:

image = np.fromstring( canvas.tostring_rgb(), dtype='uint8' )
Run Code Online (Sandbox Code Playgroud)

从我发现的一个例子,但它给我一个错误,说'FigureCanvasAgg'对象没有属性'渲染器'.

ali*_*i_m 29

为了将图形内容作为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')
Run Code Online (Sandbox Code Playgroud)

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

  • 我把img作为1d数组,你可以使用:`width,height = fig.get_size_inches()*fig.get_dpi()`和`img = np.fromstring(canvas.to_string_rgb(),dtype ='uint8')来修复它).reshape(高度,宽度,3)` (27认同)
  • 我有时会收到一个错误,其中高度和宽度为浮点数,但是将它们转换为整数很容易解决。 (2认同)

Jor*_*iaz 19

对于正在搜索此问题答案的人,这是从以前的答案中收集的代码。请记住,该方法np.fromstring已被弃用并np.frombuffer改为使用。

#Image from plot
ax.axis('off')
fig.tight_layout(pad=0)

# To remove the huge white borders
ax.margins(0)

fig.canvas.draw()
image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
image_from_plot = image_from_plot.reshape(fig.canvas.get_width_height()[::-1] + (3,))
Run Code Online (Sandbox Code Playgroud)


MrE*_*MrE 6

从文档:

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))
Run Code Online (Sandbox Code Playgroud)


小智 5

要修复大边距 Jorge 引用,请添加ax.margins(0). 详细信息请参见此处


sta*_*iet 5

我认为有一些更新,这更容易。

canvas.draw()
buf = canvas.buffer_rgba()
X = np.asarray(buf)
Run Code Online (Sandbox Code Playgroud)

来自文档的更新版本:

from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
import numpy as np

# make a Figure and attach it to a canvas.
fig = Figure(figsize=(5, 4), dpi=100)
canvas = FigureCanvasAgg(fig)

# Do some plotting here
ax = fig.add_subplot(111)
ax.plot([1, 2, 3])

# Retrieve a view on the renderer buffer
canvas.draw()
buf = canvas.buffer_rgba()
# convert to a NumPy array
X = np.asarray(buf)
Run Code Online (Sandbox Code Playgroud)