一 如何使用OpenCV的人脸检测器检测到人脸:
/ /执行的输入图像上的人脸检测,使用给定的(Haar)级联。
/ /返回一个矩形,在给定的图像中检测到的区域。
CvRect detectFaceInImage(IplImage *inputImg, CvHaarClassifierCascade* cascade)
{
/ /最小脸的大小.
CvSize minFeatureSize = cvSize(20, 20);
/ /只搜索一面.
int flags = CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH;
/ /详细的搜索.
float search_scale_factor = 1.1f;
IplImage *detectImg;
IplImage *greyImg = 0;
CvMemStorage* storage;
CvRect rc;
double t;
CvSeq* rects;
CvSize size;
int i, ms, nFaces;
storage = cvCreateMemStorage(0);
cvClearMemStorage( storage );
/ /如果图像是彩色的,使用的灰度图像的副本.
detectImg = (IplImage*)inputImg;
if (inputImg->nChannels > 1) {
size = cvSize(inputImg->width, inputImg->height);
greyImg = cvCreateImage(size, IPL_DEPTH_8U, 1 );
cvCvtColor( inputImg, greyImg, CV_BGR2GRAY );
detectImg = greyImg; // Use the greyscale image.
}
//检测的灰度图像中的所有面.
t = (double)cvGetTickCount();
rects = cvHaarDetectObjects( detectImg, cascade, storage,
search_scale_factor, 3, flags, minFeatureSize);
t = (double)cvGetTickCount() - t;
ms = cvRound( t / ((double)cvGetTickFrequency() * 1000.0) );
nFaces = rects->total;
printf("Face Detection took %d ms and found %d objects\n", ms, nFaces);
//获取第一个检测到的人脸(最大).
if (nFaces > 0)
rc = *(CvRect*)cvGetSeqElem( rects, 0 );
else
rc = cvRect(-1,-1,-1,-1); / /找不到的脸.
if (greyImg)
cvReleaseImage( &greyImg );
cvReleaseMemStorage( &storage );
// cvReleaseHaarClassifierCascade的(级联);
return rc; / /返回发现最大的面,或(-1,-1,-1,-1).
}
// Haar的级联文件,使用的人脸检测.
char *faceCascadeFilename = "haarcascade_frontalface_alt.xml";
/ /加载的HaarCascade分类器进行人脸检测.
CvHaarClassifierCascade* faceCascade;
faceCascade = (CvHaarClassifierCascade*)cvLoad(faceCascadeFilename, 0, 0, 0);
if( !faceCascade ) {
printf("Couldnt load Face detector '%s'\n", faceCascadeFilename);
exit(1);
}
/ /获取下一帧的摄像头.
IplImage *inputImg = cvQueryFrame(camera);
/ /对输入图像执行面部检测,使用给定的(Haar)分类.
CvRect faceRect = detectFaceInImage(inputImg, faceCascade);
/ /确保有效侦测到脸部.
if (faceRect.width > 0) {
printf("Detected a face at (%d,%d)!\n", faceRect.x, faceRect.y);
}
.... Use 'faceRect' and 'inputImg' ....
//人脸检测程序完成时的资源cvReleaseHaarClassifierCascade(级联);
|