Face Detection using Haar-Cascade Classifier

class CascadeClassifier - Cascade classifier class for object detection

CascadeClassifier::CascadeClassifier(const string& filename) // Constructor - Loads a classifier from a file
CascadeClassifier face_cascade( "C:/OpenCV243/data/Haarcascades/haarcascade_frontalface_alt2.xml" );

bool CascadeClassifier::empty() const // Checks whether the classifier has been loaded.bool CascadeClassifier::load(const string& filename) // Loads a classifier from a file
CascadeClassifier face_cascade;
face_cascade.load( "C:/OpenCV243/data/Haarcascades/haarcascade_frontalface_alt2.xml" ); 

bool CascadeClassifier::read(const FileNode& node) // Reads a classifier from a FileStorage node

void CascadeClassifier::detectMultiScale(const Mat& image, vector<Rect>& objects, double scaleFactor=1.1, int minNeighbors=3, int flags=0, Size minSize=Size(), Size maxSize=Size())
// Detects objects of different sizes in the input image.
// The detected objects are returned as a list of rectangles.

  • cascade – Haar classifier cascade (OpenCV 1.x API only). It can be loaded from XML or YAML file using Load(). When the cascade is not needed anymore, release it using cvReleaseHaarClassifierCascade(&cascade).
  • image – Matrix of the type CV_8U containing an image where objects are detected.
  • objects – Vector of rectangles where each rectangle contains the detected object.
  • scaleFactor – Parameter specifying how much the image size is reduced at each image scale.
  • minNeighbors – Parameter specifying how many neighbors each candidate rectangle should have to retain it.
  • flags – Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. It is not used for a new cascade.
  • minSize – Minimum possible object size. Objects smaller than that are ignored.
  • maxSize – Maximum possible object size. Objects larger than that are ignored.
bool CascadeClassifier::setImage(Ptr<FeatureEvaluator>& feval, const Mat& image)
// Sets an image for detection
  • cascade – Haar classifier cascade (OpenCV 1.x API only). See CascadeClassifier::detectMultiScale() for more information.
  • feval – Pointer to the feature evaluator used for computing features.
  • image – Matrix of the type CV_8UC1 containing an image where the features are computed
int CascadeClassifier::runAt(Ptr<FeatureEvaluator>& feval, Point pt, double& weight)
// Runs the detector at the specified point. The function returns 1 if the cascade classifier detects an object in the given location. Otherwise, it returns negated index of the stage at which the candidate has been rejected.
  • cascade – Haar classifier cascade (OpenCV 1.x API only). See CascadeClassifier::detectMultiScale() for more information.
  • feval – Feature evaluator used for computing features.
  • pt – Upper left point of the window where the features are computed. Size of the window is equal to the size of training images.


  1. Read the image.
  2. Load Face cascade (CascadeClassifier > load)
  3. Detect faces (detectMultiScale)
  4. Draw circles on the detected faces (ellipse)
  5. Show the result.



#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

int main( )
    Mat image;
    image = imread("lena.jpg", CV_LOAD_IMAGE_COLOR);  
    namedWindow( "window1", 1 );   imshow( "window1", image );

    // Load Face cascade (.xml file)
    CascadeClassifier face_cascade;
    face_cascade.load( "C:/OpenCV243/data/Haarcascades/haarcascade_frontalface_alt2.xml" );

    // Detect faces
    std::vector<Rect> faces;
    face_cascade.detectMultiScale( image, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );

    // Draw circles on the detected faces
    for( int i = 0; i < faces.size(); i++ )
        Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
        ellipse( image, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
    imshow( "Detected Face", image );
    return 0;


  1. This comment has been removed by a blog administrator.

  2. Hi! I was wondering why my xml file won't load? I put the xml files in all directories but my program can't still load the file. Any idea why is this happening?

    1. Try giving the path as:

      "F(can be any drive):\\SomeFolder\\AnotherFolder\\your.xml"

      The key things to note here are
      -> don't give the path like this: "thisIsInMyWorkingDirectory.xml" rather put this file in other folder or a drive and then
      -> Give double slashes for the path. If you see the source code then you'll understand why we are doing this

  3. Hey I have the same problem. I cant load the xml file

  4. Hello,
    When I run the code I got an error message.

    First "abort() has been called" and then the message in the command window is:
    "OpenCV Error: Assertion failed (axes.width >= 0 && axes.height >= 0 && thickness <= 255 && 0 <= shift && shift <= XY_SHIFT) in cv::ellipse, file C:\bu
    ilds\master_PackSlave-win32-vc12-shared\opencv\modules\imgproc\src\drawing.cpp, line 1772"

    I need urgently help. Would someone please help me with this issue?

    Thanks in advance!

  5. Hi, your blog is awesome.
    I am 2 week older in image processing field.
    I need to develop own classifiers to detect some special symbol or shape.
    Can you upload or give any simple reference to do so ?

  6. The Best Delphi sample code I ever had for Face Detection.
    GOD bless the good hearted Author.


  7. First time I commented in a blog! I really enjoy it. You have an awesome post. Please do more articles like this. I'm gonna come back surely. God bless.


  8. Dear Sir.. Thank you very much... I have two issues:
    1- I got some problem with (imread) , some breakpoint happen.
    2- When I put (cvLoadImage) it was work but the final result nothing happen (I got two images without any plot on it)?

    Please can you tell me what happen.

  9. This comment has been removed by the author.

  10. This is very good sir! Thank you for your effort in contributing this example.
    Be sure to add the objdetect.dll file in your linker under project settings in order to compile and generate the executable successfully.

  11. how can i use it with multifaces?

  12. i was using python with opencv and i was getting error

    Traceback (most recent call last):
    File "C:\Python27\sastra", line 5, in
    AttributeError: 'module' object has no attribute 'cascadeclassifier'
    and i request u to help me by step wise procedure to solve above problem .
    and my email id: nsuresh062@gmail.com

  13. If anyone is having issues loading the xml, make sure you use / rather than \ in the path directory. Also use the full path all the way from the disk drive as that made a difference too. Hope this helps someone!

    1. i AM facing same problem. How to recover from this.

  14. Hi thanks for sharing face detection i am detecting live faces using usb camera.It worked well thank you

  15. Guys!
    Who is having the same issue:
    Unhandled exception at 0x74FEC52F in OpenCV_test.exe: Microsoft C++ exception: cv::Exception at memory location 0x002CF4AC.

    Windows 7 x64, OpenCV 3.1.0, Visual Studio 2015
    How to deal with this?

  16. Hi,
    Nice post.
    I need to detect tigers. Any idea how to do so?

  17. hi, i have a doubt.where it is saving the captured pic. i am confused about the path whether it is storing inside the appdata or somewhere in xml files. how it is storing and retrieving the images in opencv. could somebdy explain me thoroughly. will b helpful. thanks in advance.

  18. Hey what is there in xml file , I can't get it. Means what data to store in it. Can you please tell me.

  19. I need Red-eye detection , Red-eye removal , and rectangular selection .
    I need to select a rectangular part with eyes and to detect red-eye and remove red eye .

  20. HI im using the following code to detect faces but when the control enters in for loop it gives me error
    Unhandled exception at 0x00007FFD7794A1C8 in ANOTHER CV.exe: Microsoft C++ exception: cv::Exception at memory location 0x000000AF5034F330.
    can u plaease sort this out

  21. can some one explan to me how to make this code running?
    i am working on windows with visual studio, and i am running from the cmd after executing the code.
    what i should write to the cmd: something.exe [parms]
    what should the [params] be?