python 将图转换为numpy数组

j0pj023g  于 2023-06-04  发布在  Python
关注(0)|答案(5)|浏览(289)

我试图从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'。

oprakyz7

oprakyz71#

为了将图形内容作为RGB像素值,matplotlib.backend_bases.Renderer需要首先绘制画布的内容。
您可以手动调用canvas.draw()来完成此操作:

from matplotlib.figure import Figure

fig = Figure()
canvas = fig.canvas
ax = fig.gca()

ax.text(0.0,0.0,"Test", fontsize=45)
ax.axis('off')

canvas.draw()  # Draw the canvas, cache the renderer

image_flat = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')  # (H * W * 3,)
# NOTE: reversed converts (W, H) from get_width_height to (H, W)
image = image_flat.reshape(*reversed(canvas.get_width_height()), 3)  # (H, W, 3)

See here以获取有关Matplotlib API的更多信息。

pkwftd7m

pkwftd7m2#

对于正在搜索此问题答案的人来说,这是从以前的答案中收集的代码。请记住,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,))
wgeznvg7

wgeznvg73#

从docs:
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))
cs7cruho

cs7cruho4#

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

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)
jtjikinw

jtjikinw5#

要修复大边距Jorge引用,请添加ax.margins(0)。详情请看这里。

相关问题