Opencv python build windows

Keep OpenCV Free

OpenCV is raising funds to keep the library free for everyone, and we need the support of the entire community to do it. Donate to OpenCV on Github to show your support.

  • OpenCV on Wheels
    • Installation and Usage
  • Frequently Asked Questions
  • Documentation for opencv-python
    • CI build process
    • Manual builds
      • Manual debug builds
      • Source distributions
    • Licensing
    • Versioning
    • Releases
    • Development builds
    • Manylinux wheels
    • Supported Python versions
    • Backward compatibility

OpenCV on Wheels

Pre-built CPU-only OpenCV packages for Python.

Check the manual build section if you wish to compile the bindings from source to enable additional modules such as CUDA.

Installation and Usage

  1. If you have previous/other manually installed (= not installed via pip) version of OpenCV installed (e.g. cv2 module in the root of Python’s site-packages), remove it before installation to avoid conflicts.

  2. Make sure that your pip version is up-to-date (19.3 is the minimum supported version): pip install --upgrade pip. Check version with pip -V. For example Linux distributions ship usually with very old pip versions which cause a lot of unexpected problems especially with the manylinux format.

  3. Select the correct package for your environment:

    There are four different packages (see options 1, 2, 3 and 4 below) and you should SELECT ONLY ONE OF THEM. Do not install multiple different packages in the same environment. There is no plugin architecture: all the packages use the same namespace (cv2). If you installed multiple different packages in the same environment, uninstall them all with pip uninstall and reinstall only one package.

    a. Packages for standard desktop environments (Windows, macOS, almost any GNU/Linux distribution)

    • Option 1 — Main modules package: pip install opencv-python
    • Option 2 — Full package (contains both main modules and contrib/extra modules): pip install opencv-contrib-python (check contrib/extra modules listing from OpenCV documentation)

    b. Packages for server (headless) environments (such as Docker, cloud environments etc.), no GUI library dependencies

    These packages are smaller than the two other packages above because they do not contain any GUI functionality (not compiled with Qt / other GUI components). This means that the packages avoid a heavy dependency chain to X11 libraries and you will have for example smaller Docker images as a result. You should always use these packages if you do not use cv2.imshow et al. or you are using some other package (such as PyQt) than OpenCV to create your GUI.

    • Option 3 — Headless main modules package: pip install opencv-python-headless
    • Option 4 — Headless full package (contains both main modules and contrib/extra modules): pip install opencv-contrib-python-headless (check contrib/extra modules listing from OpenCV documentation)
  4. Import the package:

    import cv2

    All packages contain Haar cascade files. cv2.data.haarcascades can be used as a shortcut to the data folder. For example:

    cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

  5. Read OpenCV documentation

  6. Before opening a new issue, read the FAQ below and have a look at the other issues which are already open.

Frequently Asked Questions

Q: Do I need to install also OpenCV separately?

A: No, the packages are special wheel binary packages and they already contain statically built OpenCV binaries.

Q: Pip install fails with ModuleNotFoundError: No module named 'skbuild'?

Since opencv-python version 4.3.0.*, manylinux1 wheels were replaced by manylinux2014 wheels. If your pip is too old, it will try to use the new source distribution introduced in 4.3.0.38 to manually build OpenCV because it does not know how to install manylinux2014 wheels. However, source build will also fail because of too old pip because it does not understand build dependencies in pyproject.toml. To use the new manylinux2014 pre-built wheels (or to build from source), your pip version must be >= 19.3. Please upgrade pip with pip install --upgrade pip.

Q: Import fails on Windows: ImportError: DLL load failed: The specified module could not be found.?

A: If the import fails on Windows, make sure you have Visual C++ redistributable 2015 installed. If you are using older Windows version than Windows 10 and latest system updates are not installed, Universal C Runtime might be also required.

Windows N and KN editions do not include Media Feature Pack which is required by OpenCV. If you are using Windows N or KN edition, please install also Windows Media Feature Pack.

If you have Windows Server 2012+, media DLLs are probably missing too; please install the Feature called «Media Foundation» in the Server Manager. Beware, some posts advise to install «Windows Server Essentials Media Pack», but this one requires the «Windows Server Essentials Experience» role, and this role will deeply affect your Windows Server configuration (by enforcing active directory integration etc.); so just installing the «Media Foundation» should be a safer choice.

If the above does not help, check if you are using Anaconda. Old Anaconda versions have a bug which causes the error, see this issue for a manual fix.

If you still encounter the error after you have checked all the previous solutions, download Dependencies and open the cv2.pyd (located usually at C:\Users\username\AppData\Local\Programs\Python\PythonXX\Lib\site-packages\cv2) file with it to debug missing DLL issues.

Q: I have some other import errors?

A: Make sure you have removed old manual installations of OpenCV Python bindings (cv2.so or cv2.pyd in site-packages).

Q: Function foo() or method bar() returns wrong result, throws exception or crashes interpreter. What should I do?

A: The repository contains only OpenCV-Python package build scripts, but not OpenCV itself. Python bindings for OpenCV are developed in official OpenCV repository and it’s the best place to report issues. Also please check OpenCV wiki and the official OpenCV forum before file new bugs.

Q: Why the packages do not include non-free algorithms?

A: Non-free algorithms such as SURF are not included in these packages because they are patented / non-free and therefore cannot be distributed as built binaries. Note that SIFT is included in the builds due to patent expiration since OpenCV versions 4.3.0 and 3.4.10. See this issue for more info: https://github.com/skvark/opencv-python/issues/126

Q: Why the package and import are different (opencv-python vs. cv2)?

A: It’s easier for users to understand opencv-python than cv2 and it makes it easier to find the package with search engines. cv2 (old interface in old OpenCV versions was named as cv) is the name that OpenCV developers chose when they created the binding generators. This is kept as the import name to be consistent with different kind of tutorials around the internet. Changing the import name or behaviour would be also confusing to experienced users who are accustomed to the import cv2.

Documentation for opencv-python

The aim of this repository is to provide means to package each new OpenCV release for the most used Python versions and platforms.

CI build process

The project is structured like a normal Python package with a standard setup.py file.
The build process for a single entry in the build matrices is as follows (see for example .github/workflows/build_wheels_linux.yml file):

  1. In Linux and MacOS build: get OpenCV’s optional C dependencies that we compile against

  2. Checkout repository and submodules

    • OpenCV is included as submodule and the version is updated
      manually by maintainers when a new OpenCV release has been made
    • Contrib modules are also included as a submodule
  3. Find OpenCV version from the sources

  4. Build OpenCV

    • tests are disabled, otherwise build time increases too much
    • there are 4 build matrix entries for each build combination: with and without contrib modules, with and without GUI (headless)
    • Linux builds run in manylinux Docker containers (CentOS 5)
    • source distributions are separate entries in the build matrix
  5. Rearrange OpenCV’s build result, add our custom files and generate wheel

  6. Linux and macOS wheels are transformed with auditwheel and delocate, correspondingly

  7. Install the generated wheel

  8. Test that Python can import the library and run some sanity checks

  9. Use twine to upload the generated wheel to PyPI (only in release builds)

Steps 1—4 are handled by pip wheel.

The build can be customized with environment variables. In addition to any variables that OpenCV’s build accepts, we recognize:

  • CI_BUILD. Set to 1 to emulate the CI environment build behaviour. Used only in CI builds to force certain build flags on in setup.py. Do not use this unless you know what you are doing.
  • ENABLE_CONTRIB and ENABLE_HEADLESS. Set to 1 to build the contrib and/or headless version
  • ENABLE_JAVA, Set to 1 to enable the Java client build. This is disabled by default.
  • CMAKE_ARGS. Additional arguments for OpenCV’s CMake invocation. You can use this to make a custom build.

See the next section for more info about manual builds outside the CI environment.

Manual builds

If some dependency is not enabled in the pre-built wheels, you can also run the build locally to create a custom wheel.

  1. Clone this repository: git clone --recursive https://github.com/opencv/opencv-python.git
  2. cd opencv-python
    • you can use git to checkout some other version of OpenCV in the opencv and opencv_contrib submodules if needed
  3. Add custom Cmake flags if needed, for example: export CMAKE_ARGS="-DSOME_FLAG=ON -DSOME_OTHER_FLAG=OFF" (in Windows you need to set environment variables differently depending on Command Line or PowerShell)
  4. Select the package flavor which you wish to build with ENABLE_CONTRIB and ENABLE_HEADLESS: i.e. export ENABLE_CONTRIB=1 if you wish to build opencv-contrib-python
  5. Run pip wheel . --verbose. NOTE: make sure you have the latest pip version, the pip wheel command replaces the old python setup.py bdist_wheel command which does not support pyproject.toml.
    • this might take anything from 5 minutes to over 2 hours depending on your hardware
  6. Pip will print fresh wheel location at the end of build procedure. If you use old approach with setup.py file wheel package will be placed in dist folder. Package is ready and you can do with that whatever you wish.
    • Optional: on Linux use some of the manylinux images as a build hosts if maximum portability is needed and run auditwheel for the wheel after build
    • Optional: on macOS use delocate (same as auditwheel but for macOS) for better portability

Manual debug builds

