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:

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:
Build your project:

Manual Compilation

Core Concepts

Including Headers

The main header includes all modules:
Or include specific modules for faster compilation:

Namespace

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

Code Examples

Reading and Displaying an Image

Face Detection with Cascade Classifier

Image Processing Pipeline

Working with Matrices

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

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