首页 > 解决方案 > Matplotlib fig.canvas.renderer 在 Win 上工作,在 Mac 上失败

问题描述

我有这个功能如下所示。它接收一个 Numpy 数组,其中包含系统摄像头捕获的实时图像,形状通常为 (480, 640, 3)。该函数使用 Pyplot 在图像上绘制一些矩形和标签。然后它尝试将带注释的图像提取回 Numpy 格式,并使用 CV2 显示它。

def draw_boxes(imdata, v_boxes, v_labels, v_scores):
  # load the image
  #data = pyplot.imread(filename)
  # plot the image
  fig, ax = pyplot.subplots()
  ax = pyplot.imshow(imdata)
  # get the context for drawing boxes
  ax = pyplot.gca()
  # plot each box
  for i in range(len(v_boxes)):
    box = v_boxes[i]
    # get coordinates
    y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax
    # calculate width and height of the box
    width, height = x2 - x1, y2 - y1
    # create the shape
    rect = Rectangle((x1, y1), width, height, fill=False, color='red')
    # draw the box
    ax.add_patch(rect)
    # draw text and score in top left corner
    label = "%s (%.3f)" % (v_labels[i], v_scores[i])
    ax.text(x1, y1, label, color='white', bbox=dict(facecolor='blue', alpha=0.3))
  fig.canvas.draw()
  #pyplot.show()
  annotated = np.array(fig.canvas.renderer.buffer_rgba(), dtype=np.uint8)
  pyplot.close('all')
  cv2.imshow('camera', cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB))

Python 3.7、Matplotlib 3.1.1、OpenCV 4.1.1.26、Numpy 1.16.4 - 我在所有系统上都使用相同的版本。

该功能在 Windows 10 上运行良好,我什至可以从中获得不错的帧率。

在 macOS 10.14.6 上,我收到此错误:

Traceback (most recent call last):
  File "sentry.py", line 278, in <module>
    draw_boxes(cvRGBimage, v_boxes, v_labels, v_scores)
  File "sentry.py", line 193, in draw_boxes
    annotated = np.array(fig.canvas.renderer.buffer_rgba(), dtype=np.uint8)
AttributeError: 'FigureCanvasMac' object has no attribute 'renderer'

为什么不一样?

标签: pythonmatplotlib

解决方案


修复很容易。我只需要在导入 matplotlib 模块后添加一行:

import matplotlib
matplotlib.use('TKAgg')

它告诉 matplotlib 使用 TKAgg 后端,这似乎避免了 Mac 上的错误。


推荐阅读