收藏 分享(赏)

人脸匹配算法.docx

上传人:j35w19 文档编号:7859056 上传时间:2019-05-27 格式:DOCX 页数:24 大小:40.83KB
下载 相关 举报
人脸匹配算法.docx_第1页
第1页 / 共24页
人脸匹配算法.docx_第2页
第2页 / 共24页
人脸匹配算法.docx_第3页
第3页 / 共24页
人脸匹配算法.docx_第4页
第4页 / 共24页
人脸匹配算法.docx_第5页
第5页 / 共24页
点击查看更多>>
资源描述

1、#include “cv.h“#include “highgui.h“#include #include #include #include #include #include #include #include #include #ifdef _EiC#define WIN32#endifstatic CvMemStorage* storage = 0;static CvHaarClassifierCascade* cascade = 0;void detect_and_draw( IplImage* image );const char* cascade_name =“haarcascad

2、e_frontalface_alt.xml“;/* “haarcascade_profileface.xml“;*/int main( int argc, char* argv )CvCapture* capture = 0;IplImage *frame, *frame_copy = 0;int optlen = strlen(“-cascade=“);const char* input_name;if( argc 1 input_name = argc 2 ? argv2 : 0;elsecascade_name = “/data/haarcascades/haarcascade_fron

3、talface_alt2.xml“;input_name = argc 1 ? argv1 : 0;cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );if( !cascade )fprintf( stderr, “ERROR: Could not load classifier cascaden“ );fprintf( stderr,“Usage: facedetect -cascade=“ filename|camera_indexn“ );return -1;storage = cvCreateMemSt

