OpenCV

Language: CPP

ML/AI

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.

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.

Installation

linux: sudo apt install libopencv-dev
mac: brew install opencv
windows: Download pre-built binaries from https://opencv.org/releases/ and configure with CMake

Usage

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.

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.

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.

Error Handling

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.