#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp" #include <iostream>
#include <stdio.h> using namespace std;
using namespace cv; /** 函数声明 */
void detectAndDisplay( Mat frame ); /** 全局变量 */
string face_cascade_name = "haarcascade_frontalface_alt.xml";
string eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
string window_name = "Capture - Face detection";
RNG rng(); /** @主函数 */
int main( int argc, const char** argv )
{
CvCapture* capture;
Mat frame; //-- 1. 加载级联分类器文件
if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -; };
if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -; }; //-- 2. 打开内置摄像头视频流
capture = cvCaptureFromCAM( - );
if( capture )
{
while( true )
{
frame = cvQueryFrame( capture ); //-- 3. 对当前帧使用分类器进行检测
if( !frame.empty() )
{ detectAndDisplay( frame ); }
else
{ printf(" --(!) No captured frame -- Break!"); break; } int c = waitKey();
if( (char)c == 'c' ) { break; }
}
}
return ;
} /** @函数 detectAndDisplay */
void detectAndDisplay( Mat frame )
{
std::vector<Rect> faces;
Mat frame_gray; cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray ); //-- 多尺寸检测人脸
face_cascade.detectMultiScale( frame_gray, faces, 1.1, , |CV_HAAR_SCALE_IMAGE, Size(, ) ); for( int i = ; i < faces.size(); i++ )
{
Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), , , , Scalar( , , ), , , ); Mat faceROI = frame_gray( faces[i] );
std::vector<Rect> eyes; //-- 在每张人脸上检测双眼
eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, , |CV_HAAR_SCALE_IMAGE, Size(, ) ); for( int j = ; j < eyes.size(); j++ )
{
Point center( faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5 );
int radius = cvRound( (eyes[j].width + eyes[i].height)*0.25 );
circle( frame, center, radius, Scalar( , , ), , , );
}
}
//-- 显示结果图像
imshow( window_name, frame );
}
05-26 06:36