OpenCV 级联分类器

 

 1 #include "opencv2/objdetect/objdetect.hpp"
 2  #include "opencv2/highgui/highgui.hpp"
 3  #include "opencv2/imgproc/imgproc.hpp"
 4 
 5  #include <iostream>
 6  #include <stdio.h>
 7 
 8  using namespace std;
 9  using namespace cv;
10 
11  /** 函数声明 */
12  void detectAndDisplay( Mat frame );
13 
14  /** 全局变量 */
15  string face_cascade_name = "haarcascade_frontalface_alt.xml";
16  string eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
17  CascadeClassifier face_cascade;
18  CascadeClassifier eyes_cascade;
19  string window_name = "Capture - Face detection";
20  RNG rng(12345);
21 
22  /** @主函数 */
23  int main( int argc, const char** argv )
24  {
25    CvCapture* capture;
26    Mat frame;
27 
28    //-- 1. 加载级联分类器文件
29    if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
30    if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
31 
32    //-- 2. 打开内置摄像头视频流
33    capture = cvCaptureFromCAM( -1 );
34    if( capture )
35    {
36      while( true )
37      {
38    frame = cvQueryFrame( capture );
39 
40    //-- 3. 对当前帧使用分类器进行检测
41        if( !frame.empty() )
42        { detectAndDisplay( frame ); }
43        else
44        { printf(" --(!) No captured frame -- Break!"); break; }
45 
46        int c = waitKey(10);
47        if( (char)c == 'c' ) { break; }
48       }
49    }
50    return 0;
51  }
52 
53 /** @函数 detectAndDisplay */
54 void detectAndDisplay( Mat frame )
55 {
56   std::vector<Rect> faces;
57   Mat frame_gray;
58 
59   cvtColor( frame, frame_gray, CV_BGR2GRAY );
60   equalizeHist( frame_gray, frame_gray );
61 
62   //-- 多尺寸检测人脸
63   face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
64 
65   for( int i = 0; i < faces.size(); i++ )
66   {
67     Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
68     ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
69 
70     Mat faceROI = frame_gray( faces[i] );
71     std::vector<Rect> eyes;
72 
73     //-- 在每张人脸上检测双眼
74     eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
75 
76     for( int j = 0; j < eyes.size(); j++ )
77      {
78        Point center( faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5 );
79        int radius = cvRound( (eyes[j].width + eyes[i].height)*0.25 );
80        circle( frame, center, radius, Scalar( 255, 0, 0 ), 4, 8, 0 );
81      }
82   }
83   //-- 显示结果图像
84   imshow( window_name, frame );
85  }
上一篇:二值化Thresholding


下一篇:(九)OpenCV-Python学习—图像傅里叶变换