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.

Parameters:   
  • 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
Parameters:
  • 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.
Parameters:
  • 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.

Steps:

  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.

Functions:


Example:

------------
#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 );
    
    waitKey(0);                   
    return 0;
}
------------

48 comments:

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

    ReplyDelete
    Replies
    1. Learn Opencv By Examples: Face Detection Using Haar-Cascade Classifier >>>>> Download Now

      >>>>> Download Full

      Learn Opencv By Examples: Face Detection Using Haar-Cascade Classifier >>>>> Download LINK

      >>>>> Download Now

      Learn Opencv By Examples: Face Detection Using Haar-Cascade Classifier >>>>> Download Full

      >>>>> Download LINK q7

      Delete
  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?

    ReplyDelete
    Replies
    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

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

    ReplyDelete
  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!

    ReplyDelete
  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 ?

    ReplyDelete
  6. The Best Delphi sample code I ever had for Face Detection.
    GOD bless the good hearted Author.
    http://delphimagic.blogspot.com.es/2011/08/reconocimiento-de-caras-con-delphi.html

    ReplyDelete
  7. 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.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. 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.

    ReplyDelete
  10. how can i use it with multifaces?

    ReplyDelete
  11. i was using python with opencv and i was getting error

    Traceback (most recent call last):
    File "C:\Python27\sastra", line 5, in
    face_cascade=cv2.cascadeclassifier('haarcascade_frontalface_default.xml')
    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

    ReplyDelete
  12. 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!

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

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

    ReplyDelete
  14. 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?

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

    ReplyDelete
  16. 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.

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

    ReplyDelete
  18. 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 .

    ReplyDelete
  19. 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

    ReplyDelete
  20. 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?

    ReplyDelete
  21. Hi thanks for great post I would like to detect traffic sign using haar cascade , I got 2 trained XML file for stop and roundabout sign , can u give me some how to do it and if I want to add more cascade how can detect this ??

    ReplyDelete
  22. How to detect this in ??' real time I mean using web cam

    ReplyDelete
  23. i have some problems. actually someone already ask before me about the error why he/she cant load the xml file. and you suggest to write the path. what i'd like to ask what if im using an hardware device like android phone. how should i write the path? should i wrote the path like whats written when i open the file on my android file manager and click details

    e.x:"/storage/emulated/0/data/haarcascade_facedetection_alt.xml"
    or should i use Environtment.getDataDirectory()+"/haarcascade_facedetection_alt.xml"

    very apreciated for your help. btw, im trying to detect faces on image using opencv haarcascade for my essay project.

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. how can we get number of faces detected in image like 1 or 2 or 3
    etc.....Thanks

    ReplyDelete
  26. hi.. i have tried the above code i got the face output and i have also added the eyes detection in the above code ..but the output is not showing...

    Someone help me with this issue and its urgent for me.. Thanks in advance

    ReplyDelete
  27. Hi, can you tell how to detect face in a live video ?

    ReplyDelete
  28. Offset Printing Machine Repair Service offers a extremely trained employees of printing instrumentation technicians to assist drawback solve and fix with regards to any drawback that may arise along with your printing instrumentation. From folders, cutters to merely concerning any offset press that's within the print business.

    ReplyDelete
  29. Unhandled exception at 0x00007FFE8CB43B29 in opencv 1.exe: Microsoft C++ exception: cv::Exception at memory location 0x0000002BEE6FF160.

    i am getting this error. How can i fix it? please help

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. طريقة تنظيف التكييف من الخارج
    يجب قبل البدء في عملية التنظيف فصل التيار الكهربائي عن التكييف نهائيا.
    يجب أولا تنظيف القطعة الخارجية من التكييف وتسمى الكمبريسور.
    يجب استخدام كمامة على الأنف عند تنظيف القطعة الخارجية كما يجب ارتداء نظارة للحماية من الأتربة والشوائب.
    يجب استخدام منفاخ الكهرباء للتخلص من الأتربة التي توجد على القطعة الخارجية، وقوموا بتنظيف مروحة التكيف الخارجية وعند توقف خروج الأتربة منه.
    قومي بتنظيفها باستخدام قطعة قماش مبللة وبعد الانتهاء من تنظيفها قومي بتجفيفها.
    يجب فك الجزء العلوى من التكييف لتنظيف المروحة من الداخل والموتور.
    يتم استخدام بخاخة التشحيم لتسهيل تشغيل المروحة بكل سهولة إذا كانت تحتاج إلى ذلك كما يتم تنظيف المروحة من الداخل والموتور بقطعة قماش بها القليل من الخل.
    يمكن أن نستخدم المكنسة الكهربائية لتنظيف الوجه الخارجي من الأتربة ويمكن استعمال بخاخة بها القليل من الماء والصابون للتأكد من تنظيف كل قطعة داخل الوجه الخارجي للتكييف.
    بعد الانتهاء من تنظيف المكيف من الداخل يجب تجفيف التكييف جيدا سواء عن طريق شفط بقايا الماء بجهاز أو قطعة قماش جافة.
    يجب تنظيف جوانب التكييف باستخدام فرشاة ناعمة للتخلص من الأتربة.
    بعد الانتهاء من تنظيف التكييف يجب تركيب الوجه الخارجي مرة أخرى.
    اقرا المزيد على
    شركة تنظيف مكيفات بمكة
    شركة تنظيف خزانات بمكة
    شركة كشف تسربات المياه بمكة
    شركة كشف تسربات المياه بجدة
    شركة تسليك مجاري بجدة

    ReplyDelete
  32. 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. lawn suits with chiffon dupatta , 2 piece suit online shopping in pakistan

    ReplyDelete

  33. تعد الحشرات أصغر الكائنات الحية على سطح الأرض، وتتعدد أنواعها،وأشكالها منها ما هو سام،ومنا ما هو مألوف،كذلك توجد حشرات ذات فائدة وضرر في نفس الوقت؛حيث يبلغ عدد فصائل الحشرات نحو ثلاثين مليون فصيلة،ولا شك أن مكافحة الحشرات تحتاج إلى دراية بكل أنواع الحشرات،وذلك للتعرف على درجة خطورتها على الإنسان والأهم من ذلك طرق مكافحتها.
    مكافحة حشرات المنزل بالنسبة للبعض أمر في غاية الصعوبة وخاصة عندما يتعلق الأمر بالصراصير والنمل والبراغيث وبق الفراش والفئران وغيرها من الآفات المنزلية التي تنتشر بكل سهولة في كل أركان المنزل. لكن يُمكنك مكافحة حشرات المنزل بطرق بسيطة وفعالة بشكل نهائي ولن تحتاج إلى المركبات الكيميائية القوية الموجودة في الأسواق المحلية والتي قدد تكون أكثر ضررًا عليك وعلى عائلتك ؛
    شركة فرسان المدينة للخدمات المنزلية

    ReplyDelete
  34. Learn Opencv By Examples: Face Detection Using Haar-Cascade Classifier >>>>> Download Now

    >>>>> Download Full

    Learn Opencv By Examples: Face Detection Using Haar-Cascade Classifier >>>>> Download LINK

    >>>>> Download Now

    Learn Opencv By Examples: Face Detection Using Haar-Cascade Classifier >>>>> Download Full

    >>>>> Download LINK dI

    ReplyDelete