如何使从源代码构建的 OpenCV 3.2 包在 Anaconda 环境中可用?

How to make OpenCV 3.2 package built from source available in Anaconda environment?

我在Windows10下用Visual Studio2017从源代码构建了OpenCV 3.2,它在构建目录中生成了一个文件cv2.cp36-win_amd64.pyd,并将其复制到C:\Users\fanta\Anaconda3\Lib\site-packages.

但是现在,在进入 Python 3.6 的 Anaconda 环境后,python 没有找到包,请看下面的记录(错误在底部):

C:\Users\fanta>conda create -n py36 python=3.6
Fetching package metadata ...........
Solving package specifications: .

Package plan for installation in environment C:\Users\fanta\Anaconda3\envs\py36:

The following NEW packages will be INSTALLED:

    pip:            9.0.1-py36_1
    python:         3.6.1-2
    setuptools:     27.2.0-py36_1
    vs2015_runtime: 14.0.25123-0
    wheel:          0.29.0-py36_0

Proceed ([y]/n)?

#
# To activate this environment, use:
# > activate py36
#
# To deactivate this environment, use:
# > deactivate py36
#
# * for power-users using bash, you must source
#


C:\Users\fanta>activate py36

(py36) C:\Users\fanta>python
Python 3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>>

如果我尝试从任何 Anaconda 环境之外导入 cv2 包,我会得到一个不同的错误,见下文:

(py36) C:\Users\fanta>deactivate py36

C:\Users\fanta>python
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: DLL load failed: The specified module could not be found.
>>>

如何使构建的 cv2 包可以在 Anaconda 环境中导入?

谢谢!

原来 cv2.cp36-win_amd64.pyd 文件的正确位置是(对于我的 py36 Anaconda 环境):

C:\Users\fanta\Anaconda3\envs\py36\Lib

然后我得到了一个ImportError: DLL load failed: The specified module could not be found.

修复导入错误:

  • 将包含 OpenCV 内置 DLL 的目录添加到 PATH 环境变量(C:\opencv32\build\install\x64\vc15\bin 在我的 案例);
  • 设置OPENCV_DIR(在我的C:\opencv32\build\install\x64\vc15 例)。

终于在Anaconda环境下安装了numpy和matplotlib

现在 OpenCV 3.2 从 Visual Studio 2017 的源代码构建。