OpenCV for C++: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is OpenCV and why is it needed?



OpenCV (Open Source Computer Vision Library) is a cross-platform open-source library designed for computer vision and machine learning tasks. It provides over 2,500 optimized algorithms that cover virtually all areas of computer vision: from simple image processing (filtering, geometric transformations) to complex tasks (face recognition, object tracking, 3D reconstruction, video analysis).



The library is written in C++ and C, which ensures high performance, and has bindings for Python, Java, MATLAB, and other languages. In this guide, we will focus on using OpenCV from C++ — this is the optimal choice for production systems where speed and efficient memory management are critical.



Why is OpenCV needed?

  • Image processing: resizing, rotation, filtering, contrast enhancement, color correction.
  • Video analysis: reading/writing video, motion detection, object tracking.
  • Object recognition: faces, cars, text (OCR), gestures.
  • Camera calibration: distortion removal, stereo vision.
  • Machine learning: built-in classifiers (SVM, KNN, Decision Trees) and integration with DNN (Deep Neural Networks) for working with TensorFlow, Caffe, PyTorch models.


Installing OpenCV for C++



Unlike Python, where a single command pip install opencv-python suffices, installing OpenCV for C++ requires compilation or using pre-built binary packages. Let's look at the main methods.



1. Installation via package manager (Linux/macOS)

Ubuntu/Debian:

sudo apt updatesudo apt install libopencv-dev

macOS (Homebrew):

brew install opencv


2. Installation via vcpkg (Windows, Linux, macOS)

vcpkg is a cross-platform package manager from Microsoft. First, install vcpkg:

git clone https://github.com/Microsoft/vcpkg.gitcd vcpkg./bootstrap-vcpkg.sh  # Linux/macOS.\\bootstrap-vcpkg.bat # Windows

Then install OpenCV:

./vcpkg install opencv4

After installation, link the library in CMake:

cmake_minimum_required(VERSION 3.10)project(MyOpenCVProject)find_package(OpenCV REQUIRED)add_executable(main main.cpp)target_link_libraries(main ${OpenCV_LIBS})


3. Building from source (advanced level)

This method gives maximum control over included modules and optimizations:

git clone https://github.com/opencv/opencv.gitcd opencvmkdir build && cd buildcmake -D CMAKE_BUILD_TYPE=RELEASE \      -D CMAKE_INSTALL_PREFIX=/usr/local \      -D WITH_TBB=ON \      -D WITH_V4L=ON \      -D WITH_QT=ON \      -D WITH_OPENGL=ON ..make -j$(nproc)sudo make install


Quick start: loading and displaying an image

Let's verify that OpenCV is installed correctly by writing a simple program that loads an image, converts it to grayscale, and displays it.



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

int main() { // Load the image cv::Mat img = cv::imread("example.jpg"); if (img.empty()) { std::cerr << "Failed to load image!" << std::endl; return -1; }

// Convert to grayscale cv::Mat gray; cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);

// Display both images cv::imshow("Original", img); cv::imshow("Gray", gray);

// Wait for a key press cv::waitKey(0); cv::destroyAllWindows();

return 0;}

Recommendations