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'.
Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format.
Saving a plot on your disk as an image file Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.
We can show arrays as images using the plt. imshow command from matplotlib. Here is the default output: >>> plt.
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.
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,))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With