1 /** 2 * @file objectDetection2.cpp 3 * @author A. Huaman ( based in the classic facedetect.cpp in samples/c ) 4 * @brief A simplified version of facedetect.cpp, show how to load a cascade classifier and how to find objects (Face + eyes) in a video stream - Using LBP here 5 */ 6 #include "opencv2/objdetect.hpp" 7 #include "opencv2/videoio.hpp" 8 #include "opencv2/highgui.hpp" 9 #include "opencv2/imgproc.hpp" 10 11 #include <iostream> 12 #include <stdio.h> 13 14 using namespace std; 15 using namespace cv; 16 17 /** Function Headers */ 18 void detectAndDisplay( Mat frame ); 19 20 /** Global variables */ 21 String face_cascade_name = "lbpcascade_frontalface.xml"; 22 String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml"; 23 CascadeClassifier face_cascade; 24 CascadeClassifier eyes_cascade; 25 String window_name = "Capture - Face detection"; 26 /** 27 * @function main 28 */ 29 int main( void ) 30 { 31 VideoCapture capture; 32 Mat frame; 33 34 //-- 1. Load the cascade 35 if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade\n"); return -1; }; 36 if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading eyes cascade\n"); return -1; }; 37 38 //-- 2. Read the video stream 39 capture.open( -1 ); 40 if ( ! capture.isOpened() ) { printf("--(!)Error opening video capture\n"); return -1; } 41 42 while ( capture.read(frame) ) 43 { 44 if( frame.empty() ) 45 { 46 printf(" --(!) No captured frame -- Break!"); 47 break; 48 } 49 50 //-- 3. Apply the classifier to the frame 51 detectAndDisplay( frame ); 52 53 //-- bail out if escape was pressed 54 int c = waitKey(10); 55 if( (char)c == 27 ) { break; } 56 } 57 return 0; 58 } 59 60 /** 61 * @function detectAndDisplay 62 */ 63 void detectAndDisplay( Mat frame ) 64 { 65 std::vector<Rect> faces; 66 Mat frame_gray; 67 68 cvtColor( frame, frame_gray, COLOR_BGR2GRAY ); 69 equalizeHist( frame_gray, frame_gray ); 70 71 //-- Detect faces 72 face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0, Size(80, 80) ); 73 74 for( size_t i = 0; i < faces.size(); i++ ) 75 { 76 Mat faceROI = frame_gray( faces[i] ); 77 std::vector<Rect> eyes; 78 79 //-- In each face, detect eyes 80 eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CASCADE_SCALE_IMAGE, Size(30, 30) ); 81 if( eyes.size() == 2) 82 { 83 //-- Draw the face 84 Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 ); 85 ellipse( frame, center, Size( faces[i].width/2, faces[i].height/2 ), 0, 0, 360, Scalar( 255, 0, 0 ), 2, 8, 0 ); 86 87 for( size_t j = 0; j < eyes.size(); j++ ) 88 { //-- Draw the eyes 89 Point eye_center( faces[i].x + eyes[j].x + eyes[j].width/2, faces[i].y + eyes[j].y + eyes[j].height/2 ); 90 int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 ); 91 circle( frame, eye_center, radius, Scalar( 255, 0, 255 ), 3, 8, 0 ); 92 } 93 } 94 95 } 96 //-- Show what you got 97 imshow( window_name, frame ); 98 } 99