YouTip LogoYouTip

Cpp Opencv Project Practice

C++ OpenCV Project Practice | Beginner's Tutorial

\\n\\n

OpenCV project practice is the process of applying theoretical knowledge to practical problems.

\\n\\n

Through project practice, you can consolidate your OpenCV skills and solve real-world computer vision problems.

\\n\\n

Here are common types of OpenCV projects:

\\n\\n
    \\n
  1. Image Processing Projects: such as image filters, image restoration, image enhancement, etc.
  2. \\n
  3. Object Detection and Tracking Projects: such as face detection, license plate recognition, moving object tracking, etc.
  4. \\n
  5. Deep Learning Projects: such as image classification, object detection, semantic segmentation, etc.
  6. \\n
  7. Video Processing Projects: such as video analysis, real-time video processing, video effects, etc.
  8. \\n
\\n\\n
\\n\\n

Simple Projects

\\n\\n

Image Filter Application

\\n\\n

Image filtering is one of the basic operations in image processing. By applying different filters, you can change the appearance and style of images.

\\n\\n

OpenCV provides rich functions to implement various image filter effects.

\\n\\n

Grayscale Filter

\\n\\n

Grayscale filter is the process of converting color images to grayscale images. Grayscale images have only one channel, where each pixel value represents brightness.

\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n\\nint main(){\\n\\n    cv::Mat image = cv::imread("input.jpg");\\n\\n    cv::Mat grayImage;\\n\\n    cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY);\\n\\n    cv::imwrite("gray_output.jpg", grayImage);\\n\\n    return 0;\\n\\n}
\\n\\n

Gaussian Blur

\\n\\n

Gaussian blur is a commonly used blur filter that can effectively remove noise from images.

\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n\\nint main(){\\n\\n    cv::Mat image = cv::imread("input.jpg");\\n\\n    cv::Mat blurredImage;\\n\\n    cv::GaussianBlur(image, blurredImage, cv::Size(15, 15), 0);\\n\\n    cv::imwrite("blurred_output.jpg", blurredImage);\\n\\n    return 0;\\n\\n}
\\n\\n

The following example implements an image filter application that supports multiple filter effects (such as grayscale, blur, edge detection, etc.).

\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n#include <iostream>\\n\\nusing namespace cv;\\nusing namespace std;\\n\\nint main(){\\n\\n    // Read image\\n    Mat image = imread("image.jpg");\\n\\n    if(image.empty()){\\n        cout<<"Error: Unable to Load image, please check if the path is correct."<< endl;\\n        return-1;\\n    }\\n\\n    // Grayscale conversion\\n    Mat gray;\\n    cvtColor(image, gray, COLOR_BGR2GRAY);\\n\\n    // Gaussian blur\\n    Mat blurred;\\n    GaussianBlur(image, blurred, Size(15, 15), 0);\\n\\n    // Edge detection\\n    Mat edges;\\n    Canny(image, edges, 100, 200);\\n\\n    // Display results\\n    imshow("Original Image", image);\\n    imshow("Gray Image", gray);\\n    imshow("Blurred Image", blurred);\\n    imshow("Edges", edges);\\n\\n    // Save result\\n    imwrite("gray_image.jpg", gray);\\n    imwrite("blurred_image.jpg", blurred);\\n    imwrite("edges.jpg", edges);\\n\\n    waitKey(0);\\n\\n    return 0;\\n\\n}
\\n\\n

Real-time Face Detection

\\n\\n

Real-time face detection is an important application in computer vision.

\\n\\n

OpenCV provides pre-trained Haar cascade classifiers that can be used to detect faces in images or videos.

\\n\\n

Implementation Steps:

\\n\\n
    \\n
  1. Load the Haar cascade classifier model.
  2. \\n
  3. Open the camera or video file.
  4. \\n
  5. Perform face detection on each frame.
  6. \\n
  7. Draw detection results and display.
  8. \\n
\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n#include <iostream>\\n\\nusing namespace cv;\\nusing namespace std;\\n\\nint main(){\\n\\n    // Load Haar cascade classifier\\n    CascadeClassifier faceCascade;\\n\\n    if(!faceCascade.load("haarcascade_frontalface_default.xml")){\\n        cout<<"Error: Failed to load Haar cascade classifier!"<< endl;\\n        return-1;\\n    }\\n\\n    // Open camera\\n    VideoCapture cap(0);\\n\\n    if(!cap.isOpened()){\\n        cout<<"Error: Failed to open camera!"<< endl;\\n        return-1;\\n    }\\n\\n    // Real-time face detection\\n    Mat frame;\\n\\n    while(true){\\n        cap >> frame;\\n\\n        if(frame.empty())break;\\n\\n        // Convert to grayscale image\\n        Mat gray;\\n        cvtColor(frame, gray, COLOR_BGR2GRAY);\\n\\n        // Detect faces\\n        vector<Rect> faces;\\n        faceCascade.detectMultiScale(gray, faces, 1.1, 3, 0, Size(30, 30));\\n\\n        // Draw detection results\\n        for(const auto& face : faces){\\n            rectangle(frame, face, Scalar(0, 255, 0), 2);\\n        }\\n\\n        // Display results\\n        imshow("Face Detection", frame);\\n\\n        // Press ESC key to exit\\n        if(waitKey(30)==27)break;\\n    }\\n\\n    // Release resources\\n    cap.release();\\n    destroyAllWindows();\\n\\n    return 0;\\n\\n}
\\n\\n

