Issue
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:
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'.
Solution
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()
:
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 for more info on the Matplotlib API.
Answered By - ali_m
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.