matplotlib运行但不生成图形

时间:2016-05-04 20:01:22

标签: python opencv matplotlib raspberry-pi

我正在尝试完成http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html#using-matplotlib它运行但不显示任何内容

import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

(我正在使用覆盆子pi并按照本教程安装open cv http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/随后我pip安装了matplotlib)

如果我用plt.savefig替换plt.show它会出错吗?

添加导入matplotlib; matplotlib.use('TkAgg')import Tkintertkinter后,

    (cv) pi@raspberrypi:~/Desktop $ python tst4.py
Traceback (most recent call last):
  File "tst4.py", line 5, in <module>
   from matplotlib import pyplot as plt
 File "/home/pi/.virtualenvs/cv/lib/python3.4/site-    packages/matplotlib/pyplot.py", line 114, in <module>
   _backend_mod, new_figure_manager, draw_if_interactive, _show =       pylab_setup()
 File "/home/pi/.virtualenvs/cv/lib/python3.4/site-   packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
   globals(),locals(),[backend_name],0)
 File "/home/pi/.virtualenvs/cv/lib/python3.4/site-   packages/matplotlib/backends/backend_tkagg.py", line 13, in <module>
   import matplotlib.backends.tkagg as tkagg
File "/home/pi/.virtualenvs/cv/lib/python3.4/site-       packages/matplotlib/backends/tkagg.py", line 9, in <module>
  from matplotlib.backends import _tkagg
 ImportError: cannot import name '_tkagg'

1 个答案:

答案 0 :(得分:1)

我自己也遇到过这个问题。问题与matplotlib后端未在虚拟环境中正确设置有关。它花了我很多试验和错误,但你首先需要安装一些依赖项:

$ sudo apt-get install tcl-dev tk-dev python-tk python3-tk

然后手动从源代码安装matplotlib而不是使用pip:

$ workon your_env_name
$ pip uninstall matplotlib
$ git clone https://github.com/matplotlib/matplotlib.git
$ cd matplotlib
$ python setup.py install

这应该解决问题。

我详细介绍了解决方案on this page的完整经验和更多细节。