Using CMake to build and install OpenCV for Python and C++ in Ubuntu 20.04

Aditya Kumar Singh
6 min readFeb 15, 2022

--

Source: http://mspoweruser.com/wp-content/uploads/2014/07/CMake-logo.png

CMake is an open-source, cross-platform family of tools designed to build, test, and package software, mainly used to control the software compilation process using simple platform and compiler independent configuration files and generate native makefiles and workspaces that can be used in the compiler environment of your choice.

Image Source: https://opencv.org/wp-content/uploads/2021/02/1_HfZmZayUqnYioPC9qTfd4A.png

OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library for image processing and machine learning tasks that support Tensorflow, Torch/Pytorch, and Caffe. It has C++, Python, Java, and MATLAB interfaces and supports Windows, Linux, Android, and Mac OS. The library is cross-platform, and you can pip install it (where you are using it with Python) with CPU support. Alternatively, where you want to use it with GPU support, you can build it from the source, which is more involved. This article is a walk-through on how to build OpenCV from a source (by cloning OpenCV repo) on a Linux Ubuntu machine. There are a lot of articles and Q&A, but all they have is scattered information that may not work in general, for which I thought to document this so that we can handle each edge case and try to install it perfectly on your Linux Ubuntu.

In this article, we’ll discuss on following points:

  • Install OpenCV from a source within a pythonic environment (e.g., conda environment) using CMake. Also, we’ll show you how to do it in Homefolder (i.e., in root).
  • What all essential libraries and packages do we need to pre-install so that OpenCV works for both C++ and Python 3.0 and above.
  • And at the end, how to configure if some known errors we face.

Since my machine consists of miniconda3, I prefer to build and install my OpenCV in a separate environment with Python3.8 (other than base). Again, it’s not only using conda; one can also use the virtualenv package to create virtual env. Also, one can install it without requiring any virtual environment (i.e., in the Home directory). Don’t worry; we’ll cover all the cases one by one in each step.

Step 0: Warm-Up

  • If you want to install it in an environment, then activate that environment first. For conda, write the following in a terminal (if you wish to install miniconda3, see this):
$ conda activate <your_env_name>
$ source <your_env_name>/bin/activate
  • If you don’t have any specific environment to start with, there is no need to write anything mentioned above.
  • Ensure that Python3.x is installed in your system (or your env). For mine, it was OpenCV 4.5.5, which requires a minimal version of Python3.2. Plus, I would suggest going with a conda or virtualenv virtual environment. You install your Python3.x there and do the following.

Step 1: Install required libraries and packages

  • Update and upgrade yourapt followed by installing some required packages like CMake, Git, python3.8-dev (make sure to change it to your required version), python3-numpy (specific to Python3). Here -y flag is for ‘yes’ response while installing packages.
$ sudo apt-get update && sudo apt-get upgrade$ sudo apt-get install -y build-essential cmake git unzip pkg-config make$ sudo apt-get install -y python3.8-dev python3-numpy libtbb2 libtbb-dev
  • OpenCV packages that aid in reading images and videos.
$ sudo apt-get install -y  libjpeg-dev libpng-dev libtiff-dev libgtk2.0-dev libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libeigen3-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev sphinx-common libtbb-dev yasm libfaac-dev libopencore-amrnb-dev libopencore-amrwb-dev libopenexr-dev libgstreamer-plugins-base1.0-dev libavutil-dev libavfilter-dev libavresample-dev

Step 2: Clone official OpenCV and OpenCV_contrib repo

  • First, create a folder named opencv_build, and then clone your required repositories into that folder as mentioned below:
$ mkdir ~/opencv_build && cd ~/opencv_build
$ git clone https://github.com/opencv/opencv
$ git clone https://github.com/opencv/opencv_contrib
$ cd ~/opencv_build/opencv
$ mkdir -p build && cd build