License Plate Recognition

\\n\\n

License plate recognition is one of the key technologies in intelligent transportation systems.

\\n\\n

OpenCV can be used for license plate detection and character recognition.

\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n\\nint main(){\\n\\n    cv::Mat image = cv::imread("car.jpg");\\n\\n    cv::Mat grayImage;\\n\\n    cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY);\\n\\n    cv::CascadeClassifier plateCascade;\\n\\n    plateCascade.load("haarcascade_russian_plate_number.xml");\\n\\n    std::vector<cv::Rect> plates;\\n\\n    plateCascade.detectMultiScale(grayImage, plates, 1.1, 2, 0| cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30));\\n\\n    for(const auto& plate : plates){\\n        cv::rectangle(image, plate, cv::Scalar(0, 255, 0), 2);\\n    }\\n\\n    cv::imwrite("plate_output.jpg", image);\\n\\n    return 0;\\n\\n}
\\n\\n
\\n\\n

Complex Projects

\\n\\n

AR Application Based on OpenCV

\\n\\n

Augmented Reality (AR) is a technology that overlays virtual information onto the real world.

\\n\\n

OpenCV can be used to implement simple AR applications, such as overlaying virtual objects on images.

\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n\\nint main(){\\n\\n    cv::Mat image = cv::imread("background.jpg");\\n\\n    cv::Mat overlay = cv::imread("overlay.png", cv::IMREAD_UNCHANGED);\\n\\n    cv::resize(overlay, overlay, cv::Size(100, 100));\\n\\n    cv::Mat roi = image(cv::Rect(50, 50, overlay.cols, overlay.rows));\\n\\n    overlay.copyTo(roi, overlay);\\n\\n    cv::imwrite("ar_output.jpg", image);\\n\\n    return 0;\\n\\n}
\\n\\n

Video Surveillance and Motion Detection

\\n\\n

Video surveillance and motion detection are important functions in security monitoring systems. OpenCV can be used to detect moving objects in videos.

