Matplotlib图像作为一个numpy数组

时间:2016-02-12 06:08:33

标签: 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")

我试过了:

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

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

5 个答案:

答案 0 :(得分:22)

为了将图形内容作为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的更多信息。

答案 1 :(得分:4)

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

canvas.draw()
buf = canvas.buffer_rgba()
X = np.asarray(buf)

文档中的更新版本:

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)

答案 2 :(得分:2)

对于正在寻找该问题答案的人们,这是从先前答案中收集的代码。请记住,方法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,))

答案 3 :(得分:2)

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

答案 4 :(得分:1)

来自文档:

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

foreach ($field_data[$i] as &$field) {                  
            $field_name = $field[0];
            $table = $field[1];
            $table_field_name = $field[2];
            $field_type = $field[3];
            $field_size = $field[4];
            $iteration = $field[5];
            $selector = $field[6];
            $clean = ($iteration >= 0 ? $clean[$table][$iteration][$field_name] : $clean[$table][$field_name]);

            if ($field_type == 'text' || $field_type == 'date') { 
            ....
            } else if ($field_type == 'select') { 
                if($selector != null) {
                    **//This is where the problem is. This results in NULL:
                    // $select[$selector] (or $select[$field[6]])
                    // Meanwhile, $select['names'] works!**
            }
}