Matplotlib figure to image as a numpy array

后端 未结 5 1059
礼貌的吻别
礼貌的吻别 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:34

    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,))
    

提交回复
热议问题