4、orage(0);if( !input_name | (isdigit(input_name0) elsecapture = cvCaptureFromAVI( input_name ); cvNamedWindow( “result“, 1 );if( capture )for(;)if( !cvGrabFrame( capture )break;frame = cvRetrieveFrame( capture );if( !frame )break;if( !frame_copy )frame_copy = cvCreateImage( cvSize(frame-width,frame-h

5、eight),IPL_DEPTH_8U, frame-nChannels );if( frame-origin = IPL_ORIGIN_TL )cvCopy( frame, frame_copy, 0 );elsecvFlip( frame, frame_copy, 0 );detect_and_draw( frame_copy );if( cvWaitKey( 10 ) = 0 )break;cvReleaseImage( cvReleaseCapture( elseconst char* filename = input_name ? input_name : (char*)“lena.

6、jpg“;IplImage* image = cvLoadImage( filename, 1 );if( image )detect_and_draw( image );cvWaitKey(0);cvReleaseImage( else/* assume it is a text file containing thelist of the image filenames to be processed - one per line */FILE* f = fopen( filename, “rt“ );if( f )char buf1000+1;while( fgets( buf, 100

7、0, f ) )int len = (int)strlen(buf);while( len 0 buflen = 0;image = cvLoadImage( buf, 1 );if( image )detect_and_draw( image );cvWaitKey(0);cvReleaseImage( fclose(f);cvDestroyWindow(“result“);return 0;void detect_and_draw( IplImage* img )static CvScalar colors = 0,0,255,0,128,255,0,255,255,0,255,0,255

8、,128,0,255,255,0,255,0,0,255,0,255;double scale = 1.3;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 );int i;cvCvtColor( img, gray, CV_BGR2GRAY );cvResize( gray, small_img, CV

9、_INTER_LINEAR );cvEqualizeHist( small_img, small_img );cvClearMemStorage( storage );if( cascade )double t = (double)cvGetTickCount();CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,cvSize(30, 30) );t = (double)cvGetTickCount() - t;printf( “detect

10、ion time = %gmsn“, t/(double)cvGetTickFrequency()*1000.) );for( i = 0; i total : 0); i+ )CvRect* r = (CvRect*)cvGetSeqElem( faces, 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)

11、;cvCircle( img, center, radius, colorsi%8, 3, 8, 0 );cvShowImage( “result“, img );cvReleaseImage( cvReleaseImage( 浅谈 OpenCV人脸检测(2011-08-27 10:52:28)转载标签: opencv人脸检测it分类: opencv人脸检测以下转载 仅供学习参考OpenCV的人脸检测主要是调用训练好的 cascade(Haar 分类器)来进行模式匹配。cvHaarDetectObjects,先将图像灰度化,根据传入参数判断是否进行 canny边缘处理(默认不使用),再进行匹配

12、。匹配后收集找出的匹配块,过滤噪声,计算相邻个数如果超过了规定值(传入的 min_neighbors)就当成输出结果,否则删去。匹配循环:将匹配分类器放大 scale(传入值)倍,同时原图缩小 scale倍,进行匹配,直到匹配分类器的大小大于原图,则返回匹配结果。匹配的时候调用 cvRunHaarClassifierCascade来进行匹配,将所有结果存入 CvSeq* Seq (可动态增长元素序列),将结果传给 cvHaarDetectObjects。cvRunHaarClassifierCascade函数整体是根据传入的图像和 cascade来进行匹配。并且可以根据传入的 cascade类

13、型不同(树型、stump(不完整的树)或其他的),进行不同的匹配方式。函数 cvRunHaarClassifierCascade 用于对单幅图片的检测。在函数调用前首先利用 cvSetImagesForHaarClassifierCascade 设定积分图和合适的比例系数 (= 窗口尺寸)。当分析的矩形框全部通过级联分类器每一层的时返回正值(这是一个候选目标),否则返回 0或负值。为了了解 OpenCV人脸检测中寻找匹配图像的详细过程,就把cvHaarDetectObjects和 cvRunHaarClassifierCascade的源文件详细看了一遍,并打上了注释。方便大家阅读。附 cvHa

14、arDetectObjects代码:CV_IMPL CvSeq*cvHaarDetectObjects( const CvArr* _img,CvHaarClassifierCascade* cascade,CvMemStorage* storage, double scale_factor,int min_neighbors, int flags, CvSize min_size )int split_stage = 2;CvMat stub, *img = (CvMat*)_img; /CvMat多通道矩阵 *img=_img 指针代换传入图CvMat *temp = 0, *sum =

15、0, *tilted = 0, *sqsum = 0, *norm_img = 0, *sumcanny = 0, *img_small = 0;CvSeq* seq = 0;CvSeq* seq2 = 0; /CvSeq可动态增长元素序列CvSeq* idx_seq = 0;CvSeq* result_seq = 0;CvMemStorage* temp_storage = 0;CvAvgComp* comps = 0;int i;#ifdef _OPENMPCvSeq* seq_threadCV_MAX_THREADS = 0;int max_threads = 0;#endifCV_FU

16、NCNAME( “cvHaarDetectObjects” );_BEGIN_;double factor;int npass = 2, coi; /npass=2int do_canny_pruning = flags /true做 canny边缘处理if( !CV_IS_HAAR_CLASSIFIER(cascade) )CV_ERROR( !cascade ? CV_StsNullPtr : CV_StsBadArg, “Invalid classifier cascade” );if( !storage )CV_ERROR( CV_StsNullPtr, “Null storage p

17、ointer” );CV_CALL( img = cvGetMat( img, if( coi )CV_ERROR( CV_BadCOI, “COI is not supported” ); /一些出错代码if( CV_MAT_DEPTH(img-type) != CV_8U )CV_ERROR( CV_StsUnsupportedFormat, “Only 8-bit images are supported” );CV_CALL( temp = cvCreateMat( img-rows, img-cols, CV_8UC1 );CV_CALL( sum = cvCreateMat( im

18、g-rows + 1, img-cols + 1, CV_32SC1 );CV_CALL( sqsum = cvCreateMat( img-rows + 1, img-cols + 1, CV_64FC1 );CV_CALL( temp_storage = cvCreateChildMemStorage( storage );#ifdef _OPENMPmax_threads = cvGetNumThreads();for( i = 0; i hid_cascade )CV_CALL( icvCreateHidHaarClassifierCascade(cascade) );if( casc

19、ade-hid_cascade-has_tilted_features )tilted = cvCreateMat( img-rows + 1, img-cols + 1, CV_32SC1 ); /多通道矩阵 图像长宽+1 4 通道seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvRect), temp_storage ); /创建序列 seq 矩形seq2 = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), temp_storage ); /创建序列 seq2 矩形和邻近result_seq =

20、cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), storage ); /创建序列 result_seq 矩形和邻近if( min_neighbors = 0 )seq = result_seq;if( CV_MAT_CN(img-type) 1 )cvCvtColor( img, temp, CV_BGR2GRAY ); /img转为灰度img = temp; if( flags /CvSize win_size0为分类器的原始大小int use_ipp = cascade-hid_cascade-ipp_stages != 0 /IPP相关

21、函数if( use_ipp )CV_CALL( norm_img = cvCreateMat( img-rows, img-cols, CV_32FC1 ); /图像的矩阵化 4 通道.CV_CALL( img_small = cvCreateMat( img-rows + 1, img-cols + 1, CV_8UC1 ); /小图矩阵化 单通道 长宽+1for( factor = 1; ; factor *= scale_factor ) /成 scale_factor倍数匹配int positive = 0;int x, y;CvSize win_size = cvRound(win_

22、size0.width*factor),cvRound(win_size0.height*factor) ; /winsize 分类器行列(扩大 factor倍)CvSize sz = cvRound( img-cols/factor ), cvRound( img-rows/factor ) ; /sz 图像行列(缩小 factor倍) 三个 CvsizeCvSize sz1 = sz.width win_size0.width, sz.height win_size0.height ; /sz1 图像 减 分类器行列CvRect rect1 = icv_object_win_border,

23、 icv_object_win_border,win_size0.width icv_object_win_border*2, /icv_object_win_border (int) 初始值=1win_size0.height icv_object_win_border*2 ; /矩形框 rect1CvMat img1, sum1, sqsum1, norm1, tilted1, mask1; /多通道矩阵CvMat* _tilted = 0;if( sz1.width 跳出break;if( win_size.width 继续continue;/CV_8UC1见定义./#define CV

24、_MAKETYPE(depth,cn) (depth) + (cn)-1) data.ptr ); /小图的矩阵化 img1 单通道 sum1 = cvMat( sz.height+1, sz.width+1, CV_32SC1, sum-data.ptr ); /长宽+1 4 通道 8位 多通道矩阵sqsum1 = cvMat( sz.height+1, sz.width+1, CV_64FC1, sqsum-data.ptr ); /长宽+1 4 通道 16位if( tilted )tilted1 = cvMat( sz.height+1, sz.width+1, CV_32SC1, ti

25、lted-data.ptr ); /长宽+1 4 通道 8位_tilted = /长宽+1 4 通道 8位norm1 = cvMat( sz1.height, sz1.width, CV_32FC1, norm_img ? norm_img-data.ptr : 0 ); /norm1 图像 减 分类器行列 4 通道mask1 = cvMat( sz1.height, sz1.width, CV_8UC1, temp-data.ptr ); /mask1 灰度图cvResize( img, /img双线性插值 输出到 img1cvIntegral( /计算积分图像if( use_ipp /ma

26、sk1赋值为 255for( i = 0; i count; i+ )if( icvApplyHaarClassifier_32s32f_C1R_p(sum1.data.i, sum1.step,norm1.data.fl, norm1.step, mask1.data.ptr, mask1.step,sz1, /匹配图像.positive += mask1.data.ptrmask1.step*y + x;if( positive 0 )for( y = 0; y rows + 1, img-cols + 1, CV_32SC1 ); /如果 做 canny边缘检测cvCanny( img,

27、 temp, 0, 50, 3 );cvIntegral( temp, sumcanny );if( (unsigned)split_stage = (unsigned)cascade-count |cascade-hid_cascade-is_tree ) split_stage = cascade-count;npass = 1;基于 opencv的人脸识别算法#include #include #include #include #include / Global variablesint nTrainFaces = 0; / number of training imagesint n

28、Eigens = 0; / number of eigenvaluesIplImage * faceImgArr = 0; / array of face imagesCvMat * personNumTruthMat = 0; /array of person numbersIplImage * pAvgTrainImg = 0; / the average imageIplImage * eigenVectArr = 0; / eigenvectorsCvMat * eigenValMat = 0; / eigenvaluesCvMat * projectedTrainFaceMat =

29、0; / projected training faces/ Function prototypesvoid learn();void recognize();void doPCA();void storeTrainingData();int loadTrainingData(CvMat * pTrainPersonNumMat);int findNearestNeighbor(float * projectedTestFace);int loadFaceImgArray(char * filename);void printUsage();int main( int argc, char*

30、argv )/ validate that an input was specifiedif( argc != 2 )printUsage();return 1;if( !strcmp(argv1, “train“) ) learn();else if( !strcmp(argv1, “test“) ) recognize();elseprintf(“Unknown command: %sn“, argv1);return 0;void printUsage()printf(“Usage: eigenface n“,“ Valid commands aren“ trainn“testn“);v

31、oid learn()int i;/ load training datanTrainFaces = loadFaceImgArray(“train.txt“);if( nTrainFaces data.fl + i*nEigens);/ store the recognition data as an xml filestoreTrainingData();int loadFaceImgArray(char * filename)FILE * imgListFile = 0;char imgFilename512;int iFace, nFaces=0;/ open the input fi

32、leimgListFile = fopen(filename, “r“);/ count the number of faceswhile( fgets(imgFilename, 512, imgListFile) ) +nFaces;rewind(imgListFile);/ allocate the face-image array and person number matrixfaceImgArr = (IplImage *)cvAlloc( nFaces*sizeof(IplImage *) );personNumTruthMat = cvCreateMat( 1, nFaces,

33、CV_32SC1 );/ store the face images in an arrayfor(iFace=0; iFacedata.i+iFace, imgFilename);/ load the face imagefaceImgArriFace = cvLoadImage(imgFilename, CV_LOAD_IMAGE_GRAYSCALE);fclose(imgListFile);return nFaces;void doPCA()int i;CvTermCriteria calcLimit;CvSize faceImgSize;/ set the number of eige

34、nvalues to usenEigens = nTrainFaces-1;/ allocate the eigenvector imagesfaceImgSize.width = faceImgArr0-width;faceImgSize.height = faceImgArr0-height;eigenVectArr = (IplImage*)cvAlloc(sizeof(IplImage*) * nEigens);for(i=0; idata.fl);void storeTrainingData()CvFileStorage * fileStorage;int i;/ create a

35、file-storage interfacefileStorage = cvOpenFileStorage( “facedata.xml“, 0, CV_STORAGE_WRITE );/ store all the datacvWriteInt( fileStorage, “nEigens“, nEigens );cvWriteInt( fileStorage, “nTrainFaces“, nTrainFaces );cvWrite(fileStorage, “trainPersonNumMat“, personNumTruthMat, cvAttrList(0,0);cvWrite(fi

36、leStorage, “eigenValMat“, eigenValMat, cvAttrList(0,0);cvWrite(fileStorage, “projectedTrainFaceMat“, projectedTrainFaceMat, cvAttrList(0,0);cvWrite(fileStorage, “avgTrainImg“, pAvgTrainImg, cvAttrList(0,0);for(i=0; idata.ii;nearest = trainPersonNumMat-data.iiNearest;printf(“nearest = %d, Truth = %dn

37、“, nearest, truth);int loadTrainingData(CvMat * pTrainPersonNumMat)CvFileStorage * fileStorage;int i;/ create a file-storage interfacefileStorage = cvOpenFileStorage( “facedata.xml“, 0, CV_STORAGE_READ );if( !fileStorage )fprintf(stderr, “Cant open facedata.xmln“);return 0;nEigens = cvReadIntByName(

38、fileStorage, 0, “nEigens“, 0);nTrainFaces = cvReadIntByName(fileStorage, 0, “nTrainFaces“, 0);*pTrainPersonNumMat = (CvMat *)cvReadByName(fileStorage, 0, “trainPersonNumMat“, 0);eigenValMat = (CvMat *)cvReadByName(fileStorage, 0, “eigenValMat“, 0);projectedTrainFaceMat =(CvMat *)cvReadByName(fileSto

39、rage, 0, “projectedTrainFaceMat“, 0);pAvgTrainImg = (IplImage *)cvReadByName(fileStorage, 0, “avgTrainImg“, 0);eigenVectArr = (IplImage *)cvAlloc(nTrainFaces*sizeof(IplImage *);for(i=0; idata.fliTrain*nEigens + i;distSq += d_i*d_i/eigenValMat-data.fli;if(distSq leastDistSq)leastDistSq = distSq;iNearest = iTrain;printf(“%f“, leastDistSq);return iNearest;此程序网上转载,已经通过测试,能正常运行

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 企业管理 > 管理学资料

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报