功能
在父图像中寻找幅图像中的子图像
相关API
CV::matchTemplate(
InputMat,//原图像
InputMat,//模板图像
OutputArray result,//输出结果,必须是单通道32位浮点数,假设原图像width*height,模板图像WIDTH*HEIGHT,则结果必须为width-WIDTH+1,height-HEIGHT+1的大小
input method,//使用的匹配方法
InputArray mask=noArray()//(optional)
)
//模板匹配类型枚举
enum templatematchmodes{
TM_SQDIFF=0,
TM_SQDIFF_NORMED=1,
TM_CCORR=2,
TM_CCORRR_NORMED=3,
TM_CCOEFF=4,
TM_CCOEFF_NORMED=5
}
样例代码
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
const char* file= "b.jpg";
//加载原图像
Mat original = imread("b.jpg");
imshow("original", original);
//加载原图像中的一部分
Rect rect(100, 100,original.cols * 0.25, original.rows * 0.24);
Mat find = imread(file)(rect);//加载原来图像的其中的一小部分
imshow("find", find);
//开始模板匹配操作
Mat result(original.cols - find.cols + 1, original.rows - find.rows + 1, CV_32F);
matchTemplate(original, find, result, CV_TM_SQDIFF, Mat());
normalize(result,result, 0, 1, NORM_MINMAX, -1, Mat());
Point minLoc;
Point maxLoc;
double min, max;
minMaxLoc(result,&min,&max,&minLoc,&maxLoc,Mat());
rectangle(original, Rect(minLoc.x,minLoc.y,find.cols,find.rows),Scalar(255,0,0),2,8);
//画矩形的这个点,如果是CV_TM_SQDIFF或者CV_TM_SQDIFF_NORMED
//则是minLoc否则则是maxLoc
imshow("io",original);
waitKey(0);
return 0;
}