Skip to content

OpenCV

The computer vision library — image processing, detection, tracking and calibration.

AI & Machine LearningML/AIC++

What it is

OpenCV (Open Source Computer Vision Library) is a powerful C++ library for computer vision, image processing, and machine learning. It provides a wide range of algorithms for real-time image and video analysis.

OpenCV in C++ provides classes and functions to read, write, process images and videos, and perform advanced computer vision tasks. It supports matrices (cv::Mat), image filters, feature detection, machine learning, and GPU acceleration.

Licence
Apache 2.0
Watch for
OpenCV reads images as BGR, not RGB — a perennial source of confusion

When to use it

The question documentation cannot answer for you — because it cannot recommend something else.

Reach for it when

  • Any image or video processing task: filtering, feature detection, camera calibration, tracking
  • You need real-time performance with optional GPU acceleration

Look elsewhere when

  • You only need to load and resize images — a smaller library will do without OpenCV's size
  • The task is purely deep-learning inference, where a dedicated runtime may fit better

Installation

sudo apt install libopencv-dev

Getting started

The smallest useful thing you can do with it, and what each part means.

Read and display an image
#include <opencv2/opencv.hpp>
int main() {
    cv::Mat img = cv::imread("image.jpg");
    if(img.empty()) return -1;
    cv::imshow("Image", img);
    cv::waitKey(0);
    return 0;
}
Reads an image from file and displays it in a window until a key is pressed.
Convert to grayscale
#include <opencv2/opencv.hpp>
int main() {
    cv::Mat img = cv::imread("image.jpg");
    cv::Mat gray;
    cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
    cv::imshow("Gray", gray);
    cv::waitKey(0);
    return 0;
}
Converts a color image to grayscale using OpenCV’s color conversion function.

Advanced usage

Where the library earns its place over a simpler alternative.

Canny edge detection
#include <opencv2/opencv.hpp>
int main() {
    cv::Mat img = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
    cv::Mat edges;
    cv::Canny(img, edges, 100, 200);
    cv::imshow("Edges", edges);
    cv::waitKey(0);
    return 0;
}
Detects edges in a grayscale image using the Canny algorithm.
Video capture from webcam
#include <opencv2/opencv.hpp>
int main() {
    cv::VideoCapture cap(0);
    if(!cap.isOpened()) return -1;
    cv::Mat frame;
    while(true) {
        cap >> frame;
        if(frame.empty()) break;
        cv::imshow("Webcam", frame);
        if(cv::waitKey(1) == 'q') break;
    }
    return 0;
}
Captures video from the default webcam and displays it in real-time.
Drawing shapes
#include <opencv2/opencv.hpp>
int main() {
    cv::Mat img = cv::Mat::zeros(512,512,CV_8UC3);
    cv::line(img, cv::Point(0,0), cv::Point(511,511), cv::Scalar(255,0,0), 5);
    cv::rectangle(img, cv::Point(100,100), cv::Point(300,300), cv::Scalar(0,255,0), 3);
    cv::circle(img, cv::Point(256,256), 50, cv::Scalar(0,0,255), -1);
    cv::imshow("Shapes", img);
    cv::waitKey(0);
    return 0;
}
Draws lines, rectangles, and circles on an empty image using OpenCV drawing functions.
Face detection using Haar cascades
#include <opencv2/opencv.hpp>
int main() {
    cv::CascadeClassifier face_cascade;
    face_cascade.load("haarcascade_frontalface_default.xml");
    cv::Mat img = cv::imread("group.jpg");
    cv::Mat gray;
    cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
    std::vector<cv::Rect> faces;
    face_cascade.detectMultiScale(gray, faces);
    for(auto &f : faces) cv::rectangle(img, f, cv::Scalar(255,0,0), 2);
    cv::imshow("Faces", img);
    cv::waitKey(0);
    return 0;
}
Detects faces in an image using pre-trained Haar cascade classifiers and draws rectangles around them.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

cv::Exception: OpenCV(…): error
Check image paths and ensure the file exists before reading.
Segmentation fault
Ensure Mat objects are initialized and not empty before performing operations.
CascadeClassifier load failed
Verify the path to Haar cascade XML files and that they are accessible.

Best practices

  • Use cv::Mat for all image operations for performance and flexibility.
  • Release resources properly and close windows to prevent memory leaks.
  • Use proper color space conversions when needed (BGR, RGB, GRAY).
  • Optimize pipelines for real-time applications using GPU or multi-threading.
  • Keep pre-trained models and classifiers organized for reuse.

Alternatives

Comparable options, and the reason you would pick one over the other.

Background

Why it exists, and what it was reacting to.

OpenCV was originally developed by Intel in 1999 to advance computer vision research. It provides highly optimized algorithms for image processing, object detection, facial recognition, and more. OpenCV is widely used in industry and research for real-time applications and robotics.