(1)错误描述

出现这种错误OpenCV3.0 和 4.0 都是一样的,不是版本导致的问题,不要在版本中挣扎啦!

最省心最安全最简洁的方式就是下载Anaconda+OpenCV再安装,别用单独的Python了...Python的Python和Anaconda的Python还是有一点点不一样...况且你都用OpenCV做项目了,那不得更加换成Anaconda了吗...

(2)Anaconda4.5.11安装OpenCV4.0.0

  • 查看当前Anaconda的版本和包含的Python解释器的版本:
D:\DevKits\Anaconda3\Scripts>conda info

     active environment : None
       user config file : C:\Users\Seven\.condarc
 populated config files : C:\Users\Seven\.condarc
          conda version : 4.5.11
    conda-build version : 3.15.1
         python version : 3.7.0.final.0
       base environment : D:\DevKits\Anaconda3  (writable)
           channel URLs : https://conda.anaconda.org/conda-forge/win-64
                          https://conda.anaconda.org/conda-forge/noarch
                          https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/free/win-64
                          https://repo.anaconda.com/pkgs/free/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/pro/win-64
                          https://repo.anaconda.com/pkgs/pro/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : D:\DevKits\Anaconda3\pkgs
                          C:\Users\Seven\AppData\Local\conda\conda\pkgs
       envs directories : D:\DevKits\Anaconda3\envs
                          C:\Users\Seven\AppData\Local\conda\conda\envs
                          C:\Users\Seven\.conda\envs
               platform : win-64
             # 由此可知Ananconda的版本是4.5.11, Python的版本的3.7.0
             user-agent : conda/4.5.11 requests/2.19.1 CPython/3.7.0 Windows/10 Windows/10.0.17763
          administrator : False
             netrc file : None
           offline mode : False
# OpenCV的核心包
opencv_python‑4.0.0‑cp37‑cp37m‑win_amd64.whl
# OpenCV的核心包+扩展包
opencv_python‑4.0.0+contrib‑cp37‑cp37m‑win_amd64.whl
  • 离线安装:
D:\DevKits\Anaconda3\Scripts>pip.exe install C:\Users\Seven\Downloads\opencv_python-4.0.0+contrib-cp37-cp37m-win_amd64.whl
Processing c:\users\seven\downloads\opencv_python-4.0.0+contrib-cp37-cp37m-win_amd64.whl
Installing collected packages: opencv-python
    Successfully uninstalled opencv-python-4.0.0
Successfully installed opencv-python-4.0.0+contrib
  • 测试安装:
>>> import cv2
>>> cv2.__version__
'4.0.0'

(3)解决完成后

(4)问题原因

无论是OpenCV3还是OpenCV4,都遇到了同样的问题...当你是用pip安装OpenCV的时候,在PyCharm或VisualStudio中可能不会有代码提示...需要在线安装是可以的,但是步骤麻烦...我就没写...在线安装时pip将OpenCV安装到了Lib/site-packages/cv2中了,而使用离线安装的方式直接安装到Lib/site-packages中,那么:如果采用的在线安装有两种解决方案:

方案一:

在cv2目录中,打开__init__.py文件,修改如下:

sys.modules['cv2'] = cv2

方案二:

导包时使用这样的方式:

from cv2 import cv2 as cv
  • Tips: 如果不是Anaconda安装的Python,Python会在Lib目录查找.