级联分类器(Here we learn how to use objdetect to find objects in our images or videos)
级联分类器
目标
在这节教程中您将学到:
- 使用 CascadeClassifier 类来检测视频流中的物体. 特别地, 我们将使用函数:
- load 来加载一个 .xml 分类器文件. 它既可以是Haar特征也可以是LBP特征的分类器.
- detectMultiScale 来进行图像的多尺度检测.
原理
代码
本教程的代码如下所示. 你也可以 点这里 下载. 第二个版本 (使用LBP进行人脸检测) 可以 从这里 找到.
#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(12345);
/** @主函数 */
int main( int argc, const char** argv )
{
CvCapture* capture;
Mat frame;
//-- 1. 加载级联分类器文件
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. 打开内置摄像头视频流
capture = cvCaptureFromCAM( -1 );
if( capture )
{
while( true )
{
frame = cvQueryFrame( capture );
//-- 3. 对当前帧使用分类器进行检测
if( !frame.empty() )
{ detectAndDisplay( frame ); }
else
{ printf(" --(!) No captured frame -- Break!"); break; }
int c = waitKey(10);
if( (char)c == 'c' ) { break; }
}
}
return 0;
}
/** @函数 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, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for