当前位置:文档之家› 人脸识别代码

人脸识别代码

void detect_and_draw(IplImage* img )
{
//这个缩放因子的作用是:拿到一个图像,首先将它缩放(scale=1.2即变为一个小图像),然后在缩放后的小图像上检测人脸,这样会比较快。
double scale=1.2;
// //定义8种不同的颜色,为了画人脸外接圆而用
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
// //创建一个单通道8位图像gray,长宽与img一样,即img的灰度图像 --什么是灰度图?完善知识点
IplImage* gray = cvCreateImage(cvSize(img->width,img->height),8,1);

/*创建一个单通道8位图像small_img,长宽分别为【img->width/scale】【img->height/scale】【取整】
即缩放scale倍数后的图像*/
//缩小图片
IplImage* small_img=cvCreateImage(cvSize(cvRound(img->width/scale),cvRound(img->height/scale)),8,1);
//RGB格式的img图像转换成GRAY格式的gray图像
cvCvtColor(img,gray, CV_BGR2GRAY);//转换成灰色的图
//把gray图像双线性缩放成small_img图像
cvResize(gray, small_img, CV_INTER_LINEAR);//对灰图缩放图片存small_img

//把small_img灰度图像直方图均衡化,结果保存在small_img中,目的是归一化图像亮度和增强对比度
cvEqualizeHist(small_img,small_img); //直方图均

//Detect objects if any
//清空一块内存区域等待使用
cvClearMemStorage(storage);

//为测量代码执行时间而使用cvGetTickCount,返还1970年到现在的总微秒数
double t = (double)cvGetTickCount();

/* 人脸的哈尔特征检测是在detect_and_draw函数中实现的,具体到以下这个函数:cvHaarDetectObjects()
返还的是一个动态数据结构faces */
CvSeq* objects = cvHaarDetectObjects(small_img,cascade,storage,1.1,2,0,cvSize(30,30));

//计算cvHaarDetectObjects函数执行的时间t并打印出来
t = (double)cvGetTickCount() - t;
printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );

//Loop through found objects and draw boxes around them
//若faces==0(即没检测到人脸),则不执行循环;若faces==1,则执行循环的次数等于检测到的人脸个数
//标记人脸
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( int i = 0; i < (objects? objects->total : 0); i++ )
{
////返回检测到的第i张人脸的元素指针
CvRect* r = (CvRect*)cvGetSeqElem( objects, i );
CvPoint center;
int radius;
//人脸外接圆的圆心坐标(x,y)就是矩形的中

心,半径差不多是矩形宽的一半
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);
//在RGB格式的img图像上给人脸画一个外接圆,8种颜色循环使用
cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );
}

cvShowImage( "result", img );
cvReleaseImage(&gray);
cvReleaseImage(&small_img);
}

相关主题
文本预览
相关文档 最新文档