> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/opencv/opencv/llms.txt
> Use this file to discover all available pages before exploring further.

# C++ API

> Learn how to use OpenCV's native C++ API, build from source, and write high-performance computer vision applications

## 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:

<Tabs>
  <Tab title="Linux">
    ```bash theme={null}
    # 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
    ```
  </Tab>

  <Tab title="macOS">
    ```bash theme={null}
    # Install dependencies using Homebrew
    brew install cmake pkg-config

    # 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
    make -j$(sysctl -n hw.ncpu)

    # Install
    sudo make install
    ```
  </Tab>

  <Tab title="Windows">
    ```bash theme={null}
    # Clone the repository
    git clone https://github.com/opencv/opencv.git
    cd opencv
    mkdir build
    cd build

    # Configure with CMake (adjust paths as needed)
    cmake -G "Visual Studio 17 2022" -A x64 \
          -DCMAKE_BUILD_TYPE=Release ..

    # Build using CMake or Visual Studio
    cmake --build . --config Release

    # Install
    cmake --install .
    ```
  </Tab>
</Tabs>

### 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 theme={null}
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:

```bash theme={null}
mkdir build && cd build
cmake ..
make
```

### Manual Compilation

```bash theme={null}
g++ main.cpp -o myapp `pkg-config --cflags --libs opencv4`
```

## Core Concepts

### Including Headers

The main header includes all modules:

```cpp theme={null}
#include <opencv2/opencv.hpp>
```

Or include specific modules for faster compilation:

```cpp theme={null}
#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:

```cpp theme={null}
using namespace cv;

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

## Code Examples

### Reading and Displaying an Image

```cpp theme={null}
#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

```cpp theme={null}
#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

```cpp theme={null}
#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

```cpp theme={null}
#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

<Note>
  **Memory Management**: OpenCV uses reference counting for Mat objects. No need for manual memory management in most cases.
</Note>

### 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

```cpp theme={null}
// 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);
```

<Warning>
  Modifying `B` will also modify `A` since they share the same data. Use `.clone()` or `.copyTo()` for independent copies.
</Warning>

## 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

* [OpenCV C++ API Reference](https://docs.opencv.org/4.x/)
* [OpenCV Tutorials](https://docs.opencv.org/4.x/d9/df8/tutorial_root.html)
* [OpenCV GitHub Repository](https://github.com/opencv/opencv)
* [Sample Code](https://github.com/opencv/opencv/tree/4.x/samples/cpp)

## Next Steps

* Explore the [Image Processing](/modules/imgproc) module
* Learn about [Video Analysis](/modules/video)
* Try [Object Detection](/modules/objdetect) features
