Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/FaceDetectionComparison/face_detection_opencv_haar.cpp
3118 views
1
#include "opencv2/objdetect.hpp"
2
#include "opencv2/videoio.hpp"
3
#include "opencv2/highgui.hpp"
4
#include "opencv2/imgproc.hpp"
5
6
#include <iostream>
7
#include <stdio.h>
8
9
using namespace std;
10
using namespace cv;
11
12
/** Global variables */
13
String faceCascadePath;
14
CascadeClassifier faceCascade;
15
16
void detectFaceOpenCVHaar(CascadeClassifier faceCascade, Mat &frameOpenCVHaar, int inHeight=300, int inWidth=0)
17
{
18
int frameHeight = frameOpenCVHaar.rows;
19
int frameWidth = frameOpenCVHaar.cols;
20
if (!inWidth)
21
inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
22
23
float scaleHeight = frameHeight / (float)inHeight;
24
float scaleWidth = frameWidth / (float)inWidth;
25
26
Mat frameOpenCVHaarSmall, frameGray;
27
resize(frameOpenCVHaar, frameOpenCVHaarSmall, Size(inWidth, inHeight));
28
cvtColor(frameOpenCVHaarSmall, frameGray, COLOR_BGR2GRAY);
29
30
std::vector<Rect> faces;
31
faceCascade.detectMultiScale(frameGray, faces);
32
33
for ( size_t i = 0; i < faces.size(); i++ )
34
{
35
int x1 = (int)(faces[i].x * scaleWidth);
36
int y1 = (int)(faces[i].y * scaleHeight);
37
int x2 = (int)((faces[i].x + faces[i].width) * scaleWidth);
38
int y2 = (int)((faces[i].y + faces[i].height) * scaleHeight);
39
rectangle(frameOpenCVHaar, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
40
}
41
}
42
43
44
int main( int argc, const char** argv )
45
{
46
faceCascadePath = "models/haarcascade_frontalface_default.xml";
47
if(!faceCascade.load(faceCascadePath))
48
{
49
printf("--(!)Error loading face cascade\n");
50
return -1;
51
}
52
53
VideoCapture source;
54
if (argc == 1)
55
source.open(0, CAP_V4L);
56
else
57
source.open(argv[1]); Mat frame;
58
59
double tt_opencvHaar = 0;
60
double fpsOpencvHaar = 0;
61
62
while (true)
63
{
64
source >> frame;
65
if (frame.empty())
66
break;
67
68
double t = cv::getTickCount();
69
detectFaceOpenCVHaar(faceCascade, frame);
70
tt_opencvHaar = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
71
fpsOpencvHaar = 1/tt_opencvHaar;
72
73
putText(frame, format("OpenCV HAAR ; FPS = %.2f",fpsOpencvHaar), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.3, Scalar(0, 0, 255), 4);
74
75
imshow("OpenCV - HAAR Face Detection", frame);
76
77
int k = waitKey(5);
78
if(k == 27)
79
{
80
destroyAllWindows();
81
break;
82
}
83
}
84
}
85
86