代码:
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main( int argc, char** argv )
{
Mat img;
Mat tpl;
Mat res;
Mat mask;
Point minloc, maxloc;
double minval, maxval;
int img_width, img_height;
int tpl_width, tpl_height;
int res_width, res_height;
/* check for arguments */
if( argc < 3 ) {
cerr << "Usage: template_match <reference> <template>" << endl;
return 1;
}
/* load reference image */
img = imread( argv[1] );
/* always check */
if( img.empty() ) {
cerr << "Cannot load file " << argv[1] << endl;
return 1;
}
/* load template image */
tpl = imread( argv[2] );
/* always check */
if( tpl.empty()) {
cerr << "Cannot load file " << argv[2] << endl;
return 1;
}
/* get image's properties */
img_width = img.cols;
img_height = img.rows;
tpl_width = tpl.cols;
tpl_height = tpl.rows;
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 */
matchTemplate( img, tpl, res, CV_TM_SQDIFF );
minMaxLoc( res, &minval, &maxval, &minloc, &maxloc,mask);
/* draw white rectangle */
rectangle( img,
cvPoint( minloc.x, minloc.y ),
cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ),
cvScalar( 255, 255, 255, 0 ), 1, 0, 0 );
/* display images */
imshow( "reference", img );
imshow( "template", tpl );
/* wait until user press a key to exit */
cvWaitKey( 0 );
return 0;
}
函数minMaxLoc()
作用:找到矩阵中全局最大值和最小值。
C++: void minMaxLoc(InputArray src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArraymask=noArray())¶
具体参数含义参考:http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#minmaxloc
函数 matchTemplate()
作用:比较模板图像和源图像重叠区域的匹配。
C++: void matchTemplate(InputArray image, InputArray templ, OutputArray result, int method)
具体参数含义参考:http://docs.opencv.org/modules/imgproc/doc/object_detection.html
结果
模板图像
匹配之后
图中白色框区域是匹配区域,效果很不错哦!
文章参考:http://www.cnblogs.com/gnuhpc/archive/2012/12/07/2807494.html