Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I just tried it successfully:

  • install Python on Windows: https://www.python.org/downloads/
  • after the installation, you should have in the user environment variable the path to the Python folder. Something like C:\Users\user\AppData\Local\Programs\Python\Python39\
  • git clone opencv
  • configure using CMake GUI, you should check that the following CMake variables are set to a valid Python folder, e.g. on my machine:

PYTHON3_EXECUTABLE: e.g. C:/Users/user/AppData/Local/Programs/Python/Python39/python.exe PYTHON3_INCLUDE_DIR: e.g. C:/Users/user/AppData/Local/Programs/Python/Python39/include PYTHON3_LIBRARY: e.g. C:/Users/user/AppData/Local/Programs/Python/Python39/libs/python39.lib PYTHON3_NUMPY_INCLUDE_DIRS: e.g. C:/Users/user/AppData/Local/Programs/Python/Python39/lib/site-packages/numpy/core/include

PYTHON3_PACKAGES_PATH: e.g. C:/Users/user/AppData/Local/Programs/Python/Python39/Lib/site-packages

For the test, I have used a custom installation directory for PYTHON3_PACKAGES_PATH, something like: C:/Users/user/opencv/build/install/Python

If you need to install Numpy: open a PowerShell terminal and install Numpy with pip install numpy

Beware, you may encounter the following bug report (as of 2020/11/14) with numpy 1.19.4 and Windows 10 2004.

If so, uninstall Numpy with pip uninstall numpy and install this specific version pip install numpy==1.19.3.

Once CMake has been correctly configured, you should have these CMake variables ticked: BUILD_opencv_python3, BUILD_opencv_python_bindings_generator and BUILD_opencv_python_tests.

Generate the CMake project and open it with Visual Studio. Build in Release mode (CMakeTargets > ALL_BUILD). And install (CMakeTargets > INSTALL).

Now, add to the user environment variables, to the path variable the path to the OpenCV dll: %OpenCV_DIR%\x64\vc16\bin. Here I have added another OpenCV_DIR environment variable that point to the install folder of OpenCV.

Same thing for the PYTHONPATH user environment variable. Create one if needed that point to the directory that contains the Python OpenCV package. See the PYTHON3_PACKAGES_PATH CMake variable.

Now open a new PowerShell terminal. You can check that the environment variables are correctly loaded with (here to print the PYTHONPATH env variable):

echo $env:PYTHONPATH

Now you should be able to run Python OpenCV script, e.g.:

``` import cv2 as cv

print(cv.getBuildInformation()) ```

You can also list the Python packages on your machine:

  • pip install ipython
  • ipython in a PowerShell terminal
  • help('modules')
  • you can also test directly the OpenCV import in the interactive Python