在opencv代码中,matchTemplate函数保存在文件imgproc文件夹下的templmatch.cpp中。主要包括下面三个函数:
void crossCorr( const Mat& img, const Mat& _templ, Mat& corr,Size corrsize, int ctype,Point anchor, double delta, int borderType )
void cv::matchTemplate( InputArray _img, InputArray _templ, OutputArray _result, int method )
CV_IMPL void cvMatchTemplate( const CvArr* _img, const CvArr* _templ, CvArr* _result, int method )
完整源代码如下:
#include "precomp.hpp"
namespace cv
{
void crossCorr( const Mat& img, const Mat& _templ, Mat& corr,
Size corrsize, int ctype,
Point anchor, double delta, int borderType )
{
const double blockScale = 4.5;
const int minBlockSize = 256;
std::vector<uchar> buf;
Mat templ = _templ;
int depth = img.depth(), cn = img.channels();
int tdepth = templ.depth(), tcn = templ.channels();
int cdepth = CV_MAT_DEPTH(ctype), ccn = CV_MAT_CN(ctype);
CV_Assert( img.dims <= 2 && templ.dims <= 2 && corr.dims <= 2 );
if( depth != tdepth && tdepth != std::max(CV_32F, depth) )
{
_templ.convertTo(templ, std::max(CV_32F, depth));
tdepth = templ.depth();
}
CV_Assert( depth == tdepth || tdepth == CV_32F);
CV_Assert( corrsize.height <= img.rows + templ.rows - 1 &&
corrsize.width <= img.cols + templ.cols - 1 );
CV_Assert( ccn == 1 || delta == 0 );
corr.create(corrsize, ctype);
int maxDepth = depth > CV_8S ? CV_64F : std::max(std::max(CV_32F, tdepth), cdepth);
Size blocksize, dftsize;
blocksize.width = cvRound(templ.cols*blockScale);
blocksize.width = std::max( blocksize.width, minBlockSize - templ.cols + 1 );
blocksize.width = std::min( blocksize.width, corr.cols );
blocksize.height = cvRound(templ.rows*blockScale);
blocksize.height = std::max( blocksize.height, minBlockSize - templ.rows + 1 );
blocksize.height = std::min( blocksize.height, corr.rows );
dftsize.width = std::max(getOptimalDFTSize(blocksize.width + templ.cols - 1), 2);
dftsize.height = getOptimalDFTSize(blocksize.height + templ.rows - 1);
if( dftsize.width <= 0 || dftsize.height <