#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <cxcore.h>
#include <iostream> using namespace cv;
using namespace std;
#define DEBUG
double matchShapes(IplImage* src, IplImage* tmplt);
CvPoint matchTemplate(IplImage* src, IplImage* tmplt);
void L_TemplateMatch(IplImage* src,IplImage* tmp);
int _tmain(int argc, _TCHAR* argv[])
{
cvNamedWindow("tmplt", );
cvNamedWindow("src", ); IplImage* pcbmark = cvLoadImage("5_000004.bmp", );
IplImage* tmplt = cvLoadImage("model.bmp", );
// IplImage* Rg=cvCreateImage(cvGetSize(pcbmark),8,3);
//cvCvtColor(pcbmark,Rg,CV_GRAY2BGR); double t=(double)getTickCount();
// cvWaitKey(1000); #ifdef DEBUG
//cvShowImage("BGR", Rg);
cvShowImage("src", pcbmark);
cvShowImage("tmplt", tmplt);
cvWaitKey();
#endif CvPoint center = matchTemplate(pcbmark, tmplt); t=((double)getTickCount()-t)/getTickFrequency();
cout<<t<<endl;
cvDestroyWindow("tmplt");
cvDestroyWindow("src");
return ;
}
CvPoint matchTemplate(IplImage* src, IplImage* tmplt)
{
CvPoint center;
CvSize sizeSrc = cvGetSize(src);
CvSize sizeTemp = cvGetSize(tmplt);
CvSize sizeResult = cvSize(sizeSrc.width-sizeTemp.width+1,sizeSrc.height-sizeTemp.height+1);
IplImage* imgResult = cvCreateImage(sizeResult,IPL_DEPTH_32F,1);
cvMatchTemplate(src,tmplt,imgResult,CV_TM_CCORR_NORMED);
// a=cvMatchShapes(src,tmplt,CV_CONTOURS_MATCH_I3);
float dMax = 0.;
CvPoint point = cvPoint(0,0);
//for (int cx=0 ; cx<sizeResult.width; cx++)
//{
//for (int cy=0 ; cy<sizeResult.height; 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(src,point,point2,cvScalar(255));
//center.x = fabs((double)(point.x + point2.x)/2);
//center.y = fabs((double)(point.y + point2.y)/2);
double min_val;
double max_val;
CvPoint pt1;
CvPoint pt2;
CvPoint min_loc;
CvPoint max_loc;
cvMinMaxLoc(imgResult,&min_val,&max_val,&min_loc,&max_loc,NULL);
CvRect rect=cvRect(max_loc.x,max_loc.y,tmplt->width,tmplt->height);
pt1=cvPoint(rect.x,rect.y);
pt2=cvPoint(rect.x+rect.width,rect.y+rect.height);
cvRectangle(src,pt1,pt2,cvScalar(255));
center.x = fabs((double)(pt1.x + pt2.x)/2);
center.y = fabs((double)(pt1.y + pt2.y)/2);
cvNamedWindow( "Test", CV_WINDOW_AUTOSIZE );
cvShowImage("Test",src);
cvWaitKey();
cvDestroyWindow("Test");
return center;
}