In order to build opencv-python in an unoptimized debug build, you need to side-step the normal process a bit.

  1. Install the packages scikit-build and numpy via pip.
  2. Run the command python setup.py bdist_wheel --build-type=Debug.
  3. Install the generated wheel file in the dist/ folder with pip install dist/wheelname.whl.

If you would like the build produce all compiler commands, then the following combination of flags and environment variables has been tested to work on Linux:

export CMAKE_ARGS='-DCMAKE_VERBOSE_MAKEFILE=ON'
export VERBOSE=1

python3 setup.py bdist_wheel --build-type=Debug

See this issue for more discussion: https://github.com/opencv/opencv-python/issues/424

Source distributions

Since OpenCV version 4.3.0, also source distributions are provided in PyPI. This means that if your system is not compatible with any of the wheels in PyPI, pip will attempt to build OpenCV from sources. If you need a OpenCV version which is not available in PyPI as a source distribution, please follow the manual build guidance above instead of this one.

You can also force pip to build the wheels from the source distribution. Some examples:

  • pip install --no-binary opencv-python opencv-python
  • pip install --no-binary :all: opencv-python

If you need contrib modules or headless version, just change the package name (step 4 in the previous section is not needed). However, any additional CMake flags can be provided via environment variables as described in step 3 of the manual build section. If none are provided, OpenCV’s CMake scripts will attempt to find and enable any suitable dependencies. Headless distributions have hard coded CMake flags which disable all possible GUI dependencies.

On slow systems such as Raspberry Pi the full build may take several hours. On a 8-core Ryzen 7 3700X the build takes about 6 minutes.

Licensing

Opencv-python package (scripts in this repository) is available under MIT license.

OpenCV itself is available under Apache 2 license.

Third party package licenses are at LICENSE-3RD-PARTY.txt.

All wheels ship with FFmpeg licensed under the LGPLv2.1.

Non-headless Linux wheels ship with Qt 5 licensed under the LGPLv3.

The packages include also other binaries. Full list of licenses can be found from LICENSE-3RD-PARTY.txt.

Versioning

find_version.py script searches for the version information from OpenCV sources and appends also a revision number specific to this repository to the version string. It saves the version information to version.py file under cv2 in addition to some other flags.

Releases

A release is made and uploaded to PyPI when a new tag is pushed to master branch. These tags differentiate packages (this repo might have modifications but OpenCV version stays same) and should be incremented sequentially. In practice, release version numbers look like this:

cv_major.cv_minor.cv_revision.package_revision e.g. 3.1.0.0

The master branch follows OpenCV master branch releases. 3.4 branch follows OpenCV 3.4 bugfix releases.

Development builds

Every commit to the master branch of this repo will be built. Possible build artifacts use local version identifiers:

cv_major.cv_minor.cv_revision+git_hash_of_this_repo e.g. 3.1.0+14a8d39

These artifacts can’t be and will not be uploaded to PyPI.

Manylinux wheels

Linux wheels are built using manylinux2014. These wheels should work out of the box for most of the distros (which use GNU C standard library) out there since they are built against an old version of glibc.

The default manylinux2014 images have been extended with some OpenCV dependencies. See Docker folder for more info.

Supported Python versions

Python 3.x compatible pre-built wheels are provided for the officially supported Python versions (not in EOL):

  • 3.7
  • 3.8
  • 3.9
  • 3.10
  • 3.11
  • 3.12

Backward compatibility

Starting from 4.2.0 and 3.4.9 builds the macOS Travis build environment was updated to XCode 9.4. The change effectively dropped support for older than 10.13 macOS versions.

Starting from 4.3.0 and 3.4.10 builds the Linux build environment was updated from manylinux1 to manylinux2014. This dropped support for old Linux distributions.

Starting from version 4.7.0 the Mac OS GitHub Actions build environment was update to version 11. Mac OS 10.x support deprecated. See https://github.com/actions/runner-images/issues/5583

Starting from version 4.9.0 the Mac OS GitHub Actions build environment was update to version 12. Mac OS 10.x support deprecated by Brew and most of used packages.

Last Updated :
07 Aug, 2024

Prerequisite: Python Language Introduction   OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries, such as Numpy, python is capable of processing the OpenCV array structure for analysis. To Identify image patterns and its various features we use vector space and perform mathematical operations on these features. To install OpenCV, one must have Python and PIP, preinstalled on their system. To check if your system already contains Python, go through the following instructions: Open the Command line(search for cmd in the Run dialog( + R). Now run the following command:

python --version

If Python is already installed, it will generate a message with the Python version available.

python-version-check-windows

If Python is not present, go through How to install Python on Windows? and follow the instructions provided.   PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI). To check if PIP is already installed on your system, just go to the command line and execute the following command:

pip -V

Verification of pip

If PIP is not present, go through How to install PIP on Windows? and follow the instructions provided.

Downloading and Installing OpenCV:

OpenCV can be directly downloaded and installed with the use of pip (package manager). To install OpenCV, just go to the command-line and type the following command:

pip install opencv-python

Beginning with the installation:

To check if OpenCV is correctly installed, just run the following commands to perform a version check:

python
>>>import cv2
>>>print(cv2.__version__)

OpenCV-Verification

Introduction and Overview

This document contains instructions for installing and migrating to the latest release of OpenCV (version 3) and the Python bindings. In addition to some API changes, there are also changes to the Python interface (e.g. removal of cv2.cv) that may require changes in existing code to work with the new version of the cv2 module. After installation, see the next page, Migration & Changes, for details regarding the changes to the module and for help migrating existing Python code to the new version.


This page covers installing OpenCV 3 on Windows (using pre-built binaries) and Linux (compiled from source), including the Python interface (the cv2 module). OpenCV can be downloaded from the official OpenCV website. Note that this guide is written based on OpenCV version 3.1.0. After installation, it is recommended that you can check the version of OpenCV that Python is using:

import cv2
print cv2.__version__

# Should print 3.0.0-rc1 or newer.

Note that although OpenCV 3 is the latest release, by convention, the module is still named cv2.


Installing on Windows (pre-built binaries)

Using pre-built binaries is the quickest way to get a Python OpenCV environment up and running on Windows. Currently, only the Python 2 version of the cv2 module is built and included in the latest Windows release. Support for Python 3 (as well as adding other non-standard features/modules), requires compiling from source — see the official OpenCV documentation for details.

Downloading OpenCV and Python

To begin, download OpenCV for Windows (version 3.1, opencv-3.1.0.exe), and extract it to a directory of your choice. The Windows build includes both a 32-bit and 64-bit module for Python 2.7.

Before continuing, ensure that you have a working Python 2.7 installation, which can be downloaded from the Python website. This guide was tested using Python 2.7.9 (x86 installer / x64 installer). When installing, it is recommended that you allow the installer to add Python to your PATH environment variable, so you can run python and pip from a command prompt.

Installing Module Dependencies

The Python OpenCV cv2 module requires both the NumPy and SciPy stack. To get this, first ensure that you have a working python environment, and have pip installed (if not, use the links above, and ensure the Python folder is in your PATH variable).

Christoph Gohlke currently provides some (unofficial) pre-built Python packages for Windows, including NumPy and SciPy. Download the latest stable versions of NumPy and SciPy, and install them by calling pip install [module].whl from a command prompt. Note that you should download the version corresponding to your Python environment (2.7 in this case) and word length. For example, on 32-bit systems/interpreters:

pip install numpy-1.9.2+mkl-cp27-none-win32.whl
pip install scipy-0.15.1-cp27-none-win32.whl

And for 64-bit systems/interpreters:

pip install numpy-1.9.2+mkl-cp27-none-win_amd64.whl
pip install scipy-0.15.1-cp27-none-win_amd64.whl

After installing, you should be able to run import numpy and import scipy from a Python interpreter to verify that the modules were installed correctly. You can check what versions of NumPy and SciPy are installed from numpy.__version__ and scipy.__version__, respectively.

Installing Python-OpenCV Module

Lastly, we need to copy the OpenCV module into the local Python packages. In the files extracted from opencv-3.0.0-rc1.exe, go to the folder opencv\build\python\2.7\, and open either the x86\ (for 32-bit) or x64\ (for 64-bit) folder. In each, there will be a cv2.pyd file.

Copy cv2.pyd directly into the Lib\site-packages\ directory of your Python installation. For most users, this will be found at:

C:\Python27\Lib\site-packages 

Lastly, ensure that the OpenCV .dll files are somewhere in your system’s %PATH%, especially the opencv_ffmpeg310.dll (or opencv_ffmpeg310_64.dll for 64-bit systems) file required for loading video files.

Continue on to the Verifying Installation section to ensure everything was installed correctly, and the new version of OpenCV is being used. Also be sure to check out the next page, Migration & Changes, for details about the changes to the module and updating existing code.


Installing on Linux (compiling from source)

Although this guide is written for Ubuntu 12.04/14.04 and other variants (e.g. Xubuntu/Lubuntu/Kubuntu), the process should largely be the same on other versions, as well as similar Debian-like Linux distributions. Pay attention to the output of each command to ensure everything worked correctly, and if there are any issues during the build process, see the bottom of this document for possible mitigations

Downloading OpenCV

