//TempleMatch void MatchTemplate(CString imagefile,CString templefile) { //double a=0.; IplImage* imgSrc = cvLoadImage(“imagefile”); IplImage* imgTemp = cvLoadImage("templefile"); CvSize sizeSrc = cvGetSize(imgSrc); CvSize sizeTemp = cvGetSize(imgTemp); CvSize sizeResult = cvSize(sizeSrc.width-sizeTemp.width+1,sizeSrc.height-sizeTemp.height+1); IplImage* imgResult = cvCreateImage(sizeResult,IPL_DEPTH_32F,1); cvMatchTemplate(imgSrc,imgTemp,imgResult,CV_TM_CCORR_NORMED); float dMax = 0.; CvPoint point = cvPoint(0,0); //if(!a) MessageBox("Not Successful!",MB_OK); for (int cx=0 ; cx { for (int cy=0 ; cy { float fTemp = CV_IMAGE_ELEM(imgResult,float,cy,cx); if (dMax < fTemp) //找到最接近的位置 { dMax = fTemp; point = cvPoint(cx,cy); //记录位置 } } } CvPoint point2 = cvPoint(point.x+sizeTemp.width,point.y+sizeTemp.height); //对角位置 cvRectangle(imgSrc,point,point2,cvScalar(255)); cvNamedWindow( "Test", CV_WINDOW_AUTOSIZE ); cvShowImage("Test",imgSrc); /* for(;;) { int k = cvWaitKey(5); if( k == 27 ) break; } */ } void CFollowDlg::OnButton4() { // TODO: Add your control notification handler code here CString path; CFileDialog dlg(TRUE); if(dlg.DoModal()==IDOK) path=dlg.GetPathName(); MatchTemplate(path); }
关于cvMatchTemplate()的说明文档:
原型:
void cvMatchTemplate( const CvArr* image, const CvArr* templ, CvArr* result, int method );
image
例子摘自http://www.opencv.org.cn/forum/viewtopic.php?f=1&t=1736
int cvMatchShapes_test() { IplImage *mode = cvLoadImage("D:\\lena.jpg", 1); IplImage *test = cvLoadImage("D:\\test3.bmp", 1); IplImage* bw_mode = cvCreateImage(cvGetSize(mode),mode->depth,1); IplImage* bw_test = cvCreateImage(cvGetSize(test),mode->depth,1); IplImage* canny_mode = cvCreateImage(cvGetSize(mode),mode->depth,1); IplImage* canny_test = cvCreateImage(cvGetSize(test),mode->depth,1); CvMemStorage *mode_mems=cvCreateMemStorage(); CvSeq *mode_seqs; CvMemStorage *test_mems=cvCreateMemStorage(); CvSeq *test_seqs; cvCvtColor(mode,bw_mode,CV_RGB2GRAY); cvCvtColor(test,bw_test,CV_RGB2GRAY); //model contours //cvCanny(bw_mode,canny_mode,50,60); cvFindContours( bw_mode, mode_mems, &mode_seqs,sizeof(CvContour),CV_RETR_TREE); //test contours //cvCanny(bw_test,canny_test,50,60); cvFindContours( bw_test, test_mems, &test_seqs,sizeof(CvContour),CV_RETR_TREE); double matching=cvMatchShapes( test_seqs, mode_seqs, 3); printf("%f",matching); cvReleaseImage( &mode ); // cvReleaseImage( &test ); cvReleaseImage( &bw_mode ); // cvReleaseImage( &bw_test ); cvReleaseImage( &canny_mode ); // cvReleaseImage( &canny_test ); return 1; }
关于cvMatchShapes()的说明文档:
比较两个形状
double cvMatchShapes( const void* object1, const void* object2,
int method, double parameter=0 );
函数 cvMatchShapes 比较两个形状。 三个实现方法全部使用 Hu 矩 (见 cvGetHuMoments)