opencv4 学习 17 模板匹配算法
算法步骤:
- 加载原始图像
- 加载模板图像
- 使用模板图像作为滑动窗口与原始图像相应patch计算相似度。
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
bool use_mask = false;
Mat img, templ, mask, result;
const char* image_window = "Source Image";
const char* result_window = "Result window";
int match_method;
int max_Trackbar = 5;
void matchingMethod(int, void*){
Mat img_display;
img.copyTo(img_display);
int result_cols = img.cols - templ.cols + 1;
int result_rows = img.rows - templ.rows + 1;
result.create(result_rows, result_cols, CV_32FC1);
bool method_accepts_mask = (TM_SQDIFF == match_method || match_method == TM_CCORR_NORMED);
if(use_mask && method_accepts_mask){
matchTemplate(img, templ, result, match_method, mask);
}else{
matchTemplate(img, templ, result, match_method);
}
normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());
double minVal, maxVal;
Point minLoc, maxLoc;
Point matchLoc;
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
if(match_method == TM_SQDIFF || match_method == TM_SQDIFF_NORMED){
matchLoc = minLoc;
}else{
matchLoc = maxLoc;
}
rectangle(img_display, matchLoc, Point(matchLoc.x + templ.cols, matchLoc.y + templ.rows), Scalar::all(0), 2, 8, 0);
rectangle(result, matchLoc, Point(matchLoc.x + templ.cols, matchLoc.y + templ.rows), Scalar::all(0), 2, 8, 0);
imshow(image_window, img_display);
imshow(result_window, result);
return;
}
int main(int argc, char* argv[])
{
img = imread("./Template_Matching_Original_Image.jpg", IMREAD_COLOR);
templ = imread("./Template_Matching_Template_Image.jpg", IMREAD_COLOR);
if(use_mask) mask = imread("mask.jpg", IMREAD_COLOR);
namedWindow(image_window, WINDOW_AUTOSIZE);
namedWindow(result_window, WINDOW_AUTOSIZE);
const char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF_NORMED \n 2: TM_CCORR \n 3: TM_CCORR_NORMED \n "
"4: TM_COEFF \n 5: TM_COEFF_NORMED";
createTrackbar(trackbar_label, image_window, &match_method, max_Trackbar, matchingMethod);
matchingMethod(0,0);
waitKey(0);
return 0;
}
参考:https://docs.opencv.org/3.4/de/da9/tutorial_template_matching.html