Python Matplotlib 图形图像为 numpy 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35355930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib figure to image as a numpy array
提问by John Stanford
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:
我正在尝试从 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")
I tried this:
我试过这个:
image = np.fromstring( canvas.tostring_rgb(), dtype='uint8' )
from an example I found but it gives me an error saying that 'FigureCanvasAgg' object has no attribute 'renderer'.
从我发现的一个例子中,但它给了我一个错误,说“FigureCanvasAgg”对象没有属性“renderer”。
采纳答案by ali_m
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()
:
为了将图形内容作为 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 herefor more info on the matplotlib API.
回答by MrE
from the docs:
从文档:
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))
回答by Jorge Diaz
For people who are searching an answer for this question, this is the code gathered from previous answers. Keep in mind that the method np.fromstring
is deprecated and np.frombuffer
is used instead.
对于正在搜索此问题答案的人,这是从以前的答案中收集的代码。请记住,该方法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,))
回答by cdw
回答by starriet
I think there is some update, which is easier.
我认为有一些更新,这更容易。
canvas.draw()
buf = canvas.buffer_rgba()
X = np.asarray(buf)
Updated version from the docs:
来自文档的更新版本:
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)