Path: blob/master/FaceDetectionComparison/face_detection_opencv_haar.cpp
3118 views
#include "opencv2/objdetect.hpp"1#include "opencv2/videoio.hpp"2#include "opencv2/highgui.hpp"3#include "opencv2/imgproc.hpp"45#include <iostream>6#include <stdio.h>78using namespace std;9using namespace cv;1011/** Global variables */12String faceCascadePath;13CascadeClassifier faceCascade;1415void detectFaceOpenCVHaar(CascadeClassifier faceCascade, Mat &frameOpenCVHaar, int inHeight=300, int inWidth=0)16{17int frameHeight = frameOpenCVHaar.rows;18int frameWidth = frameOpenCVHaar.cols;19if (!inWidth)20inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);2122float scaleHeight = frameHeight / (float)inHeight;23float scaleWidth = frameWidth / (float)inWidth;2425Mat frameOpenCVHaarSmall, frameGray;26resize(frameOpenCVHaar, frameOpenCVHaarSmall, Size(inWidth, inHeight));27cvtColor(frameOpenCVHaarSmall, frameGray, COLOR_BGR2GRAY);2829std::vector<Rect> faces;30faceCascade.detectMultiScale(frameGray, faces);3132for ( size_t i = 0; i < faces.size(); i++ )33{34int x1 = (int)(faces[i].x * scaleWidth);35int y1 = (int)(faces[i].y * scaleHeight);36int x2 = (int)((faces[i].x + faces[i].width) * scaleWidth);37int y2 = (int)((faces[i].y + faces[i].height) * scaleHeight);38rectangle(frameOpenCVHaar, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);39}40}414243int main( int argc, const char** argv )44{45faceCascadePath = "models/haarcascade_frontalface_default.xml";46if(!faceCascade.load(faceCascadePath))47{48printf("--(!)Error loading face cascade\n");49return -1;50}5152VideoCapture source;53if (argc == 1)54source.open(0, CAP_V4L);55else56source.open(argv[1]); Mat frame;5758double tt_opencvHaar = 0;59double fpsOpencvHaar = 0;6061while (true)62{63source >> frame;64if (frame.empty())65break;6667double t = cv::getTickCount();68detectFaceOpenCVHaar(faceCascade, frame);69tt_opencvHaar = ((double)cv::getTickCount() - t)/cv::getTickFrequency();70fpsOpencvHaar = 1/tt_opencvHaar;7172putText(frame, format("OpenCV HAAR ; FPS = %.2f",fpsOpencvHaar), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.3, Scalar(0, 0, 255), 4);7374imshow("OpenCV - HAAR Face Detection", frame);7576int k = waitKey(5);77if(k == 27)78{79destroyAllWindows();80break;81}82}83}848586