1.模板匹配介绍
- 模板匹配就是在整个图像区域发现与给定子图像匹配的小块区域;
- 模板匹配需要首先给定一个模板图像;
- 另外需要一张待检测的图像;
- 工作方法:在待检测图像上,从左到右,从上到下计算模板图像与重叠子图像的匹配度,匹配程度越大,两者相同的可能性越大。
2.API
matchTemplate
matchTemplate(
InputArray image, //原图像,必须是8-bit或者32-bit浮点数图像
InputArray templ, //模板图像,类型与输入图像一致
OutputArray result, //输出结果,必须是单通道32位浮点数,假设原图像W*H,模板图像w*h,结果必须为W-w+1,H-h+1的大小
int method, //使用的匹配方法
InputArray mask=noArray()
)
enum cv::TemplateMatchModes {
cv::TM_SQDIFF = 0,
cv::TM_SQDIFF_NORMED = 1,
cv::TM_CCORR = 2,
cv::TM_CCORR_NORMED = 3,
cv::TM_CCOEFF = 4,
cv::TM_CCOEFF_NORMED = 5
}
minMaxLoc(src, minVal, maxVal, minLoc, maxLoc, mask)
/*
在一个数组中找到全局最小值和全局最大值
minMaxLoc函数找到最小值和最大值元素值以及它们的位置。
*/
3.实例代码
#include
#include
#include
using namespace std;
using namespace cv;
Mat src, temp, dst;
int match_method = TM_SQDIFF;
int max_track = 5;
const char* INPUT_T = "input image";
const char* OUTPUT_T = "result image";
const char* match_t = "template match-demo";
void Match_Demo(int, void*);
int main(int argc, char** argv) {
// 待检测图像
src = imread("D:/vcprojects/images/flower.png");
// 模板图像
temp = imread("D:/vcprojects/images/t2.png");
if (src.empty() || temp.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow(INPUT_T, CV_WINDOW_AUTOSIZE);
namedWindow(OUTPUT_T, CV_WINDOW_NORMAL);
namedWindow(match_t, CV_WINDOW_AUTOSIZE);
imshow(INPUT_T, temp);
const char* trackbar_title = "Match Algo Type:";
createTrackbar(trackbar_title, OUTPUT_T, &match_method, max_track, Match_Demo);
Match_Demo(0, 0);
waitKey(0);
return 0;
}
void Match_Demo(int, void*) {
int width = src.cols - temp.cols + 1;
int height = src.rows - temp.rows + 1;
Mat result(width, height, CV_32FC1);
matchTemplate(src, temp, result, match_method, Mat());
normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());
Point minLoc;
Point maxLoc;
double min, max;
src.copyTo(dst);
Point temLoc;
minMaxLoc(result, &min, &max, &minLoc, &maxLoc, Mat());
if (match_method == TM_SQDIFF || match_method == TM_SQDIFF_NORMED) {
temLoc = minLoc;
} else {
temLoc = maxLoc;
}
// 绘制矩形
rectangle(dst, Rect(temLoc.x, temLoc.y, temp.cols, temp.rows), Scalar(0, 0, 255), 2, 8);
rectangle(result, Rect(temLoc.x, temLoc.y, temp.cols, temp.rows), Scalar(0, 0, 255), 2, 8);
imshow(OUTPUT_T, result);
imshow(match_t, dst);
}