To begin, download OpenCV for Linux (version 3.1.0, opencv-3.1.0.zip), and extract it to a directory of your choice (e.g. ~/opencv-src). Create a build folder inside the folder where the archive was extracted (the directory containing the CMakeLists.txt file), and open a terminal session there. For example:

# Assuming the files were extracted to ~/opencv-src/...
cd ~/opencv-src
mkdir build
cd build

Execute all of following commands from the build sub-folder itself, so the compiled files will be placed there.

Installing Build Dependencies

To compile OpenCV, we must ensure that the required dependencies are available, including the build tools themselves. We can get the required ones using apt on Ubuntu, but first, ensure the package list is up-to-date by running apt-get update. Next, execute the following commands to get the required packages (see below for a one-line list of all):

sudo apt-get install cmake build-essential pkg-config

sudo apt-get install libgtk2.0-dev libtbb-dev

sudo apt-get install python-dev python-numpy python-scipy

sudo apt-get install libjasper-dev libjpeg-dev libpng-dev libtiff-dev 

sudo apt-get install libavcodec-dev libavutil-dev libavformat-dev libswscale-dev

sudo apt-get install libdc1394-22-dev libv4l-dev

In single line:

sudo apt-get install cmake build-essential pkg-config libgtk2.0-dev libtbb-dev python-dev python-numpy python-scipy libjasper-dev libjpeg-dev libpng-dev libtiff-dev libavcodec-dev libavutil-dev libavformat-dev libswscale-dev libdc1394-22-dev libv4l-dev

Note that for additional OpenCV modules/features (e.g. GPU/CUDA support, or Python 3 module), you will need to download the respective development/SDK packages for those libraries as well. The dependencies listed above only cover building OpenCV itself and the Python 2.7 cv2 module.

Compiling and Installing OpenCV

Now that we have the required build dependencies, run cmake (again, in the build/ directory we created) to generate the Makefile to build OpenCV:

cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..

If there are any errors, ensure that you downloaded all the required packages — the output should help track down what is missing. To ensure the Python module will be built, you should see python2 in the list of configured modules after running cmake:

[...]

--     Linker flags (Release):
--     Linker flags (Debug):
--     Precompiled headers:      YES
--
--   OpenCV modules:
--     To be built:              hal core flann imgproc ml [...] python2

[...]

If you do not see the python2 module listed, in the «To be built» list, check that you have the proper Python development packages installed, remove all files from the build/ folder, and try running the cmake command again.

Now, we can build OpenCV (and the Python module) using make, and install it to our system:

make
sudo make install

Ensure that the build was successful after calling make, and check the output before installing. If you run into build issues/errors, again ensure that you have all the required dependencies and header files on your system. If there are actual build issues with OpenCV itself, see the Linux Build Issues section below for some possible workarounds.

When installing OpenCV 3.0-rc1 on Ubuntu 12.04, I ran into build errors regarding some missing codec #define entries. As mentioned, the steps to do this are detailed below should you run into the same problem (the problem should be solved in version 3.1.0 and above). Ubuntu 14.04 and above should build successfully without requiring any modifications.

If the build was successful, but you can’t import cv2 from a Python shell after running make install, you can install the module manually by copying the cv2.so file we just built in the build/lib/ folder to /usr/local/lib/python2.7/dist-packages/. From the build/ folder, this can be done by:

sudo cp lib/cv2.so /usr/local/lib/python2.7/dist-packages/

After this step, the cv2 module is installed, and can now be imported by your Python environment. Continue on to the Verifying Installation section to ensure everything was installed correctly, and more importantly, that the correct version of OpenCV is being used by Python. You can also check out the next page, Migration & Changes, for details about changes to the cv2 module, and what changes need to be made to existing code to run with the updated module.


Verifying Installation

As mentioned previously, you can verify that the cv2 module was installed correctly by executing the following in a Python shell:

import cv2
print cv2.__version__

If the correct version string is printed (3.0.0-rc1 or newer if you used a more recent version), everything is installed correctly at this point!

Note that there are some major changes to the cv2 module hierarchy itself, and Python programs written with OpenCV 2.4.x in mind may not work properly anymore. See the next section, Migration & Changes for details about the changes, and how to modify programs to deal with the changes.


Linux Build Issues

On some systems you may run into issues when compiling OpenCV itself, depending on what packages are available. If the proper header files are available, but build issues still arise, try to see if there are any workarounds below for the problem.

Undefined AV_CODEC_ID_... in ffmpeg_codecs.hpp

If you run into an issue where build errors are caused by certain codecs not being defined, you can download a more recent version of ffmpeg_codecs.hpp from here, and replace it in the source code you downloaded/extracted in the modules/videoio/src/ folder.

Alternatively, you can declare them manually by editing the ffmpeg_codecs.hpp file itself by adding the missing codec entry for H263I, and renaming WNV to WNV1. You can see what changes have to be made by viewing this commit from the OpenCV GitHub project.

Once the file is updated, you can call make again from the build/ folder, and OpenCV should finish compiling without error now.

OpenCV with CUDA

Why manually build OpenCV?

The pre-built Windows libraries available for OpenCV do not include the CUDA modules, support for the Nvidia Video Codec SDK or cuDNN.

If you just need the Windows libraries or a Python wheel take a look at OpenCV C++ CUDA builds and/or OpenCV Python CUDA wheels to see if there is a pre-built version suitable for your setup.

To see if building the OpenCV CUDA modules is suitable for your application you can get an indication of the performance boost of most functions in OpenCV CUDA Performance Comparison (Nvidia vs Intel).

Before you begin quickly check which parts of the guide are relevant to you

  1. This guide assumes you are building the latest stable release of OpenCV against the most recent CUDA dependencies. Whilst the instructions can also work on older versions, this is not guaranteed so please update to the latest stable releases before raising any issues.

  2. If you just need the OpenCV binaries or a Python wheel which includes the CUDA modules, check OpenCV C++ CUDA builds and/or OpenCV Python CUDA wheels first to see if they are available for your desired combination of OpenCV and CUDA.

  3. If you have previously built and/or are trying to manually install the Python bindings and are facing errors check out the troubleshooting Python bindings installation issues and manually installing OpenCV Python bindings sections first.

  4. If you already have the OpenCV source and the required dependencies and are just looking for the CMake flags they can be found here.

Prerequisites

There are a couple of components you need to download and/or install before you can get started, you first need to:

  1. Install the latest version of Visual Studio, selecting the Desktop development with C++ workload shown in the image below. If you already have an installation ensure that the correct workload is installed and that you have updated to the latest version.

    Visual Studio Select C++ Workload
  2. Download the source files1 for OpenCV from GitHub by either cloning the repositories (opencv and opencv_contrib) or or downloading the archives containing the source files (opencv.zip and opencv_contirib.zip)

  1. Install the latest stable (not release candidate -rc) version of CMake.

  2. Install the latest version of the CUDA Toolkit.

If your system path is too long, CUDA will not add the path to its shared libraries C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vxx.x\bin during installation. If you receive a warning about this at the end of the installation process do not forget to manually add the this to your system or user path.

  1. Optional2 — To decode video on the GPU with the Nvidia Video Codec SDK:
    1. Register and download the latest version of the Complete Video Codec SDK xx.x Package.
    2. Extract and copy the contents of Interface and Lib to the include and lib directories inside your CUDA installation.
  2. Optional — To use the DNN CUDA backend:
    1. Register and download the latest version of cuDNN for the version of CUDA you have installed by selecting the Tarball.
    2. Extract and copy the bin, include and lib directories to your CUDA installation.

The installation directory for CUDA xx.x is C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vxx.x.

  1. Optional3 – To call OpenCV CUDA routines from python, install the latest x64 bit version of miniforge with numpy (execute mamba install numpy from the miniforge prompt once miniforge is installed.)

Building OpenCV with CMake

Before you can build OpenCV you have to generate the build files with CMake. This can be done via the command line or with the CMake GUI. Most new users will find the GUI more accessible however by far the quickest, easiest and least error prone way to proceed is to call CMake from the command line and as a result I have not included any instructions for using the CMake GUI4.

In addition there are several ways to build OpenCV using Visual Studio. For simplicity only two methods are discussed:

  1. Building OpenCV with Visual Studio solution files.
  2. Building OpenCV with the ninja build system to reduce the build time.

Building OpenCV with CUDA using Visual Studio solution files from the command prompt (cmd)

The following steps will build opencv_worldxxx.dll which is suitable for use on the installed GPU and any other GPUs with the “same” compute capability. This is the best way to get started as it has the smallest build time, but it will limit your options if you want to build software which runs on a range of different GPUs. To fully understand the implications of this please read choosing a suitable CUDA compute capability.

Use Ninja for faster build times

