如何在matplotlib中绘制绘图但不显示

rslzwgfq  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(214)

我希望利用Matplotlib的简单绘图功能来生成一些位图作为模板或(相当大的)卷积核。
我遵循this post将图转换为Numpy数组:

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

但这似乎显示了每次调用的情节(截图在谷歌Colab):

由于这个函数以后会频繁调用,所以我不想看到用它生成的每一个图。有没有办法让它生成但不显示?

z9smfwbn

z9smfwbn1#

只需在plt.subplots中传递visible=False

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();

相关问题