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 a Linux (Debian-based) 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 Debian-based operating system. For the purpose of this guide, the archives will be decompressed to the /opt directory. To decompress the files, you will need to install a tool called unzip, which can be installed using the following command:

$ sudo apt install unzip

Once unzip has been installed, the archives can be decompressed to the /opt directory using the following commands:

$ sudo unzip ~/Downloads/opencv-4.10.0.zip -d /opt
$ sudo unzip ~/Downloads/opencv_contrib-4.10.0.zip -d /opt

The sudo command has been used as the /opt directory requires administrator privileges when creating files and folders. The outcome of the two commands above will be two folders created in the /opt directory called opencv-4.10.0 and opencv_contrib-4.1.0, respectively. To tidy up the /opt directory, it would be wise to rename these folders and remove the version number. This can be achieved by using the following commands:

$ sudo mv /opt/opencv-4.10.0 /opt/opencv
$ sudo mv /opt/opencv_contrib-4.10.0 /opt/opencv_contrib

These commands will essentially rename the directories, dropping the version number suffix.

Finally, to ensure there is read and write access to these directories, which is important for building and compilation, we need to change the owner of these directories. To do this, we can use the chown command, which will change the user and group from root to the user of your machine. This can be achieved by using the following commands:

sudo chown -R $USER:$USER /opt/opencv
sudo chown -R $USER:$USER /opt/opencv_contrib

The -R flag will ensure that the change of ownership is applied recursively for each file and folder that exist within the directories. Whilst the $USER variable will automatically apply the username of the currently logged into account as the owner of the directories and files.

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 can use the follow command:

$ sudo apt install ffmpeg libavcodec-dev libavdevice-dev libavfilter-dev libavformat-dev libavutil-dev \
libxvidcore-dev libx264-dev libmp3lame-dev libopus-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-dev libva-dev \
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libmp3lame-dev libvorbis-dev libxine2-dev libv4l-dev v4l-utils \
libtbb-dev libatlas-base-dev gfortran libprotobuf-dev protobuf-compiler libgoogle-glog-dev libgflags-dev \
libgphoto2-dev libeigen3-dev libhdf5-dev doxygen libgtk-3-dev

The number of packages provided above is quite large and extensive, but it means that the OpenCV libraries you build will be compiled with efficiency in mind. Meaning that frames from a web camera can be loaded with a high framerate, compared to taking a precompiled source of OpenCV.

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 /opt. This can be achieved using the following command:

$ cd /opt/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_INSTALL_PREFIX=/usr/local \
        -D WITH_TBB=ON \
        -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 OPENCV_GENERATE_PKGCONFIG=ON \
        -D OPENCV_PC_FILE_NAME=opencv.pc \
        -D OPENCV_ENABLE_NONFREE=ON \
        -D OPENCV_EXTRA_MODULES_PATH=/opt/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)
  • CMAKE_INSTALL_PREFIX=/usr/local: specifies the directory where the compiled binaries, libraries, and headers will be installed; /usr/local is the default installation path for software that is not part of the system's package manager
  • 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
  • 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
  • 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=/opt/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 /opt/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: /opt/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 .
  [100%] Built target opencv_model_diagnostics

The output may not be exactly the same, but as long as the last output reads 100% 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. However, before you can do this, you need to make the files that have been built. Before you do this, you need to check the number of processes that can be executed at once on your system. To do this, you need to run the following command:

$ nproc
  20

The output of this command will be an integer number, and in the example above it is 20. This is a value that you need to use in the next command:

$ sudo make install -j20

Important

Remember that the sudo command is used to elevate privileges. In this instance, the apt command requires administrator privileges to install the necessary tools/libraries for Qt.

Make sure you replace the number above with the result of your nproc command. This will start the make install process, and it will enable the number of processes that can be run at a single time corresponding to the number that you inserted. In this case, twenty process can be run at one time during the make process before a new process is spawned.

This will install the OpenCV library to the folder we disclosed in the configuration process, in this case /usr/local. You should be met with an outcome similar to the one provided below:

$ sudo make install -j20
  -- Installing: /usr/local/bin/opencv_version
  -- Set non-toolchain portion of runtime path of "/usr/local/bin/opencv_version" to "/usr/local/lib"
  -- Installing: /usr/local/bin/opencv_model_diagnostics
  -- Set non-toolchain portion of runtime path of "/usr/local/bin/opencv_model_diagnostics" to "/usr/local/lib"

The sudo command has been used as the /usr/local directory requires administrator privileges when creating files and folders. Once the installation process has finished, you will want to include the installed libraries with your development environment. This can be achieved with the following command:

$ sudo /bin/bash -c 'echo "/usr/local/lib" >> /etc/ld.so.conf.d/opencv.conf'
$ sudo ldconfig

The ldconfig command will create the necessary links and cache to the most recent shared libraries that have been installed.

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 <opencv4/opencv2/core/version.hpp>
#include <opencv4/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

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.