模板匹配是在一幅圖像中尋找到與給定目標模板圖像的技術。在匹配過程中有兩個主要因素:原圖像I,模板圖像T。爲了在I上檢測到與T最匹配的區域,需要在I上滑動模板窗口,每次需要將T在I上滑動一個像素大小(從左至右,從上至下),每次移動後,計算出其相似度來表徵匹配結果的好與壞。依次將每個位置的匹配結果存儲在R矩陣中,該矩陣的每一個點的亮度表示與模板T的匹配程度(越亮,匹配程度越高)。通過 minMaxLoc 函數可以找到R矩陣中的最大(小)值。
匹配方法:
a)method=CV_TM_SQDIFF
b)method=CV_TM_SQDIFF_NORMED
c)method=CV_TM_CCORR
d)method=CV_TM_CCORR_NORMED
e)method=CV_TM_CCOEFF
f)method=CV_TM_CCOEFF_NOR
以下是實現圖像匹配的例程,其中定義了一個函數match實現匹配的具體過程:
// Templatematch.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
void match(Mat img,Mat tem);
int main( int argc, char** argv )
{
Mat img;
Mat tem;
img = imread("xiaobei.jpg" ); //讀取原圖像"xiaobei.jpg"
if( img.empty() ) { //判斷是否讀取成功
cerr << "Cannot load file " << "xiaobei.jpg" << endl;
return -1;
}
tem = imread("mask.jpg"); //讀取模板圖像"mask.jpg"
if( tem.empty()) {
cerr << "Cannot load file " <<"mask.jpg" << endl;
return -1;
}
match( img, tem);
imshow( "result", img );
imshow( "template", tem ); //顯示結果
/* wait until user press a key to exit */
cvWaitKey( 0 );
return 0;
}
void match(Mat img,Mat tem)
{
Mat res;
Mat mask;
Point minloc, maxloc;
double minval, maxval;
int res_cols = img.cols - tem.cols + 1;
int res_rows = img.rows - tem.rows + 1;
res = cvCreateImage( cvSize(res_cols,res_rows), IPL_DEPTH_32F, 1 );
matchTemplate( img, tem, res,CV_TM_SQDIFF_NORMED ); //歸一化平方差匹配法
minMaxLoc( res, &minval, &maxval, &minloc, &maxloc,mask);
rectangle( img, cvPoint( minloc.x, minloc.y ), cvPoint( minloc.x + tem.cols, minloc.y + tem.rows ),
cvScalar( 255, 255, 255, 0 ), 1, 0, 0 );
}
演示效果:
模板:
結果:
這裏主要對以下兩點進行分析:
1)
int res_cols = img.cols - tem.cols + 1;
int res_rows = img.rows - tem.rows + 1;
結果矩陣R的計算,我是這樣理解的:文章開篇提到模板圖像每次在原圖像上移動一個像素,並將計算出來的相似度存儲在R中,那麼在整個圖像上每行橫向移動只需移動img.rows-tem.rows個長度,因此每行共計算出img.rows-tem.rows+1個結果。同理,每列共計算出img.cols-tem.cols+1個結果。
2)兩個函數:
未完待續~~~~~~~~~