Step 3: Compile and Install OpenCV with CMake

  • It’s time to install all the build files of OpenCV into the build folder while compiling and installing it using CMake. We should also configure CMake so that it would also install nonfree modules by mentioning the flag value of OPENCV_ENABLE_NONFREE=ON. Before executing the following code, we have two options:
    1. CMAKE_INSTALL_PREFIX=/usr/local or
    2. CMAKE_INSTALL_PREFIX=$(python3 -c “import sys; print(sys.prefix)”)
    Since we intend to make OpenCV compatible with both C++ and Python3.x going with the first option is more agreeable. Because /usr/local contains aninclude folder that aids in the successful execution of#include <package>statements (header statements) in our C++ code. But if we want to have OpenCV installation only for Python3, then going with option 2 is more favorable as we might want our packages to be in the desired environment (if any). Plus, if you want GPU support, putWITH_CUDA=ON ;else WITH_CUDA=OFF.
$ cmake -D WITH_CUDA=OFF -D BUILD_TIFF=ON -D BUILD_opencv_java=OFF -D WITH_OPENGL=ON -D WITH_OPENCL=ON -D WITH_IPP=ON -D WITH_TBB=ON -D WITH_EIGEN=ON -D WITH_V4L=ON -D WITH_VTK=OFF -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_opencv_python2=OFF -D CMAKE_INSTALL_PREFIX=/usr/local -D PYTHON3_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") -D PYTHON3_PACKAGES_PATH=$(python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D PYTHON3_EXECUTABLE=$(which python3) -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules -D BUILD_EXAMPLES=ON ..
  • After the build files were generated, we used maketo install the build files as shown below. This compilation approximately takes 15 to 20 minutes, depending on the number of processors you have in your system. Note thatmake -j<# of cores>. And sudo ldconfig create the necessary links and cache to the most recent shared libraries found in the directories specified.
$ make -j8
$ sudo make install
$ sudo ldconfig

Step 4: Verify your installation

To verify the installation for both C++ and Python3, type the following commands:

  • For C++ bindings:
$ pkg-config --modversion opencv4Output:
4.5.5
  • Further, we may get errors like fatal error: opencv2/opencv_modules.hpp: No such file or directory #include “opencv2/opencv_modules.hpp". We need to mention the correct path for OpenCV header files to handle this. Since /usr/local/includehandle all such imports, either we:
    1. create a symlink in /usr/local/includefor opencv2 located at /usr/local/include/opencv4 by entering the following:
    $ sudo ln -s /usr/local/include/opencv4/opencv2 /usr/local/include/opencv2
    2. Or simply change your line for header file to:
    $ #include "opencv4/opencv2/<your_file_name>.hpp"
  • For Python3:
    If you haven’t installed OpenCV, keeping your virtual environment active, and have used the system’s Python3, you are good to go. Just enter the following:
$ python3 -c "import cv2; print(cv2.__version__)"Output:
'4.5.5-dev'
  • Otherwise, we need to link the OpenCV package in cv2folder at/usr/local/lib/python3.8/site-packages/ to site-packagesfolder of our virtual env with a .sofile as shown below (type the following with the required env ON):
$ cd ~/miniconda3/envs/rodo_env/lib/python3.8/site-packages/
$ ln -s /usr/local/lib/python3.8/site-packages/cv2/python-3.8/cv2.cpython-38-x86_64-linux-gnu.so cv2.so
$ python3 -c "import cv2; print(cv2.__version__)"
Output:
'4.5.5-dev'

Conclusion

We have shown a more involved way to install OpenCV both for C++ and Python3 on your Ubuntu 20.04 machine, which guarantees to run given all the requirements and preferences are satisfied. Even though installing the packaged version from the Ubuntu repository is easier, building OpenCV from the source gives you more flexibility. It should be your first option when installing OpenCV.

Here is the bashfile I used to install it one go:

bash-script for installation OpenCV from source

References:

If you have any questions or feedback, feel free to comment below. And if you liked it or it does come out helpful, do give a clap. Till then, Happy Coding.

--

--

Aditya Kumar Singh
Aditya Kumar Singh

Written by Aditya Kumar Singh

A Confused Nerd researching why he is so Confused.

Responses (1)