本测试的人脸识别使用Opencv自带的Haar特征检测的,存在的路径在安装包opencv\sources\data\haarcascades下
Haar特征检测,存在的路径在安装包opencv\sources\data\haarcascades下
从这些文件可以看出使用的Haar特征检测文件都是xml文档。里面存储的是一些脸部特征的信息:眼睛,身体,嘴巴等特征、还可以自己通过大量的训练来进行更多特征的识别,比如笑脸、哭泣等面部表情的识别。
使用cvHaarDetectObjects
CVAPI(CvSeq*) cvHaarDetectObjects(
const CvArr* image,
CvHaarClassifierCascade* cascade,
CvMemStorage* storage,
double scale_factor CV_DEFAULT(1.1),
int min_neighbors CV_DEFAULT(3),
int flags CV_DEFAULT(0),
CvSize min_size CV_DEFAULT(cvSize(0,0)),
CvSize max_size CV_DEFAULT(cvSize(0,0))
);
我们对函数进行一下说明
函数说明:
// Haar特征检测 - 人脸识别
//Code by lei
#include
#include
#include
#include
using namespace std;
int main()
{
// 加载Haar特征检测分类器
// OpenCV自带的分类器
const char *pstrCascadeFileName = "E:\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt2.xml";
CvHaarClassifierCascade *pHaarCascade = NULL;
pHaarCascade = (CvHaarClassifierCascade*)cvLoad(pstrCascadeFileName);
// 载入图像
const char *pstrImageName = "face1.jpg";
IplImage *pSrcImage = cvLoadImage(pstrImageName, CV_LOAD_IMAGE_UNCHANGED);
IplImage *pGrayImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
cvCvtColor(pSrcImage, pGrayImage, CV_BGR2GRAY);
// 人脸识别与标记
if (pHaarCascade != NULL)
{
CvScalar FaceCirclecolors[] =
{
{ { 0, 0, 255 } },
{ { 0, 128, 255 } },
{ { 0, 255, 255 } },
{ { 0, 255, 0 } },
{ { 255, 128, 0 } },
{ { 255, 255, 0 } },
{ { 255, 0, 0 } },
{ { 255, 0, 255 } }
};
CvMemStorage *pcvMStorage = cvCreateMemStorage(0);
cvClearMemStorage(pcvMStorage);
// 识别人脸
DWORD dwTimeBegin, dwTimeEnd;
dwTimeBegin = GetTickCount();
CvSeq *pcvSeqFaces = cvHaarDetectObjects(pGrayImage, pHaarCascade, pcvMStorage);
dwTimeEnd = GetTickCount();
printf("人脸个数: %d 识别用时: %d ms\n", pcvSeqFaces->total, dwTimeEnd - dwTimeBegin);
// 用圆圈标记人脸
for (int i = 0; i < pcvSeqFaces->total; i++)
{
CvRect* r = (CvRect*)cvGetSeqElem(pcvSeqFaces, i);
CvPoint center;
int radius;
center.x = cvRound((r->x + r->width * 0.5));
center.y = cvRound((r->y + r->height * 0.5));
radius = cvRound((r->width + r->height) * 0.25);
cvCircle(pSrcImage, center, radius, FaceCirclecolors[i % 8], 2);
}
cvReleaseMemStorage(&pcvMStorage);
}
const char *pstrWindowsTitle = "人脸识别";
cvNamedWindow(pstrWindowsTitle, CV_WINDOW_AUTOSIZE);
cvShowImage(pstrWindowsTitle, pSrcImage);
cvWaitKey(0);
cvDestroyWindow(pstrWindowsTitle);
cvReleaseImage(&pSrcImage);
cvReleaseImage(&pGrayImage);
return 0;
}
可以看到结果不是很近人意,在日常我们使用的app中人脸识别准确度要比这高的多