模板匹配就是在一幅图像中寻找和模板图像(patch)最相似的区域。在OpenCV中的函数为matchTemplate,该函数的功能是,在输入源图像Source image(I)中滑动框,寻找各个位置与模板图像Template image(T)的相似度,并将结果保存在结果矩阵result matrix(R)中。该矩阵的每一个点的亮度表示与模板T的匹配程度。然后可以通过函数minMaxLoc定位矩阵R中的最大值(该函数也可以确定最小值)。
先讲下上面提到的两个函数
1、函数matchTemplate()
作用:比较模板图像和源图像重叠区域的匹配
C++: void matchTemplate(InputArray image, InputArray templ, OutputArray result, int method)
C: void cvMatchTemplate(const CvArr* image, const CvArr* templ, CvArr* result, int method)
Parameters: |
|
---|
CV_TM_SQDIFF 平方差匹配法,最好的匹配为0,值越大匹配越差
CV_TM_SQDIFF_NORMED 归一化平方差匹配法
CV_TM_CCORR 相关匹配法,采用乘法操作,数值越大表明匹配越好
CV_TM_CCORR_NORMED 归一化相关匹配法
CV_TM_CCOEFF 相关系数匹配法,最好的匹配为1,-1表示最差的匹配
CV_TM_CCOEFF_NORMED 归一化相关系数匹配法
前面两种方法为越小的值表示越匹配,后四种方法值越大越匹配。
2、函数 minMaxLoc()
作用:找到矩阵中全局最大值和最小值
C++: void minMaxLoc(InputArraysrc, double* minVal, double* maxVal=0, Point*minLoc=0, Point* maxLoc=0, InputArray mask=noArray())
C: void cvMinMaxLoc(const CvArr*arr, double* min_val, double* max_val, CvPoint*min_loc=NULL, CvPoint* max_loc=NULL, const CvArr*mask=NULL )
Parameters: |
|
---|
直接贴代码,网上一搜挺多的,参考了下其他的,这里主要用的是Mat格式:
#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;
//加载
img = imread( "car.jpg");
tpl = imread( "car_cut.jpg" );
//得到图像的属性
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;
//为模板匹配计算创建一个新图像
res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );
//选择模板和匹配方法
matchTemplate( img, tpl, res, CV_TM_SQDIFF ); //平方差匹配法
minMaxLoc( res, &minval, &maxval, &minloc, &maxloc,mask);
// 画出黑色的正方形框
rectangle( img,
cvPoint( minloc.x, minloc.y ),
cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ),
cvScalar( 0, 0, 0, 0 ), 1, 0, 0 );
//显示
namedWindow("reference",1);
namedWindow("template",1);
imshow( "reference", img );
waitKey(30);
imshow( "template", tpl );
waitKey(30);
system("pause");
return 0;
}
模板匹配的方法和直方图反向投影基本一样,都是滑动图像模板和输入图像进行匹配。但模板匹配对比的是像素,所以速度上要快些,直方图反向投影对比的是直方图,鲁棒性更好。