Matplotlib value for numpy array image

I am trying to get a numpy array image from a Matplotlib shape, and currently I am doing this by saving the file and then reading the file again, but I feel there should be a better way. Here is what I am doing now:

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 the example I found, but it gives me an error saying that the object 'FigureCanvasAgg' does not have the attribute 'renderer'.

+13
source share
3 answers

To get the contents of a shape as RGB pixel values, matplotlib.backend_bases.Rendereryou must first draw the contents of the canvas. You can do this by manually calling 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')

. API matplotlib.

+26

:

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))
+6

, , , . , np.fromstring np.frombuffer.

#Image from plot
ax.axis('off')
fig.tight_layout(pad=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,))

, , , fig.tight_layout(pad=0).

0

Source: https://habr.com/ru/post/1628429/


All Articles