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.

Answer from ali_m on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com β€Ί matplotlib-figure-to-image-as-a-numpy-array
Matplotlib figure to image as a numpy array
from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True im = plt.imread("bird.jpg") print("Numpy array of the image is: ", im) im = plt.imshow(im) plt.show() When we execute the code, it will show "bird.jpg" in a plot and show its numpy array on the console.
🌐
Univ-lille
icare.univ-lille.fr β€Ί how-to-convert-a-matplotlib-figure-to-a-numpy-array-or-a-pil-image
How to convert a matplotlib figure to a numpy array or a PIL image – ICARE Data and Services Center
import numpy def fig2data ( fig ): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values """ # draw the renderer fig.canvas.draw ( ) # Get the RGBA buffer from the figure w,h = fig.canvas.get_width_height() buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 ) buf.shape = ( w, h,4 ) # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode buf = numpy.roll ( buf, 3, axis = 2 ) return buf Conversion to a PIL image At this point, we just have to convert the numpy array to a PIL Image to end the conversion.
Discussions

Matplotlib to numpy array
What do you mean, converting matplotlib results to numpy image arrays? You want to load the image produced by matplotlib into a numpy array? It would be slow to save to disk first and then load from disk using numpy, but you could do it. Start there and then look for faster approaches if needed. More on reddit.com
🌐 r/learnpython
19
0
January 29, 2023
Converting matplotlib plot to numpy array
Huh? You already have the array, it's stored in magnitude_spectrogram and later log-transformed. More on reddit.com
🌐 r/learnpython
14
19
August 27, 2023
python - How do I convert a numpy array to (and display) an image? - Stack Overflow
Also, in IPython, you need to run matplotlib.pyplot.show() to show the image display window. 2022-04-09T21:26:21.047Z+00:00 ... Save this answer. ... Show activity on this post. I know there are simpler answers but this one will give you understanding of how images are actually drawn from a numpy array... More on stackoverflow.com
🌐 stackoverflow.com
python - Save plot to numpy array - Stack Overflow
Under this scenario, IO raw buffers ... a matplotlib figure to a numpy array. ... @Epimetheus, isn't it self-explanatory? the world only cares about speed and results' quality, a fast method can save companies. 2022-04-30T21:01:06.38Z+00:00 ... @darda no, it's not needed in plot2 and plot3. Do you see an empty picture? 2022-06-05T06:39:38.123Z+00:00 ... Save this answer. ... Show activity on this post. ... Ofcourse, this code work. But, output numpy array image is so low ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Matplotlib
matplotlib.org β€Ί stable β€Ί tutorials β€Ί images.html
Image tutorial β€” Matplotlib 3.11.2 documentation
We use Pillow to open an image (with PIL.Image.open), and immediately convert the PIL.Image.Image object into an 8-bit (dtype=uint8) numpy array.
🌐
Pluralsight
pluralsight.com β€Ί blog β€Ί tech guides & tutorials
Importing Image Data Into NumPy Arrays | Pluralsight
April 15, 2025 - Just like PIL, it has the image class that performs the same function. Functions used in this piece of code are imread(), which loads the image in the form of an array of the pixel and imshow(), which displays that image.
🌐
Analytics Vidhya
analyticsvidhya.com β€Ί home β€Ί plotting images using matplotlib library in python
Plotting Images Using Matplotlib Library in Python- Analytics Vidhya
February 20, 2025 - Learn how to convert images to NumPy array and plot them using the image sub-module of Matplotlib library in Python to create visualizations
Find elsewhere
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί converting matplotlib plot to numpy array
r/learnpython on Reddit: Converting matplotlib plot to numpy array
August 27, 2023 -

Hey all,

in my code - which is actually longer that what I show here - I'm calculating a magnitude spectrogram of an audio signal. Afterwards, I'm plotting a pcolormesh plot. When I view the spectrogram with matplotlib.pyplot.show(), almost immediately the plot pops up (see below). I measured this with time.time() and the reaction is very quick.

The issue is the following: I need to take this matplotlib.pyplot.pcolormesh and convert it to numpy array image for the purpose of sending it through SpoutGL. I've tried rendering the plot onto a canvas with FigureCanvasAgg. While this does work, it takes too long (around 0.6 sec for HD dimensions - my goal is max 0.05 sec). I've also tried get_array(). This is very fast, but it completely destroys the spectrogram plot into a confusing mix of pixels (see below).

Since the plt.show() reaction is so fast and it does show the pcolormesh as... well, essentially an image, I figured there must be a way to use this and convert the plot somewhat "directly" into a numpy array to be sent through SpoutGL. But I have no idea how. The get_array() failed so far. Is there a way to make get_array() work? Or is there another way? I'd very much appreciate any help. This has been bugging me for days and days (especially since the plot.show() is so quick).

# Calculating and plotting the spectrogram

frequencies, times, magnitude_spectrogram = spectrogram(audio_signal, fs=44100, window=hann, nperseg=2000, noverlap=int(nperseg / 1.2))

spectrogram_fig = matplotlib.pyplot.figure(figsize=(12.8, 7.2), frameon=False)

matplotlib.pyplot.pcolormesh(times, frequencies, 10 * np.log10(magnitude_spectrogram), shading='gouraud', cmap="inferno", vmin=-100, vmax=-30)

matplotlib.pyplot.show()

# Here I need to convert the plot to numpy array

# Sending through SpoutGL

SpoutGL.SpoutSender().sendImage(spectrogram_plot_to_image, 1280, 720, GL.GL_RGB, False, 0)

Show() spectrogram plot: https://postimg.cc/LnX4rgHG

Get_array() result: https://postimg.cc/fV1b7WQp

Edits: formatting

🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί save-plot-to-numpy-array-using-matplotlib
Save Plot To Numpy Array using Matplotlib - GeeksforGeeks
July 23, 2025 - This method involves creating a plot with Matplotlib and saving it to a BytesIO object in memory (as PNG) a temporary buffer in memory, instead of directly to a file. The BytesIO object is then read into a PIL Image, using the Pillow (PIL Fork) ...
🌐
Matplotlib
matplotlib.org β€Ί 2.0.2 β€Ί users β€Ί image_tutorial.html
Image tutorial β€” Matplotlib 2.0.2 documentation
For RGB and RGBA images, matplotlib supports float32 and uint8 data types. For grayscale, matplotlib supports only float32. If your array data does not meet one of these descriptions, you need to rescale it. So, you have your data in a numpy array (either by importing it, or by generating it).
🌐
Matplotlib
matplotlib.org β€Ί stable β€Ί tutorials β€Ί introductory β€Ί images.html
Image tutorial β€” Matplotlib 3.7.2 documentation
August 13, 2021 - We use Pillow to open an image (with PIL.Image.open), and immediately convert the PIL.Image.Image object into an 8-bit (dtype=uint8) numpy array.
🌐
Medium
asofficial14786.medium.com β€Ί create-a-image-by-using-numpy-arrays-and-matplotlib-fdada4732b66
Create a Image by using Numpy ,Arrays and Matplotlib | by Ankit Shukla | Medium
July 31, 2023 - In this article we will discuss about How e can create an image using numpy and matplotlib? To create an image using NumPy and arrays, you can use the numpy library to create a 2D array representing the image and then visualize it using matplotlib.
🌐
Matplotlib
matplotlib.org β€Ί 3.1.1 β€Ί gallery β€Ί misc β€Ί agg_buffer_to_array.html
Agg Buffer To Array β€” Matplotlib 3.1.2 documentation
import matplotlib.pyplot as plt import numpy as np # make an agg figure fig, ax = plt.subplots() ax.plot([1, 2, 3]) ax.set_title('a simple figure') fig.canvas.draw() # grab the pixel buffer and dump it into a numpy array X = np.array(fig.canvas.renderer.buffer_rgba()) # now display the array ...
🌐
scikit-image
scikit-image.org β€Ί skimage-tutorials β€Ί lectures β€Ί 00_images_are_arrays.html
Images are numpy arrays β€” Image analysis in Python
Mostly, we won’t be using input images from the scikit-image example data sets. Those images are typically stored in JPEG or PNG format. Since scikit-image operates on NumPy arrays, any image reader library that provides arrays will do. Options include imageio, matplotlib, pillow, etc.
🌐
GitHub
bic-berkeley.github.io β€Ί psych-214-fall-2016 β€Ί arrays_and_images.html
Arrays as images, images as arrays β€” Functional MRI methods
Matplotlib will treat False as 0 and True as 1, so this is one way of binarizing the image at a threshold (of 50 in this case): ... We can slice arrays as we slice strings or lists. The difference for arrays is that we can slice in any or all dimensions at the same time. For example, to get the dot of the β€œi” it looks (from the numbers at the sides of the ploat) that we want to the top 4 rows, and the last 5 columns:
🌐
Matplotlib
matplotlib.org β€Ί stable β€Ί api β€Ί _as_gen β€Ί matplotlib.pyplot.imread.html
matplotlib.pyplot.imread β€” Matplotlib 3.11.2 documentation
Please open the URL for reading and pass the result to Pillow, e.g. with np.array(PIL.Image.open(urllib.request.urlopen(url))). formatstr, optional Β· The image file format assumed for reading the data. The image is loaded as a PNG file if format is set to "png", if fname is a path or opened file with a ".png" extension, or if it is a URL. In all other cases, format is ignored and the format is auto-detected by PIL.Image.open. Returns: numpy.array Β·
🌐
Univie
teaching.vda.univie.ac.at β€Ί sip β€Ί 19s β€Ί Tutorial β€Ί image_processing.html
Image Processing with NumPy and matplotlib
Please be aware that array slices don't copy the data but provide a view onto the original array. So if we were to change any values in im1_no_alpha, those changes would be reflected in the original im1. Now that we've reduced the images to RGB with 3 channels, we can simply take the mean over those channels to get a grayscale image. NumPy has a function mean, but by default it will return the single mean value of the array:
🌐
Oak-Tree Technologies
oak-tree.tech β€Ί blog β€Ί numpy-images
Modeling Data with NumPy: Images
Encode the image data to a NumPy array using imageio Β· Decompose the image into each of its constituent channels and re-shape the two-dimensional table into a vector that can be used for basic image processing operations, such as creating histograms of pixel intensities. Utilize matplotlib and ...