1 函数介绍

OpenCV自带的CascadeClassifier这个类下的detectMultiScale函数,其检测效果并不是很好
void CascadeClassifier::detectMultiScale(InputArray image, vector<Rect>& objects, double scaleFactor=1.1, int minNeighbors=3, int flags=0, Size minSize=Size(), Size maxSize=Size())
总共有7个参数,分别是

第一个参数image:  要检测的图片,一般为灰度图;
第二个参数objects:  Rect型的容器,存放所有检测出的人脸,每个人脸是一个矩形;
第三个参数scaleFactor:  缩放因子,对图片进行缩放,默认为1.1;
第四个参数minNeighbors: 最小邻居数,默认为3;
第五个参数flags:  兼容老版本的一个参数,在3.0版本中没用处。默认为0;
第六个参数minSize: 最小尺寸,检测出的人脸最小尺寸;
第七个参数maxSize: 最大尺寸,检测出的人脸最大尺寸;

1.1 静态图片上的人脸检测

1.1.1 示例代码

#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 = "D:\\Program Files\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"; 

CascadeClassifier face_cascade; 
void detectAndDisplay( Mat frame ); 
int main( int argc, char** argv ){ 
    Mat image; 
    image =imread("E:/snsd.jpg",1);  //当前工程的image目录下的mm.jpg文件,注意目录符号
    if( !face_cascade.load( face_cascade_name ) ){  
        cout<<"xml文件加载失败"<<endl; 
        return -1;  
    } 
    detectAndDisplay(image); //调用人脸检测函数
    waitKey(0);  
} 

void detectAndDisplay( Mat face ){ 
    std::vector<Rect> faces; 
    Mat face_gray; 

    cvtColor( face, face_gray, CV_BGR2GRAY );  
    equalizeHist( face_gray, face_gray );   

    face_cascade.detectMultiScale( face_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(1, 1) ); 

    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( face, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 0), 2,7, 0 ); 
    } 

    imshow("静态图片人脸识别", face ); 
} 

或者

#include "opencv2\opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;

int main()
{
    string xmlPath="D:\\Program Files\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"; 
    CascadeClassifier ccf;   //创建分类器对象
    Mat img=imread("E:/snsd.jpg");   
    if(!ccf.load(xmlPath))   //加载训练文件
    {
        cout<<"不能加载指定的xml文件"<<endl;
        return 0;
    }
    vector<Rect> faces;  //创建一个容器保存检测出来的脸
    Mat gray;
    cvtColor(img,gray,CV_BGR2GRAY); //转换成灰度图,因为harr特征从灰度图中提取
    equalizeHist(gray,gray);  //直方图均衡行
    ccf.detectMultiScale(gray,faces,1.1,3,0,Size(10,10),Size(100,100)); //检测人脸
    for(vector<Rect>::const_iterator iter=faces.begin();iter!=faces.end();iter++)
    {
        rectangle(img,*iter,Scalar(0,0,255),2,8); //画出脸部矩形
    }
    imshow("faces",img);
    waitKey(0);
    return 1;
}

1.1.2 结果示例

OpenCV – 静态图片人脸检测和摄像头人脸检测-StubbornHuang Blog

从检测的结果可以看出,有些人脸没有检测出来,或者是检测出来有位置错误。

1.2 摄像头人脸检测

1.2.1 示例代码

#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 );

//全局变量
//-- Note, either copy these two files from opencv/data/haarscascades to your current folder, or change these locations
string face_cascade_name = "D:\\Program Files\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
string eyes_cascade_name = "D:\\Program Files\\opencv\\sources\\data\\haarcascades\\haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
string window_name = "Capture - Face detection";
RNG rng(12345);

int main( void )
{
    CvCapture* capture;
    Mat frame;

    //-- 1. Load the cascades
    if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
    if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };

    //-- 2. Read the video stream
    capture = cvCaptureFromCAM( 0);
    if( capture )
    {
        for(;;)
        {
            frame = cvQueryFrame( capture );

            //-- 3. Apply the classifier to the frame
            if( !frame.empty() )
            { detectAndDisplay( frame ); }
            else
            { printf(" --(!) No captured frame -- Break!"); break; }

            int c = waitKey(10);
            if( (char)c == 'c' ) { break; }

        }
    }
    return 0;
}

void detectAndDisplay( Mat frame )
{
    std::vector<Rect> faces;
    Mat frame_gray;

    cvtColor( frame, frame_gray, CV_BGR2GRAY );
    equalizeHist( frame_gray, frame_gray );
    //-- Detect faces
    face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );

    for( size_t i = 0; i < faces.size(); i++ )
    {
        Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 );
        ellipse( frame, center, Size( faces[i].width/2, faces[i].height/2), 0, 0, 360, Scalar( 255, 0, 255 ), 2, 8, 0 );

        Mat faceROI = frame_gray( faces[i] );
        std::vector<Rect> eyes;

        //-- In each face, detect eyes
        eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );

        for( size_t j = 0; j < eyes.size(); j++ )
        {
            Point eye_center( faces[i].x + eyes[j].x + eyes[j].width/2, faces[i].y + eyes[j].y + eyes[j].height/2 );
            int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 );
            circle( frame, eye_center, radius, Scalar( 255, 0, 0 ), 3, 8, 0 );
        }
    }
    //-- Show what you got
    imshow( window_name, frame );
}

1.2.2 结果示例

OpenCV – 静态图片人脸检测和摄像头人脸检测-StubbornHuang Blog