消息“ Matplotlib当前正在使用agg”,并且Matplotlib不显示图像

时间:2019-02-08 05:30:31

标签: python matplotlib tkinter

其他人有这个问题,我使用了他们的解决方案,但没有解决。

我使用virtual env with python3.5Matplotlib安装在virtual env下。 我在系统上安装了python3.tkinter。

当我检查

matplotlib.get_backend()

我有

>>> import matplotlib
>>> matplotlib.get_backend()
'TkAgg'

但是当我运行下面的代码

for image_path in TEST_IMAGE_PATHS:
  image = Image.open(image_path)
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = load_image_into_numpy_array(image)
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.expand_dims(image_np, axis=0)
  # Actual detection.
  output_dict = run_inference_for_single_image(image_np, detection_graph)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks'),
      use_normalized_coordinates=True,
      line_thickness=8)
  #plt.figure(figsize=IMAGE_SIZE)
  plt.imshow(image_np)
  plt.show()

我有问题

 UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  % get_backend())

我把标题放在

from io import StringIO
import matplotlib
matplotlib.rcParams["backend"] = "TkAgg"
from matplotlib import pyplot as plt
from PIL import Image

有人说它已经解决了,但是我仍然有同样的问题,plt没有显示图像。

2 个答案:

答案 0 :(得分:0)

you noted一样,Matplotlib后端sometimes require extra steps to run in virtual environments

话虽如此,上面链接的文档还表明TkAgg应该可用:

  

[...] Tk框架(TkAgg后端)不需要任何外部依赖关系,并且通常始终可用。

我使用Ubuntu,我以为TkAgg将依赖PyGObject。该选项本身有一个注释,可链接到构建说明。

PyGObject build instructions之后,我去安装了它的系统dependencies

sudo apt-get install -y python3-venv python3-wheel python3-dev
sudo apt-get install -y libgirepository1.0-dev build-essential \
  libbz2-dev libreadline-dev libssl-dev zlib1g-dev libsqlite3-dev wget \
  curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libcairo2-dev

然后将以下Python dependencies添加到项目的虚拟环境中:

  • pycairo
  • pygobject
# inside my project's virtual environment
pip install pycairo
pip install pygobject

完成后,像往常一样运行我的项目将显示预期的图形。

注释

  • 我在项目的虚拟环境中使用Ubuntu 18.04.2和Python 3.6.8。

  • 我跳过了有关PyGObject的大多数构建说明,仅做了我上面描述的内容。

答案 1 :(得分:0)

在我的情况下,我通过用PIL Image函数替换pyplot函数来解决了这个问题:

(我的猜测是某些图像格式的函数出现错误)

import matplotlib
matplotlib.use('GTK3Agg')
import matplotlib.pyplot as plt

from PIL import Image


# plt.imshow(image_np)
# plt.show()
img = Image.fromarray(image_np, 'RGB')
img.show()