OpenCV4入门教程129:HAAR级联检测器使用

索引地址:系列索引

HAAR级联检测器介绍见(四十八)Haar级联检测器

级联是所谓的淘金过程,淘一遍有沙不行换个箩再筛一遍呗。比如说我想检测耳朵,但是耳朵是依附在脸旁边的,如果此图中没有检测到脸那么就肯定没有耳朵。如果有脸那就继续检测。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;
using namespace ml;

int main()
{
CascadeClassifier faceDetector;
if(!faceDetector.load("haarcascade_frontalface_default.xml"))
{
cout << "Can't find cascade classifier." << endl;
return -1;
}

VideoCapture cam;
if(!cam.open(0))
{
cout << "Can't open camera." << endl;
return -1;
}

Scalar red = Scalar(0,0,255);
Scalar green = Scalar(0,255,0);
int thickness = 2;
double scale = 0.75;

while(true)
{
Mat frame;
cam >> frame;
if(frame.empty())
break;

vector<Rect> faces;

double t = (double)getTickCount();

faceDetector.detectMultiScale(frame,
faces);

t = ((double)getTickCount() - t)/getTickFrequency();
t *= 1000; // convert to ms

for(int i=0; i<faces.size(); i++)
{
rectangle(frame,
faces[i],
red,
thickness);
}

putText(frame,
"Took " + to_string(int(t)) + "ms to detect",
Point(0, frame.rows-1),
FONT_HERSHEY_SIMPLEX,
scale,
green,
thickness);

imshow("Camera", frame);
if(waitKey(10) == 27) // escape key
break;
}

return 0;
}

效果为:

haar


OpenCV4入门教程129:HAAR级联检测器使用
https://blog.jackeylea.com/opencv/opencv-haar-cascade-classifier/
作者
JackeyLea
发布于
2020年11月10日
许可协议