0

I wish to utilize the easy plotting feature of Matplotlib to generate some bitmaps as templates or (rather large) convolution kernels.

I followed this post to convert the plot into a Numpy array:

def DrawKernel(x = 0.5, y = 0.5, radius = 0.49, dimension = 256):
    '''Make a solid circle and return a numpy array of it'''

    DPI = 100
    figure, axes = plt.subplots(figsize=(dimension/DPI, dimension/DPI), dpi=DPI)
    canvas = FigureCanvas(figure)

    Drawing_colored_circle = plt.Circle(( x, y ), radius, color='k')
    
    axes.set_aspect( 1 )
    axes.axis("off")
    axes.add_artist( Drawing_colored_circle )

    canvas.draw()  

    # Convert figure into an numpy array
    img = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    img = img.reshape(dimension, dimension, 3)

    return img

But this seems to show the plot every time it's called (screenshot in Google Colab) :

enter image description here

Since this function will be invoked frequently later, I don't want to see every plot generated with it. Is there a way to let it be generated but not displayed?

Amarth Gûl
  • 1,040
  • 2
  • 14
  • 33

1 Answers1

1

Just pass visible=False in plt.subplots:

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
def DrawKernel(x = 0.5, y = 0.5, radius = 0.49, dimension = 256):
    '''Make a solid circle and return a numpy array of it'''

    DPI = 100
    figure, axes = plt.subplots(figsize=(dimension/DPI, dimension/DPI), dpi=DPI, visible=False)
    canvas = FigureCanvas(figure)


    Drawing_colored_circle = plt.Circle(( x, y ), radius, color='k')
    
    axes.set_aspect( 1 )
    axes.axis("off")
    axes.add_artist( Drawing_colored_circle )

    canvas.draw()  

    # Convert figure into an numpy array
    img = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    img = img.reshape(dimension, dimension, 3)

    return img
DrawKernel();
TanjiroLL
  • 1,354
  • 1
  • 5
  • 5
  • I tried this method, but Colab still gave me an image output, the difference is that there's nothing in the image, it's blank. I think the visibility only turned off the subplot but not the plot? – Amarth Gûl May 10 '23 at 15:41