/*===============================================//
功能:Template Matching with OpenCV
时间:3/22/2011 SkySeraph HQU
//===============================================*/
#include "iostream"
using
namespace
std;
#include "cv.h"
#include "highgui.h"
#include "math.h"
#pragma comment(lib,"highgui.lib")
#pragma comment(lib,"cv.lib")
#pragma comment(lib,"cvaux.lib")
#pragma comment(lib,"cxcore.lib")
const
char
* filename1 =
"D:\\My Documents\\My Pictures\\Images\\归一化.bmp"
;
const
char
* filename2 =
"D:\\My Documents\\My Pictures\\Images\\归一化模板.bmp"
;
/*=============================================*/
int
main(
int
argc,
char
** argv )
{
IplImage *img;
IplImage *tpl;
IplImage *res;
CvPoint minloc, maxloc;
double
minval, maxval;
int
img_width, img_height;
int
tpl_width, tpl_height;
int
res_width, res_height;
img = cvLoadImage( filename1, CV_LOAD_IMAGE_COLOR );
tpl = cvLoadImage( filename2, CV_LOAD_IMAGE_COLOR );
if
( tpl == 0 )
{
fprintf
( stderr,
"Cannot load file %s!\n"
, argv[2] );
return
1;
}
cvNamedWindow(
"src"
, CV_WINDOW_AUTOSIZE );
cvShowImage(
"src"
, img );
cvNamedWindow(
"template"
, CV_WINDOW_AUTOSIZE );
cvShowImage(
"template"
, tpl );
/* get image's properties */
img_width = img->width;
img_height = img->height;
tpl_width = tpl->width;
tpl_height = tpl->height;
res_width = img_width - tpl_width + 1;
res_height = img_height - tpl_height + 1;
/* create new image for template matching computation */
res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );
/* choose template matching method to be used */
cvMatchTemplate( img, tpl, res, CV_TM_CCORR_NORMED );
/*cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF_NORMED );
cvMatchTemplate( img, tpl, res, CV_TM_CCORR );
cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF );
cvMatchTemplate( img, tpl, res, CV_TM_CCOEFF );
cvMatchTemplate( img, tpl, res, CV_TM_CCOEFF_NORMED );*/
cvNamedWindow(
"res"
, CV_WINDOW_AUTOSIZE );
cvShowImage(
"res"
, res );
cvMinMaxLoc( res, &minval, &maxval, &minloc, &maxloc, 0 );
/* draw red rectangle */
/*cvRectangle( img,
cvPoint( minloc.x, minloc.y ),
cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ),
cvScalar( 0, 0, 255, 0 ), 1, 0, 0 );*/
CvPoint pt1;
CvPoint pt2;
CvRect rect;
rect=cvRect(maxloc.x,maxloc.y,tpl->width,tpl->height);
//最佳的匹配区域
pt1=cvPoint(rect.x,rect.y);
pt2=cvPoint(rect.x+rect.width,rect.y+rect.height);
cvRectangle( img,pt1, pt2, cvScalar(0,0,255),1, 8, 0 );
/* display images */
cvNamedWindow(
"reference"
, CV_WINDOW_AUTOSIZE );
cvShowImage(
"reference"
, img );
/* wait until user press a key to exit */
cvWaitKey( 0 );
/* free memory */
cvDestroyWindow(
"reference"
);
cvDestroyWindow(
"template"
);
cvReleaseImage( &img );
cvReleaseImage( &tpl );
cvReleaseImage( &res );
return
0;
}