CUEH Development Environment Guides
Compiling OpenCV Libraries

Compiling OpenCV for C++

As part of the programming module you study on the course, you will be required to use the OpenCV libraries for the individual programming assessment, using the C++ programming language. To ensure that your development environment is ready and prepared for the assessment, you will need to follow this guide fully to compile the OpenCV libraries for use on your system.

In this guide, you shall be taken through the journey of compiling and building the sources for OpenCV for the Microsoft Windows operating system.

Downloading the OpenCV Libraries

Before you can begin using the OpenCV library for programming and providing solutions to lab activities and assignments, you will need to download the OpenCV source files from the following link:

OpenCV Source Files

OpenCV Contribution Module Source Files

These links will begin the download of a compressed folder, one for the OpenCV core modules, and the other for the OpenCV contribution modules. The contribution modules contains additional non-free algorithms which can be useful for applications such as object detection and recognition, along with facial recognition etc.

Decompressing the Source Files

The two compressed archives you have downloaded will be called opencv-4.10.0.zip and opencv_contrib-4.10.0.zip, respectively. As part of the building and compilation process they will need to be decompressed to an area on your Windows operating system. For the purpose of this guide, the archives will be decompressed to the C:\ directory.

To decompress the files, you will need to be located in the Downloads directory of your user area. To traverse to the Downloads directory, you can use the following command:

> cd C:\Users\<YOUR_USERNAME>\Downloads

You will need to replace <YOUR_USERNAME> with the username of your machine. Inside the downloads folder, should be the two files you downloaded earlier. To decompress these files and move them to the root directory of C:\, you can use the following commands:

> tar -xf opencv-4.10.0.zip && move opencv-4.10.0 C:\opencv
> tar -xf opencv_contrib-4.10.0.zip && move opencv_contrib-4.10.0 C:\opencv-contrib

The tar -xf command will decompress the archive to the Downloads directory. The && characters is being used to join another command after our previous one has completed executing. In this case, our second command is move and this will move the folder opencv* to the C:\ and rename it by removing the version number from the end.

Once these commands have been executed, you should notice in your C:\ directory two new folders, one called opencv and another called opencv-contrib.

Setting up for Compilation

Before you can begin building the libraries for OpenCV, there is some preliminary work that needs to be undertaken to ensure that the third-party libraries for audio, image and video processing are linked with OpenCV. This will ensure that the OpenCV libraries are optimally configured to run on your hardware, and is efficient. To do this, you will need to download and install the following software:

It is necessary that students download these files and install them on their system, as they are required to ensure that your OpenCV libraries are configured to run correctly on your system. It will ensure that the algorithms provided in these libraries run at their most optimum performance.

Note

It is important to note, that the compilation steps provided in this guide does not take into account GPU acceleration. If you would like to compile the OpenCV libraries with native GPU accelerating there are plenty of guides available on the internet. You can approach the module leader in the lab sessions for more information.

Configuring the OpenCV Libraries

With the preliminary work completed, you can now begin the process of configuring the OpenCV libraries. Before you can begin, you will need to traverse the directory opencv located in C:\. This can be achieved using the following command:

> cd C:\opencv

Inside the opencv directory, you will need to create a folder called build. This is where we shall build the library from source. This can be achieved using the following command:

> mkdir build && cd build

Once the directory has been created, the command will automatically put you inside the build folder, and you can now begin the process of configuring the library. The configuration process will make use of the CMake tool that was installed during the process of setting up your C++ toolset. However, there are a number of flags and options that we need to use to ensure we optimise our build of OpenCV. The following command can be used to configure the OpenCV library:

