OpenCV实现人脸检测(face detection) 代码
人脸检测利用detectMultiScale函数和CascadeClassifier(级联分类器);
需要留意的是: VS2012, 利用低版本的OpenCV(如2.4.3)会呈现问题, 导致CascadeClassifier无法加载(load)模子;
进级至OpenCV2.4.7即可, 并利用VS2012的库;
代码如下(VS2012):
#include <opencv.hpp>#include <iostream>
#include <iterator>
#include <string>
#include <stdio.h>using namespace std;
using namespace cv;void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip );string cascadeName = "haarcascade_frontalface_alt.xml";
string nestedCascadeName = "haarcascade_eye_tree_eyeglasses.xml";int main( int argc, const char** argv )
{
cv::CascadeClassifier cascade, nestedCascade;
double scale = 1;
bool tryflip = true;
cv::Mat image = imread( "girls.jpg", 1 );
cascade.load( cascadeName );
nestedCascade.load( nestedCascadeName );
detectAndDraw( image, cascade, nestedCascade, scale, tryflip);
cv::waitKey(0);
return 0;
}void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip )
{
int i = 0;
double t = 0;
vector<Rect> faces, faces2;
const static Scalar colors[] = { CV_RGB(0,0,255),
CV_RGB(0,128,255),
CV_RGB(0,255,255),
CV_RGB(0,255,0),
CV_RGB(255,128,0),
CV_RGB(255,255,0),
CV_RGB(255,0,0),
CV_RGB(255,0,255)} ;
Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );cvtColor( img, gray, CV_BGR2GRAY );
resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
equalizeHist( smallImg, smallImg );
//