2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
Trending Now DSA Web Tech Foundational Courses Data Science Practice Problem Python M
OpenCV C++ Program for Face Detection
Last Updated : 12 Apr, 2023
This program uses the OpenCV library to detect faces in a live stream
from webcam or in a video file stored in the local machine. This program
detects faces in real time and tracks it. It uses pre-trained XML
classifiers for the same. The classifiers used in this program have facial
features trained in them. Different classifiers can be used to detect
different objects. Requirements for running the program: 1) OpenCV
must be installed on the local machine. 2) Paths to the classifier XML
files must be given before the execution of the program. These XML
files can be found in the OpenCV directory “opencv/data/haarcascades”.
3) Use 0 in capture.open(0) to play webcam feed. 4) For detection in a
local video provide the path to the video.
(capture.open(“path_to_video”)). Implementation:
CPP
// CPP program to detects face in a video
// Include required header files from OpenCV directory
#include "/usr/local/include/opencv2/objdetect.hpp"
#include "/usr/local/include/opencv2/highgui.hpp"
#include "/usr/local/include/opencv2/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
// Function for Face Detection
void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade, double scale );
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 1/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
string cascadeName, nestedCascadeName;
int main( int argc, const char** argv )
{
// VideoCapture class for playing video for which faces to be detected
VideoCapture capture;
Mat frame, image;
// PreDefined trained XML classifiers with facial features
CascadeClassifier cascade, nestedCascade;
double scale=1;
// Load classifiers from "opencv/data/haarcascades" directory
nestedCascade.load( "../../haarcascade_eye_tree_eyeglasses.xml" ) ;
// Change path before execution
cascade.load( "../../haarcascade_frontalcatface.xml" ) ;
// Start Video..1) 0 for WebCam 2) "Path to Video" for a Local Video
capture.open(0);
if( capture.isOpened() )
{
// Capture frames from video and detect faces
cout << "Face Detection Started...." << endl;
while(1)
{
capture >> frame;
if( frame.empty() )
break;
Mat frame1 = frame.clone();
detectAndDraw( frame1, cascade, nestedCascade, scale );
char c = (char)waitKey(10);
// Press q to exit from window
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
}
else
cout<<"Could not Open Camera";
return 0;
}
void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale)
{
vector<Rect> faces, faces2;
Mat gray, smallImg;
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 2/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
cvtColor( img, gray, COLOR_BGR2GRAY ); // Convert to Gray Scale
double fx = 1 / scale;
// Resize the Grayscale Image
resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR );
equalizeHist( smallImg, smallImg );
// Detect faces of different sizes using cascade classifier
cascade.detectMultiScale( smallImg, faces, 1.1,
2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) );
// 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); // Color for Drawing tool
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);
circle( img, center, radius, color, 3, 8, 0 );
}
else
rectangle( img, cvPoint(cvRound(r.x*scale), cvRound(r.y*scale)
cvPoint(cvRound((r.x + r.width-1)*scale),
cvRound((r.y + r.height-1)*scale)), color, 3, 8, 0);
if( nestedCascade.empty() )
continue;
smallImgROI = smallImg( r );
// Detection of eyes in the input image
nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2
0|CASCADE_SCALE_IMAGE, Size(30, 30
// Draw circles around eyes
for ( size_t j = 0; j < nestedObjects.size(); j++ )
{
Rect nr = nestedObjects[j];
center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale);
center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale);
radius = cvRound((nr.width + nr.height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
}
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 3/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
// Show Processed Image with detected faces
imshow( "Face Detection", img );
}
Output:
Face Detection
Next Article: Opencv Python Program for face detection References: 1)
http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.h
tml 2)
http://docs.opencv.org/2.4/doc/tutorials/objdetect/cascade_classifier/casc
ade_classifier.html
Get 90% Course fee refund on completing 90% course in 90 days!
Take the Three 90 Challenge today.
The next 90 Days of focus & determination can unlock your full
potential. The Three 90 challenge has started and this is your chance
to upskill and get 90% refund. What more motivation do you need?
Start the challenge right away!
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 4/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
Comment More info
Next Article
Advertise with us Back-Face Detection Method
Similar Reads
Back-Face Detection Method
When we project 3-D objects on a 2-D screen, we need to detect the
faces that are hidden on 2D. Back-Face detection, also known as Plane…
3 min read
Python Program to detect the edges of an image using OpenCV | So…
The following program detects the edges of frames in a livestream video
content. The code will only compile in linux environment. Make sure that…
4 min read
Nikhil Kumar - Geek on the top | "Never follow the crowd, be the fac…
Geek on the top is all about success stories of Geeks who are working
hard to chase their goals and are the inspiration for other geeks. Nikhil…
4 min read
Python | Program to extract frames using OpenCV
OpenCV comes with many powerful video editing functions. In the current
scenario, techniques such as image scanning and face recognition can be…
2 min read
OpenCV | Hands on Image Brightness
Brightness means to change the value of each and every image pixel. This
change can be done by either increasing or decreasing the pixel values o…
3 min read
Detecting objects of similar color in Python using OpenCV
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 5/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
OpenCV is a library of programming functions mainly aimed at real-time
computer vision. In this article, we will see how to get the objects of the…
3 min read
Displaying the coordinates of the points clicked on the image using…
OpenCV helps us to control and manage different types of mouse events
and gives us the flexibility to operate them. There are many types of…
3 min read
Webcam QR code scanner using OpenCV
In this article, we're going to see how to perform QR code scanning using
a webcam. Before starting, You need to know how this process is going t…
3 min read
Erosion and Dilation of images using OpenCV in python
Morphological operations are a set of operations that process images
based on shapes. They apply a structuring element to an input image an…
2 min read
Printing source code of a C program itself
Printing the source code of a C program itself is different from the Quine
problem. Here we need to modify any C program in a way that it prints…
2 min read
Program to compute division upto n decimal places
Given 3 numbers x, y and n compute the division (x/y) upto n decimal
places. Examples : Input : x = 22, y = 7, n = 10Output :…
7 min read
Program to print the arrow pattern
Given the value of n, print the arrow pattern.Examples : Input : n = 5
Output : * ** *** **** ***** **** *** ** * Input : n = 7 Output : * ** *** ****…
10 min read
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 6/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
Program to print Fibonacci Triangle
Given the value of n(n < 10), i.e, number of lines, print the Fibonacci
triangle. Examples: Input : n = 5 Output : 1 1 2 3 5 8 13 21 34 55 89 144…
7 min read
Program for triangular pattern (mirror image around 0)
Given the value of n, print the pattern.Examples : Input : n = 5 Output : 0
101 21012 3210123 432101234 Input : n = 7 Output : 0 101 21012…
5 min read
Program for Fibonacci numbers in PL/SQL
The Fibonacci numbers are the numbers in the following integer
sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. In mathematical…
1 min read
Program to check Involutory Matrix
Given a matrix and the task is to check matrix is involutory matrix or not.
Involutory Matrix: A matrix is said to be involutory matrix if matrix…
7 min read
Program to print the pattern "GFG"
In this article, given the value of n(length of the alphabet) and k(width of
the alphabet) we will learn how to print the pattern "GFG" using stars a…
8 min read
Java Program to Append a String in an Existing File
In Java, we can append a string in an existing file using FileWriter which
has an option to open a file in append mode. Java FileWriter class is use…
3 min read
"Campus Content Partner" Program by GeeksforGeeks
About the Program : Campus Content Partner is a stipend based program
focused on choosing GeeksforGeeks representatives at various campuse…
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 7/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
2 min read
LEX program to add line numbers to a given file
Lex is a computer program that generates lexical analyzers and was
written by Mike Lesk and Eric Schmidt. Lex reads an input stream…
2 min read
8086 program for selection sort
Problem - Write an assembly language program in 8086 microprocessor
to sort a given array of n numbers using Selection Sort. Assumptions -…
3 min read
Lex Program to count number of words
Lex is a computer program that generates lexical analyzers and was
written by Mike Lesk and Eric Schmidt. Lex reads an input stream…
1 min read
Splint -- A C program verifier
C compiler is pretty vague in many aspects of checking program
correctness, particularly in type checking. Careful use of prototyping of…
1 min read
8085 program to show masking of lower and higher nibbles of 8 bit…
Problem - Write an assembly language program in 8085 microprocessor
to show masking of lower and higher nibble of 8 bit number. Example -…
3 min read
8085 program to exchange content of HL register pair with DE regist…
Problem - Write an assembly language program in 8085 microprocessor
to exchange content of HL register pair with DE register pair using PUSH…
2 min read
8085 program to count total even numbers in series of 10 numbers
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 8/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
Program - Write an assembly language program in 8085 microprocessor
to count even numbers in a series of 10 numbers. Example - Assumption…
4 min read
8085 program for pulse waveform
Problem - Write a program to generate continuous square wave. Use D0
bit to output the square wave. The required waveform is: Explanation -…
2 min read
8085 program to count total odd numbers in series of 10 numbers
Program - Write an assembly language program in 8085 microprocessor
to count odd numbers in series of 10 numbers. Example - Assumption -…
3 min read
Lex program to take input from file and remove multiple spaces, lin…
FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for
generating lexical analyzers (scanners or lexers) written by Vern Paxson …
2 min read
Program to check if a matrix is Binary matrix or not
Given a matrix, the task is to check if that matrix is a Binary Matrix. A
Binary Matrix is a matrix in which all the elements are either 0 or 1. It is…
5 min read
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305)
Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 9/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
Buddh Nagar, Uttar Pradesh, 201305
Advertise with us
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Privacy Policy GfG Weekly Contest
Careers Offline Classes (Delhi/NCR)
In Media DSA in JAVA/C++
Contact Us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community
Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial
Data Science & ML Web Technologies
Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning JavaScript
ML Maths TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS
Python Tutorial Computer Science
Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 10/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
Python Interview Question Engineering Maths
DevOps System Design
Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions
School Subjects Commerce
Mathematics Accountancy
Physics Business Studies
Chemistry Economics
Biology Management
Social Science HR Management
English Grammar Finance
Income Tax
Databases Preparation Corner
SQL Company-Wise Recruitment Process
MYSQL Resume Templates
PostgreSQL Aptitude Preparation
PL/SQL Puzzles
MongoDB Company-Wise Preparation
Companies
Colleges
Competitive Exams More Tutorials
JEE Advanced Software Development
UGC NET Software Testing
UPSC Product Management
SSC CGL Project Management
SBI PO Linux
SBI Clerk Excel
IBPS PO All Cheat Sheets
IBPS Clerk Recent Articles
Free Online Tools Write & Earn
Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator
DSA/Placements Development/Testing
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 11/12
2/24/25, 5:13 PM OpenCV C++ Program for Face Detection - GeeksforGeeks
DSA - Self Paced Course JavaScript Full Course
DSA in JavaScript - Self Paced Course React JS Course
DSA in Python - Self Paced React Native Course
C Programming Course Online - Learn C with Data Structures Django Web Development Course
Complete Interview Preparation Complete Bootstrap Course
Master Competitive Programming Full Stack Development - [LIVE]
Core CS Subject for Interview Preparation JAVA Backend Development - [LIVE]
Mastering System Design: LLD to HLD Complete Software Testing Course [LIVE]
Tech Interview 101 - From DSA to System Design [LIVE] Android Mastery with Kotlin [LIVE]
DSA to Development [HYBRID]
Placement Preparation Crash Course [LIVE]
Machine Learning/Data Science Programming Languages
Complete Machine Learning & Data Science Program - [LIVE] C Programming with Data Structures
Data Analytics Training using Excel, SQL, Python & PowerBI - C++ Programming Course
[LIVE] Java Programming Course
Data Science Training Program - [LIVE] Python Full Course
Mastering Generative AI and ChatGPT
Data Science Course with IBM Certification
Clouds/Devops GATE
DevOps Engineering GATE CS & IT Test Series - 2025
AWS Solutions Architect Certification GATE DA Test Series 2025
Salesforce Certified Administrator Course GATE CS & IT Course - 2025
GATE DA Course 2025
GATE Rank Predictor
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
https://www.geeksforgeeks.org/opencv-c-program-face-detection/ 12/12