Matplotlib figure to image as a numpy array
Solution 1:
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.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.frombuffer(canvas.tostring_rgb(), dtype='uint8')
See here for more info on the Matplotlib API.
Solution 2:
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.
#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,))