> cmake -D CMAKE_BUILD_TYPE=RELEASE ^
        -D CMAKE_PREFIX_PATH="C:\opencv" ^
        -D WITH_TBB=ON ^
        -D TBB_DIR="C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\include" ^
        -D TBB_ENV_LIB="C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\lib\vc_mt\tbb.lib" ^
        -D TBB_ENV_LIB_DEBUG="C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\lib\vc_mt\tbb_debug.lib" ^
        -D ENABLE_FAST_MATH=1 ^
        -D WITH_CUBLAS=1 ^
        -D WITH_V4L=ON ^
        -D WITH_QT=OFF ^
        -D WITH_OPENGL=ON ^
        -D WITH_GSTREAMER=ON ^
        -D GSTREAMER_DIR="C:\gstreamer\1.0\msvc_x86_64" ^
        -D OPENCV_GENERATE_PKGCONFIG=ON ^
        -D OPENCV_PC_FILE_NAME=opencv.pc ^
        -D OPENCV_ENABLE_NONFREE=ON ^
        -D OPENCV_EXTRA_MODULES_PATH="C:\opencv-contrib\modules" ^
        -D INSTALL_PYTHON_EXAMPLES=OFF ^
        -D INSTALL_C_EXAMPLES=OFF ^
        -D BUILD_EXAMPLES=OFF ^
        ..

Each one of these options (after the -D flag) is important, and I shall explain what each one of these options is configuring:

  • CMAKE_BUILD_TYPE=RELEASE: sets the build mode to Release, meaning the code will be compiled with optimisations enabled (typically for production use); It results in faster, optimized binaries; other options include Debug (for debugging with debug symbols) and RelWithDebInfo (release with debug info)
  • WITH_TBB=ON: enables the use of Intel's Threading Building Blocks (TBB) library, which improves performance by parallelizing certain tasks (multithreading); this can speed up many OpenCV operations, especially when working with large datasets or computationally intensive tasks
  • TBB_DIR="C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\include": specifies the directory where Intel's Threading Building Blocks (TBB) headers are located, enabling OpenCV to use TBB for parallel processing
  • TBB_ENV_LIB="C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\lib\vc_mt\tbb.lib": points to the TBB library for release mode, linking OpenCV with TBB’s optimized library to boost performance in multithreaded tasks
  • TBB_ENV_LIB_DEBUG="C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\lib\vc_mt\tbb_debug.lib": links OpenCV to TBB’s debug library, providing debugging support for multithreading during development
  • ENABLE_FAST_MATH=1: enables faster mathematical operations using less precise floating-point calculations, which can speed up the processing at the cost of slight reductions in precision; this uses SIMD (Single Instruction, Multiple Data) instructions for improved performance
  • WITH_V4L=ON: enables support for Video4Linux (V4L), which is a collection of device drivers and APIs to capture video from cameras; this is necessary to use OpenCV with video capture devices like webcams on Linux systems
  • WITH_QT=OFF: disables the use of the Qt library for building OpenCV’s high-level GUI components; Qt provides a cross-platform framework for GUI, but if set to OFF, OpenCV will use its native or basic graphical capabilities instead
  • WITH_OPENGL=ON: enables support for OpenGL, a cross-platform API for rendering 2D and 3D vector graphics; this is useful for GPU-accelerated image rendering and visualization
  • WITH_GSTREAMER=ON: enables support for GStreamer, a multimedia framework that allows handling audio and video streams; OpenCV can use it to read and write a variety of multimedia formats and stream video over networks
  • GSTREAMER_DIR="C:\gstreamer\1.0\msvc_x86_64": specifies the GStreamer installation path, enabling OpenCV to support video capture, processing, and streaming through GStreamer plugins on Windows
  • OPENCV_GENERATE_PKGCONFIG=ON: generates a pkg-config file (used by the pkg-config tool) to help other programs or libraries easily find and link to OpenCV; this file simplifies dependency management and build configuration for software developers using OpenCV
  • OPENCV_PC_FILE_NAME=opencv.pc: specifies the name of the pkg-config file that will be generated; the default is typically opencv.pc; this file contains information about the OpenCV library’s installation paths and compile/link flags, helping other build systems (like autotools or CMake) find and link OpenCV
  • OPENCV_ENABLE_NONFREE=ON: enables building OpenCV modules that include patented or non-free algorithms, like SIFT (Scale-Invariant Feature Transform); these modules are subject to certain legal restrictions or licenses, so by default, they are excluded unless explicitly enabled with this flag
  • OPENCV_EXTRA_MODULES_PATH=C:\opencv-contrib\modules: specifies the path to the extra modules from the opencv-contrib repository, which contains additional functionalities that are not included in the main OpenCV repository; these modules extend OpenCV with more algorithms and features (e.g., SIFT, SURF, and many others)
  • INSTALL_PYTHON_EXAMPLES=OFF: prevents the installation of Python example scripts that come with OpenCV; setting this to OFF reduces the installation size and clutter, particularly if you do not need example Python code
  • INSTALL_C_EXAMPLES=OFF: similar to INSTALL_PYTHON_EXAMPLES, this option prevents installing C/C++ example programs that are included with OpenCV, minimizing unnecessary files during installation
  • BUILD_EXAMPLES=OFF: disables the building of example programs; these examples can be useful for learning or testing OpenCV features, but setting this to OFF can speed up the build process and reduce disk usage if examples are not needed

