Matplotlib figure to image as a numpy array

后端 未结 5 1060
礼貌的吻别
礼貌的吻别 2020-11-28 10:58

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

5条回答
  •  伪装坚强ぢ
    2020-11-28 11:36

    I think there is some update, which is easier.

    canvas.draw()
    buf = canvas.buffer_rgba()
    X = np.asarray(buf)
    

    Updated version from the docs:

    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from matplotlib.figure import Figure
    import numpy as np
    
    # make a Figure and attach it to a canvas.
    fig = Figure(figsize=(5, 4), dpi=100)
    canvas = FigureCanvasAgg(fig)
    
    # Do some plotting here
    ax = fig.add_subplot(111)
    ax.plot([1, 2, 3])
    
    # Retrieve a view on the renderer buffer
    canvas.draw()
    buf = canvas.buffer_rgba()
    # convert to a NumPy array
    X = np.asarray(buf)
    

提交回复
热议问题