【问题标题】:matplotlib: ImportError: cannot import name 'pyplot'matplotlib:ImportError:无法导入名称'pyplot'
【发布时间】:2015-10-16 04:29:43
【问题描述】:

我使用 pip 安装了 matplotlib 库,但是当我运行此代码时,它给了我这个错误:

shar@shar-Lenovo-G50-30 ~ $ python3 opencv.py
Traceback (most recent call last):
  File "opencv.py", line 3, in <module>
    from matplotlib import pyplot as plt
ImportError: cannot import name 'pyplot'

我的代码是:

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

img1 = cv2.imread('/home/shar/home.jpg',0)  # queryImage
img2 = cv2.imread('/home/shar/home2.jpg',0) # trainImage

# Initiate SIFT detector
orb = cv2.ORB()

# find the keypoints and descriptors with SIFT
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
# create BFMatcher object
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

# Match descriptors.
matches = bf.match(des1,des2)

# Sort them in the order of their distance.
matches = sorted(matches, key = lambda x:x.distance)

# Draw first 10 matches.
img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10], flags=2)

plt.imshow(img3),plt.show()

我还尝试从源代码安装 matplotlib,但仍然出现错误。

【问题讨论】:

  • 你用什么命令来安装它,无论是通过 pip 还是从源代码?您正在使用python3 运行该程序,是否可以为 python 2 安装它?发布pip --version 的输出以查看它使用的是哪个python 版本。
  • 您是否尝试将代码更改为import matplotlib.pyplot as plt?我想你可能在 Python 2 上开发了这段代码,现在正试图在implicit relative imports won't work. 的 Python 3 上运行它
  • 你为什么将你的脚本命名为opencv.py?你碰巧也有matplotlib.py 吗? import matplotlib; print(matplotlib.__file__) 产生了什么?
  • 啊对不起,我忘记了我在 python3 中使用了你的行 import matplotlib.pyplot as plt 并且它可以工作但在 python 2 中不起作用请创建一个答案,我会接受它:)
  • 来自未来的你好。在这里能得到答案真的很好,因为我现在似乎遇到了完全相同的问题。

标签: python opencv matplotlib


【解决方案1】:

确保您没有任何已创建的文件名 matplotlib.py(如果有),然后重命名或删除该文件。它对我有用

【讨论】:

    【解决方案2】:

    您是否收到错误提示“无法从部分初始化的模块 'matplotlib' 导入名称 'pyplot'”?

    您可能在不知不觉中将文件名保存为 matplotlib.py,因为它是默认文件名建议。 所以更改文件名和Bingo,您将不会再出现该错误..

    【讨论】:

    • 这个问题实际上已经在 cmets 中得到了回答。由于 Python 2/3 的差异,这是一个导入错误。
    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2020-02-05
    • 2011-07-11
    • 2018-06-11
    • 2014-11-20
    • 2014-03-04
    相关资源
    最近更新 更多