Finally, the .. at the end of the command tells the cmake tool to configure OpenCV using the library files that are located in the directory up-one from the build directory. Therefore, it will use the files that are located in the root of the directory C:\opencv.

Once the compilation process has completed, you should be met with an outcome that has the last few lines:

> cmake <snip>
  -- Build files have been written to: C:\opencv\build

Important

If you are met with any other issue (or error), speak to the module team in the lab session for assistance.

Building the OpenCV Library

With the OpenCV libraries now configured, you can begin the process of building the library. In order to do this, you must ensure you are still located in the build directory and use the following command:

> cmake --build . 

This will begin the process of building the OpenCV libraries. Depending on the capability of your machine, this process may take some time. However, upon its completion you should be met with an outcome similar to below:

$ cmake --build .
  Building Custom Rule C:/opencv/CMakeLists.txt

The output may not be exactly the same, but as long as the last output is something similar and there were no errors or issues then the libraries have been built successfully.

Installing the OpenCV Library

Once the libraries have been built, you are now required to install the libraries on the system. To install the libraries, you will need to use the following command:

> cmake --build . --target=INSTALL

Important

It is very important you are running the Developer Command Prompt for VS 2022 in administrator mode. If you do not, then the installation process will error.

Once the installation command has finished executing, you will be met with a similar output to the one shown below:

> cmake --build . --target=INSTALL
  -- Installing: C:/opencv/build/install/x64/vc17/bin/opencv_version_win32d.exe
  -- Installing: C:/opencv/build/install/x64/vc17/bin/opencv_model_diagnosticsd.exe

Once the installation process has finished, the libraries will have been installed. However, we need to copy the directory where the library was installed to into a folder in Program Files (x86). You will notice that the library has been placed in a directory called opencv/build/install. However, this is not the folder that the cmake tool will look for when compiling your C++ source code. Instead, it will be looking for a folder called OpenCV in Program Files (x86). Therefore, to resolve this issue, we need to copy the folder opencv/build/install to Program Files (x86)/OpenCV. To achieve this, you can use the following command:

> xcopy /S /I /Q /Y /F "C:\opencv\build\install" "C:\Program Files (x86)\OpenCV"

Important

It is very important you are running the Developer Command Prompt for VS 2022 in administrator mode. If you do not, then the installation process will error.

The command will copy the files to the necessary folder that CMake will resolve to locate the necessary libraries. Once the files have been copied across, the installation process is complete.

Setting your Environment Variables

Before you can begin using the OpenCV libraries on your machine, there are some additional steps required to ensure that your compiler can locate the necessary libraries and resources. Using the Start Menu search for Environment Variables and select the result named: Edit the system environment variables.