\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n\\nint main(){\\n\\n    cv::VideoCapture cap(0);\\n\\n    if(!cap.isOpened()){\\n        std::cerr<<"Error opening video stream"<< std::endl;\\n        return-1;\\n    }\\n\\n    cv::Mat frame, prevFrame, diffFrame;\\n\\n    cap >> prevFrame;\\n\\n    cv::cvtColor(prevFrame, prevFrame, cv::COLOR_BGR2GRAY);\\n\\n    while(true){\\n        cap >> frame;\\n\\n        if(frame.empty())break;\\n\\n        cv::Mat grayFrame;\\n\\n        cv::cvtColor(frame, grayFrame, cv::COLOR_BGR2GRAY);\\n\\n        cv::absdiff(grayFrame, prevFrame, diffFrame);\\n\\n        cv::threshold(diffFrame, diffFrame, 30, 255, cv::THRESH_BINARY);\\n\\n        cv::imshow("Motion Detection", diffFrame);\\n\\n        if(cv::waitKey(1)==27)break;// ESC key to exit\\n\\n        prevFrame = grayFrame.clone();\\n    }\\n\\n    cap.release();\\n\\n    cv::destroyAllWindows();\\n\\n    return 0;\\n\\n}
\\n\\n

Multi-Object Tracking

\\n\\n

Multi-object tracking is a complex problem in computer vision, involving tracking multiple targets simultaneously in videos. OpenCV provides various tracking algorithms, such as KCF, MIL, and CSRT.

\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n#include <opencv2/tracking.hpp>\\n\\nint main(){\\n\\n    cv::VideoCapture cap("video.mp4");\\n\\n    if(!cap.isOpened()){\\n        std::cerr<<"Error opening video stream"<< std::endl;\\n        return-1;\\n    }\\n\\n    cv::Ptr<cv::MultiTracker> multiTracker = cv::MultiTracker::create();\\n\\n    cv::Mat frame;\\n\\n    cap >> frame;\\n\\n    std::vector<cv::Rect> bboxes;\\n\\n    cv::selectROIs("Tracking", frame, bboxes);\\n\\n    for(const auto& bbox : bboxes){\\n        multiTracker->add(cv::TrackerKCF::create(), frame, bbox);\\n    }\\n\\n    while(true){\\n        cap >> frame;\\n\\n        if(frame.empty())break;\\n\\n        multiTracker->update(frame);\\n\\n        for(const auto& bbox : multiTracker->getObjects()){\\n            cv::rectangle(frame, bbox, cv::Scalar(255, 0, 0), 2);\\n        }\\n\\n        cv::imshow("Multi-Object Tracking", frame);\\n\\n        if(cv::waitKey(1)==27)break;// ESC key to exit\\n    }\\n\\n    cap.release();\\n\\n    cv::destroyAllWindows();\\n\\n    return 0;\\n\\n}
\\n\\n
\\n\\n

Deep Learning Project: Object Detection (YOLO)

\\n\\n

Implement object detection using the YOLO model.

\\n\\n

Implementation Steps:

\\n\\n
    \\n
  1. Load the YOLO model and configuration file.
  2. \\n
  3. Load class labels.
  4. \\n
  5. Preprocess the input image.
  6. \\n
  7. Run the model and parse detection results.
  8. \\n
  9. Draw bounding boxes and display results.
  10. \\n
\\n\\n

Example

\\n\\n
#include <opencv2/opencv.hpp>\\n#include <opencv2/dnn.hpp>\\n#include <iostream>\\n\\nusing namespace cv;\\nusing namespace dnn;\\nusing namespace std;\\n\\nint main(){\\n\\n    // Load YOLO model\\n    Net net = readNet("yolov3.weights", "yolov3.cfg");\\n\\n    if(net.empty()){\\n        cout<<"Error: Failed to load YOLO model!"<< endl;\\n        return-1;\\n    }\\n\\n    // Load class labels\\n    ifstream classNamesFile("coco.names");\\n\\n    vector<string> classNames;\\n\\n    string className;\\n\\n    while(getline(classNamesFile, className)){\\n        classNames.push_back(className);\\n    }\\n\\n    // Load image\\n    Mat image = imread("image.jpg");\\n\\n    if(image.empty()){\\n        cout<<"Error: Unable to Load image, please check if the path is correct."<< endl;\\n        return-1;\\n    }\\n\\n    // Preprocess image\\n    Mat blob = blobFromImage(image, 1/255.0, Size(416, 416), Scalar(0, 0, 0), true, false);\\n\\n    net.setInput(blob);\\n\\n    // Forward pass\\n    vector<Mat> outs;\\n\\n    net.forward(outs, net.getUnconnectedOutLayersNames());\\n\\n    // Parse detection results\\n    float confThreshold =0.5;// Confidence threshold\\n\\n    vector<int> classIds;\\n\\n    vector<float> confidences;\\n\\n    vector<Rect> boxes;\\n\\n    for(const auto& output : outs){\\n        for(int i =0; i < output.rows; i++){\\n            Mat scores = output.row(i).colRange(5, output.cols);\\n\\n            Point classIdPoint;\\n\\n            double confidence;\\n\\n            minMaxLoc(scores, nullptr, &confidence, nullptr, &classIdPoint);\\n\\n            if(confidence > confThreshold){\\n                int centerX =static_cast<int>(output.at<float>(i, 0)* image.cols);\\n\\n                int centerY =static_cast<int>(output.at<float>(i, 1)* image.rows);\\n\\n                int width =static_cast<int>(output.at<float>(i, 2)* image.cols);\\n\\n                int height =static_cast<int>(output.at<float>(i, 3)* image.rows);\\n\\n                int left = centerX - width /2;\\n\\n                int top = centerY - height /2;\\n\\n                classIds.push_back(classIdPoint.x);\\n\\n                confidences.push_back(static_cast<float>(confidence));\\n\\n                boxes.push_back(Rect(left, top, width, height));\\n            }\\n        }\\n    }\\n\\n    // Non-maximum suppression\\n    float nmsThreshold =0.4;// NMS Threshold\\n\\n    vector<int> indices;\\n\\n    NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);\\n\\n    // Draw detection results\\n    for(int idx : indices){\\n        Rect box = boxes;\\n\\n        rectangle(image, box, Scalar(0, 255, 0), 2);\\n\\n        string label = format("%s: %.2f", classNames[classIds].c_str(), confidences);\\n\\n        putText(image, label, Point(box.x, box.y-10), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0), 2);\\n    }\\n\\n    // Display results\\n    imshow("Object Detection", image);\\n\\n    waitKey(0);\\n\\n    return 0;\\n\\n}
\\n\\n
\\n\\n

Video Processing Project: Real-time Video Effects

\\n\\n

Implement a real-time video effects application that supports multiple effects (such as edge detection, blur, color inversion, etc.).

← Cpp OpencvCpp Opencv Video β†’