基于OpenCV的人脸检测代码

最近在做人脸识别,在做人脸识别之前,必须有这么的一个过程,那即是人脸检测,只有先检测出人脸后,再预处理人脸图像,最后才做人脸识别,这是人脸识别的过程,现在的

人脸测试代码都被封装好了,只要调用OpenCV的几个函数即可,非常方便,现在就为大家贴出我写的代码吧!

#include "cv.h"  
#include "highgui.h"  
#include <stdio.h> 

static CvMemStorage* storage = 0; 
static CvHaarClassifierCascade* cascade = 0;

const char* cascade_name = 
"haarcascade_frontalface_alt.xml"; 



void detect_and_draw(IplImage* img ) 
{ 
	cvNamedWindow( "result", 1 ); 
    double scale=1.2; 
    static CvScalar colors[] = { 
        {{0,0,255}},{{0,128,255}},{{0,255,255}},{{0,255,0}}, 
        {{255,128,0}},{{255,255,0}},{{255,0,0}},{{255,0,255}} 
    };//Just some pretty colors to draw with
	
    //Image Preparation 
    // 
    IplImage* gray = cvCreateImage(cvSize(img->width,img->height),8,1); 
    IplImage* small_img=cvCreateImage(cvSize(cvRound(img->width/scale),cvRound(img->height/scale)),8,1); 
    cvCvtColor(img,gray, CV_BGR2GRAY); 
    cvResize(gray, small_img, CV_INTER_LINEAR);
    cvSmooth( gray, gray,CV_MEDIAN, 3, 3);
    cvEqualizeHist(small_img,small_img); 
	
    //Detect objects if any 
    // 
    cvClearMemStorage(storage); 
    double t = (double)cvGetTickCount(); 
    CvSeq* objects = cvHaarDetectObjects(small_img, 
		cascade, 
		storage, 
		1.1, 
		2, 
		CV_HAAR_DO_CANNY_PRUNING, 
		cvSize(20,20));
	
    t = (double)cvGetTickCount() - t; 
    printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );
	
    //Loop through found objects and draw boxes around them 
    for(int i=0;i<(objects? objects->total:0);++i) 
    { 
        CvRect* r=(CvRect*)cvGetSeqElem(objects,i); 
		cvRectangle(img, cvPoint(r->x*scale,r->y*scale), cvPoint((r->x+r->width)*scale,(r->y+r->height)*scale), colors[i%8]);		
    } 
    for(  i = 0; i < (objects? objects->total : 0); i++ ) 
    { 
		CvRect* r = (CvRect*)cvGetSeqElem( objects, i ); 
		CvPoint center; 
		int radius; 
		center.x = cvRound((r->x + r->width*0.5)*scale); 
		center.y = cvRound((r->y + r->height*0.5)*scale); 
		radius = cvRound((r->width + r->height)*0.25*scale); 
		cvCircle( img, center, radius, colors[i%8], 3, 8, 0 ); 
	}
	
	    
    cvShowImage( "result", img ); 
    cvReleaseImage(&gray); 
    cvReleaseImage(&small_img); 
}

int main( int argc, char** argv ) 
{ 
	int c;
    cascade_name = "haarcascade_frontalface_alt.xml"; 
    cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 ); 
	
    if( !cascade ) 
    { 
        fprintf( stderr, "ERROR: Could not load classifier cascade\n" ); 
        return -1; 
    } 
    storage = cvCreateMemStorage(0); 
	const char* picturefilename = "Lena.jpg"; 
    IplImage* image = cvLoadImage( picturefilename, 1 );
    if( image ) 
    { 
        detect_and_draw( image ); 
		cvWaitKey(0); 
        cvReleaseImage( &image );   
    }
  return 0;
}

基于OpenCV的人脸检测代码_第1张图片

你可能感兴趣的:(opencv,人脸检测)