This will open a new dialogue window, and from this window you will need to click on the button called Environment Variables. Once again, this will open another dialogue window, and from here, under System Variables you will need to edit the Path variable.

This will open a new dialogue window, and you will need to insert the follow values:

  • C:\Program Files (x86)\OpenCV\x64\vc17\bin
  • C:\gstreamer\1.0\msvc_x86_64\bin
  • C:\gstreamer\1.0\msvc_x86_64\lib
  • C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\bin
  • C:\Program Files (x86)\Intel\oneAPI\tbb\2022.0\lib

Each value should be on its own line. Once populated, you can click the OK button on both of the dialogue windows that popped up.

You must then log out of your user account, and log back in for these changes to be saved. Once you have logged back in, you can continue with the rest of this guide.

Checking the OpenCV Install

To confirm whether you have installed the OpenCV libraries correctly, you can run the C++ script that has been provided below. The outcome of this script should print the OpenCV version number (in this case 4.10.0) to the terminal window.

#include <iostream>
#include <opencv2/core/version.hpp>
#include <opencv2/core.hpp>

using namespace cv;

int main() {
    printf("OpenCV Version -> %s", CV_VERSION);
    return 0;
}

If you are using the JetBrains CLion IDE, you will need to modify the CMakeLists.txt file so it looks like the one below:

cmake_minimum_required(VERSION 3.29)
project(My_First_Project)

find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})

set(CMAKE_CXX_STANDARD 23)

add_executable(My_First_Project main.cpp)

target_link_libraries(My_First_Project ${OpenCV_LIBS})

The differences compared to the normal CMakeLists.txt file are the following lines:

  • find_package( OpenCV REQUIRED ): tells CMake to search for the OpenCV package installed on your system; The REQUIRED keyword indicates that OpenCV is mandatory for the project; if CMake cannot find OpenCV, the configuration process will stop with an error; if CMake finds OpenCV, it makes several variables available, including OpenCV_INCLUDE_DIRS (paths to the OpenCV header files) and OpenCV_LIBS (the libraries to link against)
  • include_directories( ${OpenCV_INCLUDE_DIRS} ): adds the OpenCV include directories (header files) to the project's list of include directories; OpenCV_INCLUDE_DIRS is a variable populated by find_package and contains the path(s) to the OpenCV header files that your project needs to include; it allows the compiler to find and use OpenCV's header files when compiling the project
  • target_link_libraries( My_First_Project ${OpenCV_LIBS} ): specifies the libraries that should be linked to your project target (in this case, My_First_Project); ${OpenCV_LIBS} contains the OpenCV libraries that are required for linking the executable or shared library; it ensures that when your project is compiled, it will be linked with OpenCV, allowing you to use OpenCV functions in your project

Hopefully, once you have compiled and built your script the version number of OpenCV will be printed to the terminal window. You should be met with a similar output to the following:

OpenCV Version -> 4.10.0

If you notice in the JetBrains CLion IDE that the OpenCV include directives a red, you will need to invalidate the cache of the IDE, and restart it. To do this, click on the File Menu system, and look for Invalidate Caches... A new dialogue window will pop up with many options. You can leave these options as default on click on the button labelled Invalidate and Restart.

This will restart the IDE and begin the index process again. This will search the machine for the OpenCV libraries and include directories to ensure that code completion is working as normal. Any issues, speak to a member of the module team in the lab sessions for the module.

Conclusion

That is the end of this guide on building, compiling and installing the OpenCV libraries. If you have followed all the necessary steps correctly, you should have a fully functional implementation of the OpenCV libraries, bespoke to your machine. This will enable you to complete any necessary programming based lab activities and assessments that you will participate with on this course.

Mistakes or Problems?

If you have spotted any errors or issues within this tutorial, you can e-mail Dr Ian Cornelius. Ensure to include in your message a description of the error or issue and a possible resolution. Also remember to include a URL to the page with the issue or error.