#include "stdafx.h" #include "opencv2/core/core.hpp" #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; string face_cascade_name = "F:\\CV\\src\\haarcascade_frontalface_alt.xml"; CascadeClassifier face_cascade; string window_name = "人脸识别"; void detectAndDisplay( Mat frame ); int main(){ Mat frame; if( !face_cascade.load( face_cascade_name ) ){ printf("[error] 无法加载级联分类器文件!\n"); return -1; } CvCapture* capture; capture = cvCaptureFromCAM( -1 ); if( capture ) { while( true ) { frame = cvQueryFrame( capture ); if( !frame.empty() ) { detectAndDisplay( frame ); } else { printf(" --(!) No captured frame -- Break!"); break; } int c = waitKey(100); if( (char)c == 'c' ) break; } } waitKey(0); } 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, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) ); for( int i = 0; 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), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow( window_name, frame ); }
说明:
函数detectAndDisplay( Mat frame )输入Mat结构,检测人脸并在窗口中显示检测结果。
你可以为detectAndDisplay( Mat frame )自定义输入,例如载入一张图片,传到detectAndDisplay( Mat frame )让它检测并显示。
测试环境: win7旗舰x64下配置的vs2010 ,opencv2.4.3,库文件配置的x86
疑惑:配置x64的库文件,测试没有结果,检测不人脸。