AttributeError FigureCanvasAgg object has no attribute renderer

网上的方法没有成功,我尝试了一下新的方法成功,记录一下

使用matplotlib figure转为numpy array或者PIL图像进行显示时,我用到fig.canvas.tostring_rgb()这个函数(https://blog.csdn.net/aa846555831/article/details/52372884),然后报了这个错,使用pycharm。

后来我使用fig.canvas.tostring_argb()好像不会报错,如果报错就按照tostring_rgb()的方式一样进行修改

解决办法1:通过将%PycharmInstallDir%\helpers\pycharm_matplotlib_backend\backend_interagg.py文件中的FigureCanvasAgg类的tostring_rgb方法前面加入self.renderer = self.get_renderer()成功

def tostring_rgb(self):
    '''Get the image as an RGB byte string.

    `draw` must be called at least once before this function will work and
    to update the renderer for any subsequent changes to the Figure.

    Returns
    -------
    bytes
    '''
    self.renderer = self.get_renderer()  # add
    return self.renderer.tostring_rgb()

解决办法2:也可以试试stackoverflow提供的方法:在FigureCanvasAgg类的draw方法前面加入        FigureCanvasAgg.draw(self)

    def draw(self):
        """
        Draw the figure using the renderer.
        """
        FigureCanvasAgg.draw(self)  # add
        self.renderer = self.get_renderer(cleared=True)
        # acquire a lock on the shared font cache
        RendererAgg.lock.acquire()

        toolbar = self.toolbar
        try:
            self.figure.draw(self.renderer)
            # A GUI class may be need to update a window using this draw, so
            # don't forget to call the superclass.
            super().draw()
        finally:
            RendererAgg.lock.release()

参考文献:https://stackoverflow.com/questions/51214140/attributeerror-figurecanvasinteragg-object-has-no-attribute-renderer

 

附上matplotlib figure转为numpy array或者PIL图像进行显示的参考链接:https://blog.csdn.net/guyuealian/article/details/104179723?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

# -*- coding: utf-8 -*-
"""
# --------------------------------------------------------
# @Author : panjq
# @E-mail : pan_jinquan@163.com
# @Date   : 2020-02-05 11:01:49
# --------------------------------------------------------
"""

import matplotlib.pyplot as plt
import numpy as np
import cv2


def fig2data(fig):
    """
    fig = plt.figure()
    image = 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
    """
    import PIL.Image as Image
    # draw the renderer
    fig.canvas.draw()

    # Get the RGBA buffer from the figure
    w, h = fig.canvas.get_width_height()
    buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.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 = np.roll(buf, 3, axis=2)
    image = Image.frombytes("RGBA", (w, h), buf.tostring())
    image = np.asarray(image)
    return image


if __name__ == "__main__":
    # Generate a figure with matplotlib</font>
    figure = plt.figure()
    plot = figure.add_subplot(111)

    # draw a cardinal sine plot
    x = np.arange(1, 100, 0.1)
    y = np.sin(x) / x
    plot.plot(x, y)
    plt.show()
    ##
    image = fig2data(figure)
    cv2.imshow("image", image)
    cv2.waitKey(0)

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读