Skip to main content

Overview

The C++ API is OpenCV’s native interface, providing direct access to all functionality with optimal performance. All OpenCV modules are written in C++ and offer the most complete feature set.

Installation

Building from Source

OpenCV uses CMake as its build system. Here’s how to build and install OpenCV from source:
# Install dependencies
sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config \
                     libavcodec-dev libavformat-dev libswscale-dev

# Clone the repository
git clone https://github.com/opencv/opencv.git
cd opencv
mkdir build && cd build

# Configure with CMake
cmake -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_INSTALL_PREFIX=/usr/local ..

# Build (use -j flag for parallel compilation)
make -j$(nproc)

# Install
sudo make install

Key CMake Options

Customize your build with these important CMake flags:
  • BUILD_EXAMPLES=ON - Build example applications
  • BUILD_opencv_world=ON - Build single combined library (Windows)
  • WITH_CUDA=ON - Enable CUDA support for GPU acceleration
  • WITH_TBB=ON - Enable Intel TBB for parallel processing
  • OPENCV_EXTRA_MODULES_PATH=<path> - Add opencv_contrib modules

Including OpenCV in Your Project

Using CMake

Create a CMakeLists.txt file:
cmake_minimum_required(VERSION 3.5)
project(MyOpenCVApp)

# Find OpenCV
find_package(OpenCV REQUIRED)

# Add your executable
add_executable(myapp main.cpp)

# Link OpenCV libraries
target_link_libraries(myapp ${OpenCV_LIBS})
Build your project:
mkdir build && cd build
cmake ..
make

Manual Compilation

g++ main.cpp -o myapp `pkg-config --cflags --libs opencv4`

Core Concepts

Including Headers

The main header includes all modules:
#include <opencv2/opencv.hpp>
Or include specific modules for faster compilation:
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp>

Namespace

All OpenCV C++ functions and classes are in the cv namespace:
using namespace cv;

// Or use explicit namespace
cv::Mat image;

Code Examples

Reading and Displaying an Image

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

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    // Read an image
    Mat image = imread("image.jpg", IMREAD_COLOR);
    
    if (image.empty()) {
        cout << "Could not open or find the image" << endl;
        return -1;
    }
    
    // Display the image
    namedWindow("Display Image", WINDOW_AUTOSIZE);
    imshow("Display Image", image);
    
    // Wait for a keystroke
    waitKey(0);
    
    return 0;
}

Face Detection with Cascade Classifier

#include <opencv2/objdetect.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <iostream>

using namespace std;
using namespace cv;

void detectAndDraw(Mat& img, CascadeClassifier& cascade, double scale) {
    vector<Rect> faces;
    Mat gray, smallImg;
    
    // Convert to grayscale
    cvtColor(img, gray, COLOR_BGR2GRAY);
    
    // Resize for faster detection
    double fx = 1 / scale;
    resize(gray, smallImg, Size(), fx, fx, INTER_LINEAR_EXACT);
    equalizeHist(smallImg, smallImg);
    
    // Detect faces
    cascade.detectMultiScale(smallImg, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, 
                            Size(30, 30));
    
    // Draw rectangles around detected faces
    for (size_t i = 0; i < faces.size(); i++) {
        Rect r = faces[i];
        Point center(cvRound((r.x + r.width*0.5)*scale), 
                    cvRound((r.y + r.height*0.5)*scale));
        int radius = cvRound((r.width + r.height)*0.25*scale);
        circle(img, center, radius, Scalar(255, 0, 0), 3, 8, 0);
    }
    
    imshow("Detection", img);
}

int main(int argc, const char** argv) {
    VideoCapture capture;
    Mat frame;
    CascadeClassifier cascade;
    double scale = 1.3;
    
    // Load the cascade classifier
    if (!cascade.load("haarcascade_frontalface_alt.xml")) {
        cerr << "ERROR: Could not load classifier cascade" << endl;
        return -1;
    }
    
    // Open camera
    if (!capture.open(0)) {
        cout << "Capture from camera failed" << endl;
        return 1;
    }
    
    cout << "Video capturing has been started..." << endl;
    
    for (;;) {
        capture >> frame;
        if (frame.empty())
            break;
        
        detectAndDraw(frame, cascade, scale);
        
        char c = (char)waitKey(10);
        if (c == 27 || c == 'q')
            break;
    }
    
    return 0;
}

Image Processing Pipeline

#include <opencv2/opencv.hpp>

using namespace cv;

int main() {
    // Read image
    Mat src = imread("input.jpg");
    
    // Convert to grayscale
    Mat gray;
    cvtColor(src, gray, COLOR_BGR2GRAY);
    
    // Apply Gaussian blur
    Mat blurred;
    GaussianBlur(gray, blurred, Size(5, 5), 0);
    
    // Edge detection
    Mat edges;
    Canny(blurred, edges, 50, 150);
    
    // Find contours
    vector<vector<Point>> contours;
    findContours(edges, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
    
    // Draw contours on original image
    Mat result = src.clone();
    drawContours(result, contours, -1, Scalar(0, 255, 0), 2);
    
    // Save result
    imwrite("output.jpg", result);
    
    return 0;
}

Working with Matrices

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

using namespace cv;
using namespace std;

int main() {
    // Create a 3x3 matrix
    Mat M = (Mat_<double>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
    cout << "M = " << endl << M << endl;
    
    // Create identity matrix
    Mat I = Mat::eye(4, 4, CV_64F);
    cout << "I = " << endl << I << endl;
    
    // Create matrix filled with zeros
    Mat Z = Mat::zeros(2, 3, CV_8UC1);
    cout << "Z = " << endl << Z << endl;
    
    // Matrix operations
    Mat A = Mat::eye(3, 3, CV_64F);
    Mat B = Mat::ones(3, 3, CV_64F);
    
    Mat C = A + B;  // Addition
    Mat D = A * B;  // Multiplication
    Mat E = A.t();  // Transpose
    
    // Element access
    double value = M.at<double>(1, 2);
    M.at<double>(0, 0) = 10;
    
    return 0;
}

Best Practices

Memory Management: OpenCV uses reference counting for Mat objects. No need for manual memory management in most cases.

Performance Tips

  1. Use appropriate data types: Choose the smallest data type that fits your needs
  2. Avoid unnecessary copies: Use references and ROI (Region of Interest) operations
  3. Enable parallel processing: Build with TBB or OpenMP support
  4. Use GPU acceleration: Enable CUDA modules for compute-intensive operations

Mat Operations

// Efficient: No data copy, just header copy
Mat A = imread("image.jpg");
Mat B = A;  // Shares data with A

// Deep copy when needed
Mat C = A.clone();

// Region of Interest (ROI) - no data copy
Rect roi(10, 10, 100, 100);
Mat imageROI = A(roi);
Modifying B will also modify A since they share the same data. Use .clone() or .copyTo() for independent copies.

Module Organization

OpenCV is organized into several modules:
  • core: Basic data structures and operations
  • imgproc: Image processing functions
  • imgcodecs: Image file reading and writing
  • videoio: Video I/O operations
  • highgui: GUI functionality
  • video: Video analysis
  • calib3d: Camera calibration and 3D reconstruction
  • features2d: 2D feature detection and description
  • objdetect: Object detection
  • dnn: Deep neural network module
  • ml: Machine learning

Resources

Next Steps

Build docs developers (and LLMs) love