C++ Program To Detect Face In A Video Using OpenCV Library

by | Mar 28, 2022 | C/C++, Coding

Home » Coding » Basic Coding » C/C++ » C++ Program To Detect Face In A Video Using OpenCV Library

Introduction Of The Project

Are you fascinated with face recognition technology? Do you want to go deep into OpenCV? Let’s try to implement a part of it today. So, we will implement a C++ program using which we will be able to detect faces inside the video. Sounds interesting! Right? So, let’s begin with the C++ Program to detect a face in a video using OpenCV Library.



  • VSCode/VisualStudio
  • C++ compiler
  • OpenCV
  • A Video file

Steps To Create A C++ Program To Detect A Face In A Video Using OpenCV Library

Step 1: Install VSCode Editor and C++ extension using the below link.



To install Visual Studio, use this link.

Step 2: Install the C++ compiler with the help of the below link


Step 3: Download OpenCV on your machine using the below link.


Step 4: Now, run the below code in the VSCode Editor/ Visual Studio.

Source Code

// Include required header files from the OpenCV directory
#include "C:\opencv\build\include\opencv2\objdetect.hpp"
#include "C:\opencv\build\include\opencv2\highgui.hpp"
#include "C:\opencv\build\include\opencv2\imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;

// Function Declaration to detect face
void detectFace(Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale);
string cascadeName, nestedCascadeName;

int main(int argc, const char** argv)
            // Class for video capturing from video files & provides C++ API for capturing video from cameras or reading video files.
            VideoCapture capture;
            Mat frame, image;

            // PreDefined trained XML classifiers with facial features
            CascadeClassifier cascade, nestedCascade;
            double scale = 1;

            // Loads a classifiers from "opencv\sources\data\haarcascades" directory

            // Before execution, change the paths according to your openCV location

            // To capture Video from WebCam replace the path with 0, else edit the path
            if (capture.isOpened())
                        // Capturing frames from the video
                        cout << "Face Detection is started...." << endl;
                        while (1)
                                    capture >> frame;
                                    if (frame.empty())
                                    Mat frame1 = frame.clone();

                                    // Calling the detect face function
                                    detectFace(frame1, cascade, nestedCascade, scale);
                                    char c = (char)waitKey(10);

                                    // Press q to exit from the window
                                    if (c == 27 || c == 'q' || c == 'Q')
                        cout << "Could not Open Video/Camera! ";
            return 0;

// Defination of Detect face function
void detectFace(Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale)
            vector<Rect> faces, faces2;
            Mat gray, smallImg;

            // To convert the frames to gray color
            cvtColor(img, gray, COLOR_BGR2GRAY);
            double fx = 1 / scale;

            // To resize the frames
            resize(gray, smallImg, Size(), fx, fx, INTER_LINEAR);
            equalizeHist(smallImg, smallImg);

            // To detect faces of different sizes using cascade classifier
            cascade.detectMultiScale(smallImg, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));

            // To draw circles around the faces
            for (size_t i = 0; i < faces.size(); i++)
                        Rect r = faces[i];
                        Mat smallImgROI;
                        vector<Rect> nestedObjects;
                        Point center;
                        Scalar color = Scalar(255, 0, 0);
                        int radius;

                        double aspect_ratio = (double)r.width / r.height;
                        if (0.75 < aspect_ratio && aspect_ratio < 1.3)
                                    center.x = cvRound((r.x + r.width * 0.5) * scale);
                                    center.y = cvRound((r.y + r.height * 0.5) * scale);
                                    radius = cvRound((r.width + r.height) * 0.25 * scale);

                                    // To draw circle
                                    circle(img, center, radius, color, 3, 8, 0);
                                    rectangle(img, Point(cvRound(r.x * scale), cvRound(r.y * scale)),
                                                Point(cvRound((r.x + r.width - 1) * scale),
                                                            cvRound((r.y + r.height - 1) * scale)), color, 3, 8, 0);
                        if (nestedCascade.empty())
                        smallImgROI = smallImg(r);


            // To display the detected face
            imshow("Face Detection", img);

Explanation Of The Code

At the beginning of the code, we have included header files that are used in our functions.

1. Then, we have declared the function to detect the face in the video/camera with the necessary arguments.

2. After this, we have defined our main function, in which we are capturing the video, converting it to its individual frame, and at last, calling our detect face function to draw a circle over the detected face.

3. Then, we have defined our detect face function, in which we are converting the frames of the video to grayscale using the cvtcolor() function.

4. Then, we resize each frame and detect the faces using a cascade classifier.

5. After this, we draw circles around the detected face using the cvround and circle function.

6. At last, we use the imshow() function to display the detected face.


The below screenshot shows how our C++ Program To Detect Face In A Video Using OpenCV Library has successfully detected faces in the video.

C++ Program To Detect Face In Video Using OpenCV Library

Things to Remember

  • Set the path of the compiler in VSCode along with system variables.
  • If you are using visual studio, then edit the general(dependencies – OpenCVpath) and input fields(Lib path of openCV) in C++ & Linker under the project – properties option.
  • Follow the steps written in the documentation after installing the compiler to avoid errors(If you are using VS Code).
  • Edit the path in the code as per the location of OpenCV in your system.


You May Also Like To Create…