Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib figure to image as a numpy array

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'.

like image 452
John Stanford Avatar asked Feb 12 '16 06:02

John Stanford


People also ask

Can an image could be converted into a NumPy array?

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.

How do I make a matplotlib plot into an image?

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.

How do I display an image array in matplotlib?

We can show arrays as images using the plt. imshow command from matplotlib. Here is the default output: >>> plt.


2 Answers

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.

like image 186
ali_m Avatar answered Sep 19 '22 03:09

ali_m


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,)) 
like image 20
Jorge Diaz Avatar answered Sep 19 '22 03:09

Jorge Diaz