Visual Studio is painfully slow when compiling OpenCV with CUDA, to reduce the build time I recommended always using the Ninja build system instead, see the Ninja tab below for the command line arguments and building OpenCV with the ninja build system to reduce the build time for more information.

  1. Open windows command prompt, type cmd in the Windows search bar.
  1. Paste the below5 into to the command prompt and press Enter.

    • All CUDA modules
    • cuDNN only
    • Without Python bindings
    • Without CUDA
    • Ninja
    set CMAKE_BUILD_PARALLEL_LEVEL=<N_THREADS>
    "C:\Program Files\CMake\bin\cmake.exe" -H"<PATH_TO_OPENCV_SOURCE>" -DOPENCV_EXTRA_MODULES_PATH="<PATH_TO_OPENCV_CONTRIB_MODULES>" -B"<PATH_TO_BUILD_DIR>" -G"Visual Studio 17 2022" -DINSTALL_TESTS=ON -DINSTALL_C_EXAMPLES=ON -DBUILD_EXAMPLES=ON -DBUILD_opencv_world=ON -DENABLE_CUDA_FIRST_CLASS_LANGUAGE=ON -DWITH_CUDA=ON -DCUDA_GENERATION=Auto -DBUILD_opencv_python3=ON -DPYTHON3_INCLUDE_DIR=<PATH_TO_PYTHON_DIST>/include -DPYTHON3_LIBRARY=<PATH_TO_PYTHON_DIST>/libs/<PYTHON_Lib> -DPYTHON3_EXECUTABLE=<PATH_TO_PYTHON_DIST>/python.exe -DPYTHON3_NUMPY_INCLUDE_DIRS=<PATH_TO_PYTHON_DIST>/lib/site-packages/numpy/core/include -DPYTHON3_PACKAGES_PATH=<PATH_TO_PYTHON_DIST>/Lib/site-packages/

    If you just want to CUDA accelerate the DNN module and are not interested in building the rest of the CUDA modules this will significantly reduce compilation time and size of opencv_worldxxx.dll.

    set CMAKE_BUILD_PARALLEL_LEVEL=<N_THREADS>
    "C:\Program Files\CMake\bin\cmake.exe" -H"<PATH_TO_OPENCV_SOURCE>" -DOPENCV_EXTRA_MODULES_PATH="<PATH_TO_OPENCV_CONTRIB_MODULES>" -B"<PATH_TO_BUILD_DIR>" -G"Visual Studio 17 2022" -DINSTALL_TESTS=ON -DINSTALL_C_EXAMPLES=ON -DBUILD_EXAMPLES=ON -DBUILD_opencv_world=ON -DENABLE_CUDA_FIRST_CLASS_LANGUAGE=ON -DWITH_CUDA=ON -DCUDA_GENERATION=Auto -DBUILD_opencv_cudaarithm=OFF -DBUILD_opencv_cudabgsegm=OFF -DBUILD_opencv_cudafeatures2d=OFF -DBUILD_opencv_cudafilters=OFF -DBUILD_opencv_cudaimgproc=OFF -DBUILD_opencv_cudalegacy=OFF -DBUILD_opencv_cudaobjdetect=OFF -DBUILD_opencv_cudaoptflow=OFF -DBUILD_opencv_cudastereo=OFF -DBUILD_opencv_cudawarping=OFF -DBUILD_opencv_cudacodec=OFF -DBUILD_opencv_python3=ON -DPYTHON3_INCLUDE_DIR=<PATH_TO_PYTHON_DIST>/include -DPYTHON3_LIBRARY=<PATH_TO_PYTHON_DIST>/libs/<PYTHON_Lib> -DPYTHON3_EXECUTABLE=<PATH_TO_PYTHON_DIST>/python.exe -DPYTHON3_NUMPY_INCLUDE_DIRS=<PATH_TO_PYTHON_DIST>/lib/site-packages/numpy/core/include -DPYTHON3_PACKAGES_PATH=<PATH_TO_PYTHON_DIST>/Lib/site-packages/
    set CMAKE_BUILD_PARALLEL_LEVEL=<N_THREADS>
    "C:\Program Files\CMake\bin\cmake.exe" -H"<PATH_TO_OPENCV_SOURCE>" -DOPENCV_EXTRA_MODULES_PATH="<PATH_TO_OPENCV_CONTRIB_MODULES>" -B"<PATH_TO_BUILD_DIR>" -G"Visual Studio 17 2022" -DINSTALL_TESTS=ON -DINSTALL_C_EXAMPLES=ON -DBUILD_EXAMPLES=ON -DBUILD_opencv_world=ON -DENABLE_CUDA_FIRST_CLASS_LANGUAGE=ON -DWITH_CUDA=ON -DCUDA_GENERATION=Auto
    set CMAKE_BUILD_PARALLEL_LEVEL=<N_THREADS>
    "C:\Program Files\CMake\bin\cmake.exe" -H"<PATH_TO_OPENCV_SOURCE>" -DOPENCV_EXTRA_MODULES_PATH="<PATH_TO_OPENCV_CONTRIB_MODULES>" -B"<PATH_TO_BUILD_DIR>" -G"Visual Studio 17 2022" -DINSTALL_TESTS=ON -DINSTALL_C_EXAMPLES=ON -DBUILD_EXAMPLES=ON -DBUILD_opencv_world=ON -DBUILD_opencv_python3=ON -DPYTHON3_INCLUDE_DIR=<PATH_TO_PYTHON_DIST>/include -DPYTHON3_LIBRARY=<PATH_TO_PYTHON_DIST>/libs/<PYTHON_Lib> -DPYTHON3_EXECUTABLE=<PATH_TO_PYTHON_DIST>/python.exe -DPYTHON3_NUMPY_INCLUDE_DIRS=<PATH_TO_PYTHON_DIST>/lib/site-packages/numpy/core/include -DPYTHON3_PACKAGES_PATH=<PATH_TO_PYTHON_DIST>/Lib/site-packages/

    For details see decreasing the build time with Ninja

    "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
    "C:\Program Files\CMake\bin\cmake.exe" -H"<PATH_TO_OPENCV_SOURCE>" -DOPENCV_EXTRA_MODULES_PATH="<PATH_TO_OPENCV_CONTRIB_MODULES>" -B"<PATH_TO_BUILD_DIR>" -G"Ninja Multi-Config"" -DCMAKE_BUILD_TYPE=Release -DINSTALL_TESTS=ON -DINSTALL_C_EXAMPLES=ON -DBUILD_EXAMPLES=ON -DBUILD_opencv_world=ON -DENABLE_CUDA_FIRST_CLASS_LANGUAGE=ON -DWITH_CUDA=ON -DCUDA_GENERATION=Auto -DBUILD_opencv_python3=ON -DPYTHON3_INCLUDE_DIR=<PATH_TO_PYTHON_DIST>/include -DPYTHON3_LIBRARY=<PATH_TO_PYTHON_DIST>/libs/<PYTHON_Lib> -DPYTHON3_EXECUTABLE=<PATH_TO_PYTHON_DIST>/python.exe -DPYTHON3_NUMPY_INCLUDE_DIRS=<PATH_TO_PYTHON_DIST>/lib/site-packages/numpy/core/include -DPYTHON3_PACKAGES_PATH=<PATH_TO_PYTHON_DIST>/Lib/site-packages/

    Following the configuration step the build is started with

    "C:\Program Files\CMake\bin\cmake.exe" --build PATH_TO_BUILD_DIR --target install --config Release

    where

    1. <N_THREADS> should be set to the number of cores/logical processors on your CPU,
    2. <PATH_TO_OPENCV_SOURCE> is the root of the OpenCV files you downloaded or cloned (the directory containing 3rdparty, apps, build, etc.),
    3. <PATH_TO_OPENCV_CONTRIB_MODULES>6 is the path to the modules directory inside the opencv-contrib repository (the directory containing cudaarithm, cudabgsegm, etc.),
    4. <PATH_TO_BUILD_DIR> is the path to the directory where the build files should go,
    5. <PATH_TO_PYTHON_DIST>7 is the directory where miniforge was installed and,
    6. <PYTHON_LIB> is the concatination of “python” with the major and minor version of your python install and “.lib”, e.g. for Python 3.10.6 <PYTHON_LIB>==python310.lib. You can confirm this by looking in your <PATH_TO_PYTHON_DIST>/libs directory.

    When passing paths to CMake on the command line make sure not to terminate them using \ as this is a special character and will cause the following arguments to be ignored. e.g. PATH_TO_OPENCV_SOURCE can be D:\opencv or D:\opencv/ but not D:\opencv\.

    This will generate the build files for OpenCV with python bindings with CUDA acceleration including all the corresponding tests and examples for verifcation. Additionally if the Nvidia Video Codec SDK or cuDNN are installed the corresponding modules will automatically be included.

    Expand the tips below for an example of the CMake output if the configuration step is successful and how to check that output to make sure the Python bindings will be being built.

    Example of CMake Configuration Output

    --
    -- General configuration for OpenCV 4.10.0-dev =====================================
    --   Version control:               4.9.0-571-g2629688d11
    --
    --   Extra modules:
    --     Location (extra):            D:/repos/opencv/contrib/modules
    --     Version control (extra):     4.9.0-84-gb236c71c
    --
    --   Platform:
    --     Timestamp:                   2024-06-11T08:50:41Z
    --     Host:                        Windows 10.0.22631 AMD64
    --     CMake:                       3.29.5
    --     CMake generator:             Ninja Multi-Config
    --     CMake build tool:            D:/bin/ninja/ninja.exe
    --     MSVC:                        1940
    --     Configuration:               Debug Release
    --
    --   CPU/HW features:
    --     Baseline:                    SSE SSE2 SSE3
    --       requested:                 SSE3
    --     Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
    --       requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
    --       SSE4_1 (18 files):         + SSSE3 SSE4_1
    --       SSE4_2 (2 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
    --       FP16 (1 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
    --       AVX (9 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
    --       AVX2 (38 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
    --       AVX512_SKX (8 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX
    --
    --   C/C++:
    --     Built as dynamic libs?:      YES
    --     C++ standard:                11
    --     C++ Compiler:                C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.40.33807/bin/Hostx64/x64/cl.exe  (ver 19.40.33811.0)
    --     C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise /FS     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819  /O2 /Ob2 /DNDEBUG  /Zi
    --     C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise /FS     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819  /Zi /Ob0 /Od /RTC1
    --     C Compiler:                  C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.40.33807/bin/Hostx64/x64/cl.exe
    --     C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise /FS       /O2 /Ob2 /DNDEBUG  /Zi
    --     C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise /FS     /Zi /Ob0 /Od /RTC1
    --     Linker flags (Release):      /machine:x64  /INCREMENTAL:NO  /debug
    --     Linker flags (Debug):        /machine:x64  /debug /INCREMENTAL
    --     ccache:                      NO
    --     Precompiled headers:         NO
    --     Extra dependencies:          C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/cudart_static.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppial.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppc.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppitc.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppig.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppist.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppidei.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/cublas.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/cublasLt.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/cufft.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppif.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppim.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5/lib/x64/nppicc.lib
    --     3rdparty dependencies:
    --
    --   OpenCV modules:
    --     To be built:                 aruco bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev datasets dnn dnn_objdetect dnn_superres dpm face features2d flann fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency shape signal stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab wechat_qrcode world xfeatures2d ximgproc xobjdetect xphoto
    --     Disabled:                    -
    --     Disabled by dependency:      -
    --     Unavailable:                 alphamat cannops cvv freetype hdf java julia matlab ovis python2 python2 sfm viz
    --     Applications:                tests perf_tests examples apps
    --     Documentation:               doxygen
    --     Non-free algorithms:         NO
    --
    --   Windows RT support:            NO
    --
    --   GUI:
    --     Win32 UI:                    YES
    --     VTK support:                 NO
    --
    --   Media I/O:
    --     ZLib:                        build (ver 1.3.1)
    --     JPEG:                        build-libjpeg-turbo (ver 3.0.3-70)
    --       SIMD Support Request:      YES
    --       SIMD Support:              NO
    --     WEBP:                        build (ver encoder: 0x020f)
    --     PNG:                         build (ver 1.6.43)
    --       SIMD Support Request:      YES
    --       SIMD Support:              YES (Intel SSE)
    --     TIFF:                        build (ver 42 - 4.6.0)
    --     JPEG 2000:                   build (ver 2.5.0)
    --     OpenEXR:                     build (ver 2.3.0)
    --     HDR:                         YES
    --     SUNRASTER:                   YES
    --     PXM:                         YES
    --     PFM:                         YES
    --
    --   Video I/O:
    --     DC1394:                      NO
    --     FFMPEG:                      YES (prebuilt binaries)
    --       avcodec:                   YES (58.134.100)
    --       avformat:                  YES (58.76.100)
    --       avutil:                    YES (56.70.100)
    --       swscale:                   YES (5.9.100)
    --       avresample:                YES (4.0.0)
    --     GStreamer:                   NO
    --     DirectShow:                  YES
    --     Media Foundation:            YES
    --       DXVA:                      YES
    --
    --   Parallel framework:            Concurrency
    --
    --   Trace:                         YES (with Intel ITT)
    --
    --   Other third-party libraries:
    --     Intel IPP:                   2021.11.0 [2021.11.0]
    --            at:                   D:/build/opencv/4_10/3rdparty/ippicv/ippicv_win/icv
    --     Intel IPP IW:                sources (2021.11.0)
    --               at:                D:/build/opencv/4_10/3rdparty/ippicv/ippicv_win/iw
    --     Lapack:                      NO
    --     Eigen:                       NO
    --     Custom HAL:                  NO
    --     Protobuf:                    build (3.19.1)
    --     Flatbuffers:                 builtin/3rdparty (23.5.9)
    --
    --   NVIDIA CUDA:                   YES (ver 12.5.40, CUFFT CUBLAS NVCUVID NVCUVENC)
    --     NVIDIA GPU arch:             50 52 60 61 70 75 80 86 89 90
    --     NVIDIA PTX archs:            90
    --
    --   cuDNN:                         YES (ver 9.2.0)
    --
    --   OpenCL:                        YES (NVD3D11)
    --     Include path:                D:/repos/opencv/opencv/3rdparty/include/opencl/1.2
    --     Link libraries:              Dynamic load
    --
    --   Python 3:
    --     Interpreter:                 C:/Users/b/miniforge3/envs/py37_mini/python.exe (ver 3.7.12)
    --     Libraries:                   C:/Users/b/miniforge3/envs/py37_mini/libs/python37.lib (ver 3.7.12)
    --     Limited API:                 NO
    --     numpy:                       C:/Users/b/miniforge3/envs/py37_mini/Lib/site-packages/numpy/core/include (ver 1.21.6)
    --     install path:                C:/Users/b/miniforge3/envs/py37_mini/Lib/site-packages/cv2/python-3.7
    --
    --   Python (for build):            C:/Users/b/miniforge3/envs/py37_mini/python.exe
    --
    --   Java:
    --     ant:                         NO
    --     Java:                        NO
    --     JNI:                         NO
    --     Java wrappers:               NO
    --     Java tests:                  NO
    --
    --   Install to:                    D:/build/opencv/4_10/install
    -- -----------------------------------------------------------------
    --
    -- Configuring done (63.3s)
    -- Generating done (21.4s)
    -- Build files have been written to: D:/build/opencv/4_10

    Verify configuration includes Python bindings before building

    If you are building the python bindings look for python3 in the To be built: section of your CMake configuration output and if its not present look for any python related errors in the output preceeding it. e.g.

    --   OpenCV modules:
    --     To be built:                 aruco bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev datasets dnn dnn_objdetect dpm face features2d flann fuzzy hfs highgui img_hash imgcodecs imgproc line_descriptor ml objdetect optflow phase_unwrapping photo plot python2 python3 quality reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab world xfeatures2d ximgproc xobjdetect xphoto
  2. The OpenCV.sln solution file should now be in your PATH_TO_BUILD_DIR directory. To build OpenCV you have two options depending on you preference you can:

    1. Build directly from the command line by simply entering the following (swaping Release for Debug to build a release version)

      "C:\Program Files\CMake\bin\cmake.exe" --build PATH_TO_BUILD_DIR --target install --config Debug
    2. Build through Visual Studio GUI by opening up the OpenCV.sln in Visual Studio, selecting your Configuration, clicking on Solution Explorer, expanding CMakeTargets, right clicking on INSTALL and clicking Build.

      Visual Studio Build Solution

    Either approach will both build the library, install the Python bindings and copy the necessary redistributable parts to the install directory (PATH_TO_BUILD_DIR/build/install). All that is required now to run any programs compiled against these libs is to add the directory containing opencv_worldxxx.dll to you user path environmental variable.

By default you have to build Release when generating python bindings, for instructions on how to build Debug see generate python bindings for a debug build

If everything was successful, congratulations, you now have OpenCV built with CUDA. To quickly verify that the CUDA modules are working and check if there is any performance benefit on your specific hardware see verifying OpenCV is CUDA accelerated.

Decreasing the build time with Ninja

The build time for OpenCV can be reduced by more than 2x (from 2 hours to 30 mins to under an hour on an i7-8700) by utilizing the Ninja build system instead of directly generating Visual Studio solution files.

Ninja is installed by default if the Desktop development with C++ workload is selected when installing Visual Studio, therefore building with Ninja only requires two extra configuration steps:

  1. Configuring Visual Studio Development tools by entering the following into the command prompt before entering the CMake command (changing Community to either Professional or Enterprise if necessary)

    "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
  2. Telling CMake to use Ninja instead of Visual Studio, i.e. replacing -G»Visual Studio 17 2022″ with -G»Ninja Multi-Config».

Once the build files have been generated the build can be kicked off in the same way as before. i.e.

"C:\Program Files\CMake\bin\cmake.exe" --build PATH_TO_BUILD_DIR --target install --config Release

for an example fo the full command line for building a Release version of OpenCV with the Ninja build system go to the Ninja tab.

Verifying OpenCV is CUDA accelerated

The easiest way to quickly verify that everything is working is to check that one of the inbuilt CUDA tests passes. This is demonstrated here using the GEMM8 acccuracy test which can be run by entering the following into the existing command prompt.

"PATH_TO_BUILD_DIR\bin\opencv_test_cudaarithm.exe" --gtest_filter=CUDA_Arithm/GEMM.Accuracy/0

To verify that everything is working look for the [ PASSED ] 1 test text, at the bottom of the test output, i.e.

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from CUDA_Arithm/GEMM
[ RUN      ] CUDA_Arithm/GEMM.Accuracy/0, where GetParam() = (NVIDIA GeForce RTX 3070 Ti Laptop GPU, 128x128, 32FC1, 0, whole matrix)
[       OK ] CUDA_Arithm/GEMM.Accuracy/0 (1038 ms)
[----------] 1 test from CUDA_Arithm/GEMM (1039 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1041 ms total)
[  PASSED  ] 1 test.

If the test has passed then we can confirm that the OpenCV build inside PATH_TO_BUILD_DIR includes the CUDA modules.

The instructions above will enable you to build a Release version of OpenCV with bindings for Python and automatically install them into your PATH_TO_PYTHON_DIST/site-packages directory. You can then import the OpenCV python module (cv2) as

and you should see output similar to the below when interrogating the build information

>>> print(cv2.getBuildInformation())

General configuration for OpenCV 4.10.0-dev =====================================
  Version control:               4.9.0-571-g2629688d11

  Extra modules:
    Location (extra):            D:/repos/opencv/contrib/modules
    Version control (extra):     4.9.0-84-gb236c71c

  Platform:
    Timestamp:                   2024-06-11T08:50:41Z
    Host:                        Windows 10.0.22631 AMD64
    CMake:                       3.29.5
    CMake generator:             Ninja Multi-Config
    CMake build tool:            D:/bin/ninja/ninja.exe
    MSVC:                        1940
    Configuration:               Debug Release
    ...

That said you may:

  1. Want to build bindings for a Debug as well or instead of a Release build.
  2. Encounter errors when trying to import the cv2 module in Python.
  3. Manually install the Python bindings.

Generate Python bindings for a Debug Build

Python bindings cannot by default be generated for a Debug configuration, that is unless you have specificaly built or downloaded a debug version of Python. That said you can make a Debug build if you first modify the contents of PATH_TO_PYTHON_DIST/include/pyconfig.h, changing

pragma comment(lib,"pythonxx_d.lib")

to

pragma comment(lib,"pythonxx.lib")

and

to

Then simply follow the instructions above for building with CMake.

Troubleshooting Python Bindings Installation issues

If you are unable to import cv2 without errors then check below to see if there is a solution to the error you recieve.

  1. ModuleNotFoundError: No module named 'cv2'

    The installation of the Python bindings has failed, check

    1. the build was successful,
    2. -DPYTHON3_PACKAGES_PATH=PATH_TO_PYTHON_DIST/Lib/site-packages/ was set correctly, and
    3. if you are still seeing the above error try manually installing opencv Python bindings.
  1. ImportError: ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.

    The main two reasons for this are:

    1. You have another installation of OpenCV, either manually installed or through the package manager (pip/mamba etc.). This can easily be fixed by first uninstalling any opencv-python, opencv-contrib-python distributions from your package manager and then deleting the cv2 directory (PATH_TO_PYTHON_DIST/Lib/site-packages/cv2/) or bindings file (PATH_TO_PYTHON_DIST/Lib/site-packages/cv2.cpxx-win_amd64.pyd) if they exist.

    2. You have built a Debug configuration. Currently (https://github.com/opencv/opencv/issues/23568) when building this configuration the cv2.cpxx-win_amd64.pyd shared library is not copied into site-packages-x.x
      directory on installation. This can easily be resolved by creating the python-x.x directory and copying the shared library accross so you have PATH_TO_PYTHON_DIST/Lib/site-packages/cv2/python-x.x/cv2.cpxx-win_amd64.pyd, where xx is the PYTHON_VERSION.

  2. ImportError: DLL load failed: The specified module could not be found.

    The directory of one or more of the required DLL’s has not been added with os.add_dll_directory(). Whilst the automatic installation of the bindings should have added all the directories containing the dependant DLL’s to config.py it’s possible that one has been missed or you are using a less common configuration. In these cases you will have to

    1. first track down which DLL’s are missing (see this guide for assistance) and then
    2. permanantly add the directory containing them to your installation by modifying the contents of PATH_TO_PYTHON_DIST/Lib/site-packages/cv2/config.py.

    e.g. If you built OpenCV against CUDA 12.1 and your own version of the FFMpeg libraries (-DOPENCV_FFMPEG_USE_FIND_PACKAGE=ON) instead of using the provided opencv_videoio_ffmpegxxx_64.dll plugin, the contents of config.py should look like

    import os
    
    BINARIES_PATHS = [
        os.path.join('D:/build/opencv/install', 'x64/vc17/bin'),
        os.path.join(os.getenv('CUDA_PATH', 'C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.5'), 'bin')
        os.path.join(`D:/ffmpeg/bin`)
    ] + BINARIES_PATHS
  3. ImportError: DLL load failed while importing cv2: A dynamic link library (DLL) initialization routine failed.

    The most common cause of this is out of date Visual C++ Redistributable libraries. These can be loaded from your windows system or your python installation depending on your configuration. The easiest thing to do is update both by

    1. downloading and installing the latest version of the Visual C++ Redistributable from Microsoft, and
    2. checking your python package manager (pip/mamba/conda/… list) for the vc or vc14_runtime packages and updating them to the latest version (e.g. pip install vc --upgrade or mamba/conda upgrade vc) and try importing OpenCV again.

Manually installing OpenCV Python bindings

If you have downloaded the pre-built binaries or are having issues with the automatic installation then you can manually install the python bindings following the steps below:

  1. Remove any pre-existing OpenCV installations.

  2. Copy PATH_TO_BUILD_DIR/lib/python3/cv2.cpxx-win_amd64.pyd to PATH_TO_PYTHON_DIST/Lib/site-packages/cv2.cpxx-win_amd64.pyd

  3. Determine the paths to the directories containing any dependant shared libraries (see here for assistance).

  4. Adding the locations from (3) by calling os.add_dll_directory() for each one before importing the OpenCV python module. e.g. If you have followed the guide exactly this will be the directories containing the OpenCV and Nvidia shared libaries, which you would add as

    import os
    os.add_dll_directory('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\vxx.x\\bin')
    os.add_dll_directory('PATH_TO_BUILD_DIR/bin')

    before calling

Choosing a suitable CUDA compute capability

The default command line options given above will build a version of OpenCV which runs on the GPUs which are installed at configuration time. As mentioned above depending on your circumstances this might be the best solution. e.g. If you don’t have a GPU installed on the build system. Before discussing the various options which can be used to add support for GPUs with different compute capabilities to those installed on your system it is important to understand the following concepts:

  1. Compute capability – every GPU has a fixed compute capability which determines its general specifications and features. In general the more recent the GPU the higher the compute-capability and the more features it will support. This is important because:
    • Each version of CUDA supports different compute capabilities. Usually a new version of CUDA comes out to suppoort a new GPU architecture, in the case of CUDA 11.0, support was added for the Ampere (compute 8.0, with compute 8.6 added in CUDA 11.1) architecture. On the flip side support for compute 3.0 and 3.2 was dropped. Therefore by if we chose to build OpenCV with CUDA 11.0 we limit ourselves to GPU’s of compute capability >=3.5. Notice we have not limited ourselves to compute capability GPU’s <=8.6, the reason for this is discussed in the next section.
    • You can build OpenCV to support one or many different compute capabilities, depending on your specific requirements.
  2. Supporting a compute capability — to support a specific compute capability you can do either of the following, or a combination of the two:
    • Generate architecture-specific cubin files, which are only forward-compatible (excluding Tegra) with GPU architectures with the same major version number. This can be controlled by passing the CUDA_ARCH_BIN flag to CMake. For example passing -DCUDA_ARCH_BIN=3.0 to CMake, will result in binary code which can only run on compute capability 3.0, 3.5 and 3.7 devices. Futhermore it will not support any specific features of compute capability 3.5 (e.g. dynamic parallelism) or 3.7 (e.g. 128 K 32 bit registers). You can detrmine which functions this will affect by searching OpenCV on github for the CUDA_ARCH flag. Because of the default CMake rules when CUDA_ARCH_BIN is not explicitly set it will also contain architecture-specific cubin files for all GPU architectures supported by your CUDA version.
    • Generate forward-compatible PTX assembly for a virtual architecture, which is forward-compatable with all GPU architectures of greater than or equal compute-capability. This can be controlled by passing CUDA_ARCH_PTX to CMake. e.g. Setting the -DCUDA_ARCH_PTX=9.0 flag, builds OpenCV containing PTX code for compute capability 9.0 which can be Just In Time (JIT) compiled to architecture-specific binary code by the CUDA driver, on any future GPU architectures.
  1. PTX considerations – given that PTX code is forward-compatible and cubin binaries are not it would be tempting to only include the former. To understand why this might not be such a great idea, a things to be aware of when generating PTX code:
    • As mentioned previously the CUDA driver JIT compiles PTX code at run time and cache’s the resulting cubin files so that the compile operation should in theory be a one-time delay, at least until the driver is updated. However if the cache is not large enough JIT compilation will happen every time, causing delay every time your program executes.To get an idea of this delay I passed -DCUDA_ARCH_BIN=3.5 and -DCUDA_ARCH_PTX=3.5 to CMake before building OpenCV. I then emptied the cache (default location %appdata%\NVIDIA\ComputeCache\) and ran the performance example on a GTX 1060 (compute-capability 6.1), to force JIT compilation. I measured an initial delay of over 3 minutes as the PTX code was JIT compiled before the program started to execute. Following that, the delay of subsequent executions was around a minute, because the default cache size (256 MB) was not large enough to store all the compiled PTX code. Given my compile options the only solution to remove this delay is to increase the size of the cache by setting the CUDA_CACHE_MAXSIZE environmental variable to a number of bytes greater than required. Unfortunately because,

      Older binary codes are evicted from the cache to make room for newer binary codes if needed

      this is more of a band aid than a solution. This is because the maximum cache size is 4 GB, therefore your PTX compiled code can be evicted at any point in time if other programs on your machine are also JIT compiling from PTX, bringing back the “one-time” only delay.

    • For maximum device coverage you should include PTX for the lowest possible GPU architecture you want to support.

    • For maximum performance NVIDIA recommends including PTX for the highest possible architecture you can.

CMake command line options to control cubin/PTX content of the OpenCV shared library

Given (1)-(3) above, the command line options that you want to pass to CMake when building OpenCV will depend on your specific requirements. I have given some examples below for various scenarios given a main GPU with compute capability 6.1 and CUDA toolkit 12:

  • Firstly stick with the defaults (-DCUDA_GENERATION=Auto) if your programs will always be run on your main GPU. It should take around an hour to build, depending on your CPU and the resulting shared library should not be larger than 200 MB.
  • If you want maximum coverage then use Nvidia’s recommended settings for future compatibility. That is compile for all supported major and minor real architectures, and the highest major virtual architecture by passing -DCUDA_ARCH_BIN=50,52,60,61,70,75,80,86,89,90 and -DCUDA_ARCH_PTX=90 to CMake.
  • If you are going to deploy your application, but only to newer GPU’s pass -DCUDA_ARCH_BIN=61,70,80,86,89,90 and -DCUDA_ARCH_PTX=90 to CMake for maximum performance and future compatibility. This is advisable because you may not have any control over the size of the JIT cache on the target machine, therefore including cubin’s for all compute-capabilities you want to support, is the only way be sure to prevent JIT compilation delay on every invocation of your application.
  • If size is really an issue but you don’t know which GPU’s you want to run your application on then to ensure that your program will run on all current and future supported GPU’s pass -DCUDA_ARCH_BIN=61 and -DCUDA_ARCH_PTX=30 to CMake for maximum coverage.

Back to top

Footnotes

  1. I have seen lots of guides including instructions to download and use git to get the source files, however this is a completely unnecessary step. If you are a developer and you don’t already have git installed and configured then I would assume there is a good reason for this and I would not advise installing it just to build OpenCV.↩︎

  2. Before building you may want to ensure that your GPU has decoding support by referring to Nvidia Video Decoder Support Matrix↩︎

  3. All python distributions should work however I recommend building and testing against a new install of this compact distribution to avoid any problems caused by existing configurations.↩︎

  4. If you have any build issues with OpenCV then you will need to provide the arguments passed to CMake as well as the output from the generation step when asking for assistance which is another good reason to avoid the CMake GUI if you can.↩︎

  5. An additionally option you may want to include is -DCUDA_FAST_MATH=ON which compiles the CUDA kernels with the -use_fast_math option. This will however cause some of the accuracy and performance tests to fail as the floating point results will be slightly less accurate.↩︎

  6. If you get the following error “CUDA : OpenCV requires enabled ‘cudev’ module from ‘opencv_contrib’” when configuring the build with CMake you have not set OPENCV_EXTRA_MODULES_PATH correctly, most likely you have set it to the root of the opencv_contrib repo and not the modules directory inside the repo.↩︎

  7. The default installation directory for miniforge is %userprofile%\miniforge3.↩︎

  8. The GEMM test is used in this example but any of the accuracy (opencv_test_cuda*.exe) or performance (opencv_perf_cuda*.exe) tests could have been chosen.↩︎

Время на прочтение7 мин

Количество просмотров41K

Введение

В данной статье речь пойдет о сборке и установке OpenCV 4 для C/C++, Python 2 и Python 3 из исходных файлов с дополнительными модулями CUDA 10 на ОС Windows.

Я постарался включить сюда все тонкости и нюансы, с которыми можно столкнуться в ходе установки, и про которые не написано в официальном мануале.

Сборка тестировалась для:

  • Windows 8.1 + Visual Studio 2017 + Python 2/3 + CUDA 10.0 + GeForce 840m
  • Windows 10 + Visual Studio 2019 + Python 2/3 + CUDA 10.0 + GeForce GTX 1060

Внимание! Сборка не подойдет для версии OpenCV 4.0.1 и/или CUDA ниже 10-й версии. CUDA 9 и ниже поддерживается OpenCV 3.

Что потребуется для установки

В моей сборке использовались следующие инструменты:

  1. CMake 3.15
  2. MS Visual Studio 2019 64-бит + средства CMake С++ для Windows
  3. Python 3.7.3 64-бит + NumPy 64-бит
  4. Python 2.7.16 64-бит + NumPy 64-бит
  5. CUDA 10.0
  6. CuDNN 7.6.2
  7. OpenCV 4.1.1 и OpenCV-contrib-4.1.1

Установка

Так как установка производится через консольные команды, то следует внимательно и аккуратно выполнять все шаги. Также, при необходимости, меняйте установочные пути на свои.
Для начала необходимо установить требуемое ПО, причем Visual Studio должна быть установлена до CUDA:

  • CMake (версия >= 3.9.1)
  • MS Visual Studio
  • Python 3.7 (дистрибутив Anaconda3)
  • CUDA 10.0
  • CuDNN 7.6.2

После установки всех компонент убедитесь, что пути для CMake, Visual Studio, Python, CUDA, CuDNN прописаны в переменных PATH, PYTHONPATH, CUDA_PATH и cudnn соответственно.

Далее загружаем архивы исходников opencv-4.1.1 и opencv-contrib-4.1.1 в желаемое место (в моем случае это C:\OpenCV\).

git clone https://github.com/opencv/opencv.git -b "4.1.1"
git clone https://github.com/opencv/opencv_contrib.git -b "4.1.1"

Создаем папку build/ внутри opencv-4.1.1.

Далее сгенерируем файлы сборки с помощью cmake. Мы будем использовать консольный вариант cmake, так как cmake-gui путает типы некоторых переменных (например, OPENCV_PYTHON3_VERSION) и, как следствие, неправильно генерирует файлы.

Открываем консоль по пути C:\OpenCV\ и прописываем переменные.

set "opencvSource=opencv-4.1.1"
set "opencvExtraModules=opencv_contrib-4.1.1/modules"
set "opencvBuild=%opencvSource%\build"
set "compiler=Visual Studio 16 2019"
set "buildType=Release"

Примечание. Для Visual Studio 2017 генератор пишется как «Visual Studio 15 2017 Win64» и без флага -A.

Также можно явно указать питоновские библиотеки для python 2 и python 3 на случай, если сборщик не сможет найти их автоматически.

set "python2_executable=C:/Python27/python.exe"
set "python2_include_dir=C:/Python27/include"
set "python2_library=C:/Python27/libs/python27.lib"
set "python2_numpy_include_dirs=C:/Python27/Lib/site-packages/numpy/core/include"
set "python2_packages_path=C:/Python27/Lib/site-packages"

set "python3_executable=C:/Users/root/Anaconda3/python.exe"
set "python3_include_dir=C:/Users/root/Anaconda3/include"
set "python3_library=C:/Users/root/Anaconda3/libs/python37.lib"
set "python3_numpy_include_dirs=C:/Users/root/Anaconda3/lib/site-packages/numpy/core/include"
set "python3_packages_path=C:/Users/root/Anaconda3/Lib/site-packages"

Примечание. Обратите внимание на то, что библиотека NumPy должна быть той же разрядности, что и OpenCV. Проверить это легко:

import numpy.distutils.system_info as sysinfo
print(sysinfo.platform_bits)

Выполняем генерацию файлов сборки с помощью длинной команды ниже. При неудачной генерации или наличии ошибок после выполнения команды, повторную генерацию следует производить вычистив все файлы в build/ и .cache/.

cmake ^
-B"%opencvBuild%/" ^
-H"%opencvSource%/" ^
-G"%compiler%" ^
-Ax64 ^
-DCMAKE_BUILD_TYPE=%buildType% ^
-DBUILD_opencv_world=ON ^
-DINSTALL_TESTS=OFF ^
-DINSTALL_C_EXAMPLES=OFF ^
-DBUILD_EXAMPLES=OFF ^
-DOPENCV_EXTRA_MODULES_PATH="%opencvExtraModules%/" ^
-DBUILD_PROTOBUF=ON ^
-DBUILD_opencv_python_bindings_generator=ON ^
-DWITH_CUDA=ON ^
-DCUDA_FAST_MATH=ON ^
-DWITH_CUBLAS=ON ^
-DCUDA_ARCH_PTX=7.5 ^
-DBUILD_opencv_python2=ON ^
-DPYTHON2_EXECUTABLE="%python2_executable%" ^
-DOPENCV_PYTHON2_VERSION=2.7.16 ^
-DPYTHON2_INCLUDE_DIR="%python2_include_dir%" ^
-DPYTHON2_LIBRARY="%python2_library%" ^
-DPYTHON2_NUMPY_INCLUDE_DIRS="%python2_numpy_include_dirs%" ^
-DPYTHON2_PACKAGES_PATH="%python2_packages_path%" ^
-DBUILD_opencv_python3=ON ^
-DPYTHON3_EXECUTABLE="%python3_executable%" ^
-DOPENCV_PYTHON3_VERSION=3.7.3 ^
-DPYTHON3_INCLUDE_DIR="%python3_include_dir%" ^
-DPYTHON3_LIBRARY="%python3_library%" ^
-DPYTHON3_NUMPY_INCLUDE_DIRS="%python3_numpy_include_dirs%" ^
-DPYTHON3_PACKAGES_PATH="%python3_packages_path%"

Значение некоторых флагов

  • BUILD_opencv_world – необязательный модуль, содержащий копии всех выбранных в ходе установки библиотек. Удобен при разработке на C++, так как вместо подключения кучи зависимостей opencv можно подключить одну зависимость opencv_world411.lib в проект
  • INSTALL_EXAMPLES/INSTALL_TESTS – установка примеров/тестов кода opencv
  • CUDA_FAST_MATH, WITH_CUBLAS – дополнительные модули для CUDA, призванные ускорить вычисления
  • CUDA_ARCH_PTX – версия PTX инструкций для улучшения производительности вычислений
  • OPENCV_EXTRA_MODULES_PATH – путь до дополнительных модулей из opencv-contrib (обязательно для CUDA)
  • BUILD_PROTOBUF – для работы некоторых модулей opencv необходим Protobuf (сборщик opencv в любом случае поставит BUILD_PROTOBUF=ON)

Спустя примерно 10 минут в консоле должна появиться информация о сборке и завершающие строки «Configuring done» и «Generating done». Проверяем всю информацию, особенно разделы NVIDIA CUDA, Python 2, Python 3.

Далее собираем решение. На сборку может уйти несколько часов в зависимости от вашего процессора и версии Visual Studio.

cmake --build %opencvBuild% --target ALL_BUILD --config Release

Устанавливаем решение.

cmake --build %opencvBuild% --target INSTALL --config Release

После успешной установки создаем системную переменную OPENCV_DIR со значением C:\OpenCV\opencv-4.1.1\build\install\x64\vc15\bin и также добавляем ее в PATH.

Тест

Проверим работоспособность OpenCV с модулем CUDA на простом примере умножения матриц.

Подключение OpenCV в проект Visual Studio

  1. Установить тип сборки Release/x64 (для Debug следует собрать OpenCV с флагом Debug)
  2. Project Properties → C/C++ → General → Добавить строку «C:\OpenCV\opencv-4.1.1\build\install\include» в Additional Include Directories
  3. Project Properties → Linker → General → Добавить строку « C:\OpenCV\opencv-4.1.1\build\install\x64\vc16\lib» в Additional Library Directories
  4. Project Properties → Linker → General → Добавить «;opencv_world411.lib» («;opencv_world411d.lib» для Debug) в конец Additional Dependencies

Пример на Python 3

import numpy as np
import cv2 as cv
import time

rand = np.random.random((1024, 1024)).astype(np.float32)
h_array1 = np.stack([rand, rand],axis=2)
h_array2 = h_array1
d_array1 = cv.cuda_GpuMat()
d_array2 = cv.cuda_GpuMat()
d_array1.upload(h_array1)
d_array2.upload(h_array2)

start = time.time()
cv.cuda.gemm(d_array1, d_array2, 1, None, 0, None, 1)
end = time.time()
print("Time elapsed:", end - start, "sec")

Вывод в консоли

Time elapsed: 0.3130002021789551

Пример на C++

#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/cudaarithm.hpp>

using namespace std;
using namespace cv;
using namespace cv::cuda;

int main() {

	Mat h_array1 = Mat::ones(1024, 1024, CV_32FC2);
	Mat h_array2 = Mat::ones(1024, 1024, CV_32FC2);
	Mat h_array3 = Mat::zeros(1024, 1024, CV_32FC2);
	Mat h_result;
	GpuMat d_array1, d_array2, d_array3, d_result;

	d_array1.upload(h_array1);
	d_array2.upload(h_array2);

	const clock_t begin_time = clock();
	cuda::gemm(d_array1, d_array2, 1.0, d_array3, 0.0, d_result);
	cout << "Time elapsed: " << (float(clock() - begin_time) / CLOCKS_PER_SEC) << " sec" << endl;

	d_result.download(h_result);

	return 0;
}

Вывод в консоли

Time elapsed: 0.354

Удаление

Чтобы удалить OpenCV, нужно выполнить команду.

cmake --build %opencvBuild% --target uninstall --config Release

и удалить системную переменную OPENCV_DIR и убрать путь до OpenCV из PATH.

Заключение

В статье мы рассмотрели установку OpenCV 4 для ОС Windows 10. Данный алгоритм тестировался на Windows 8.1 и Windows 10, но, в теории, может собираться и на Windows 7. За дополнительной информацией можно обратиться к списку источников ниже.

P.S. Напоследок сведем все установочные команды в один .bat файл для тех, кто хочет автоматизировать установку.

install_opencv411.bat

cd C:\OpenCV

git clone https://github.com/opencv/opencv_contrib.git -b "4.1.1"
git clone https://github.com/opencv/opencv.git -b "4.1.1"

ren opencv opencv-4.1.1
ren opencv_contrib-4.1.1

set "opencvSource=opencv-4.1.1"
set "opencvExtraModules=opencv_contrib-4.1.1/modules"
set "opencvBuild=%opencvSource%\build"
set "compiler=Visual Studio 16 2019"
set "buildType=Release"

set "python2_executable=C:/Python27/python.exe"
set "python2_include_dir=C:/Python27/include"
set "python2_library=C:/Python27/libs/python27.lib"
set "python2_numpy_include_dirs=C:/Python27/Lib/site-packages/numpy/core/include"
set "python2_packages_path=C:/Python27/Lib/site-packages"

set "python3_executable=C:/Users/root/Anaconda3/python.exe"
set "python3_include_dir=C:/Users/root/Anaconda3/include"
set "python3_library=C:/Users/root/Anaconda3/libs/python37.lib"
set "python3_numpy_include_dirs=C:/Users/root/Anaconda3/lib/site-packages/numpy/core/include"
set "python3_packages_path=C:/Users/root/Anaconda3/Lib/site-packages"

cmake ^
-B"%opencvBuild%/" ^
-H"%opencvSource%/" ^
-G"%compiler%" ^
-Ax64 ^
-DCMAKE_BUILD_TYPE=%buildType% ^
-DBUILD_opencv_world=ON ^
-DINSTALL_TESTS=OFF ^
-DINSTALL_C_EXAMPLES=OFF ^
-DBUILD_EXAMPLES=OFF ^
-DOPENCV_EXTRA_MODULES_PATH="%opencvExtraModules%/" ^
-DBUILD_PROTOBUF=ON ^
-DBUILD_opencv_python_bindings_generator=ON ^
-DWITH_CUDA=ON ^
-DCUDA_FAST_MATH=ON ^
-DWITH_CUBLAS=ON ^
-DCUDA_ARCH_PTX=7.5 ^
-DBUILD_opencv_python2=ON ^
-DPYTHON2_EXECUTABLE="%python2_executable%" ^
-DOPENCV_PYTHON2_VERSION=2.7.16 ^
-DPYTHON2_INCLUDE_DIR="%python2_include_dir%" ^
-DPYTHON2_LIBRARY="%python2_library%" ^
-DPYTHON2_NUMPY_INCLUDE_DIRS="%python2_numpy_include_dirs%" ^
-DPYTHON2_PACKAGES_PATH="%python2_packages_path%" ^
-DBUILD_opencv_python3=ON ^
-DPYTHON3_EXECUTABLE="%python3_executable%" ^
-DOPENCV_PYTHON3_VERSION=3.7.3 ^
-DPYTHON3_INCLUDE_DIR="%python3_include_dir%" ^
-DPYTHON3_LIBRARY="%python3_library%" ^
-DPYTHON3_NUMPY_INCLUDE_DIRS="%python3_numpy_include_dirs%" ^
-DPYTHON3_PACKAGES_PATH="%python3_packages_path%"

cmake --build %opencvBuild% --target ALL_BUILD --config Release
cmake --build %opencvBuild% --target INSTALL --config Release

Список источников

  1. docs.opencv.org/4.1.1/d3/d52/tutorial_windows_install.html
  2. www.learnopencv.com/install-opencv-4-on-windows
  3. jamesbowley.co.uk/build-opencv-4-0-0-with-cuda-10-0-and-intel-mkl-tbb-in-windows
  4. lightbuzz.com/opencv-cuda
  5. Глава «Building libraries from Source» книги Hands-on GPU-Accelerated Computer Vision with OpenCV and CUDA

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Где вы хотите установить windows что делать
  • Nextcloud client windows download
  • Van9003 valorant ошибка windows 11
  • Windows синхронизация автономных папок
  • Диск с windows стал raw