2
* @file MatchTemplate_Demo.cpp
3
* @brief Sample code to use the function MatchTemplate
7
#include "opencv2/imgcodecs.hpp"
8
#include "opencv2/highgui/highgui.hpp"
9
#include "opencv2/imgproc/imgproc.hpp"
17
Mat img; Mat templ; Mat result;
18
const char* image_window = "Source Image";
19
const char* result_window = "Result window";
25
void MatchingMethod( int, void* );
30
int main( int, char** argv )
32
/// Load image and template
33
img = imread( argv[1], 1 );
34
templ = imread( argv[2], 1 );
37
namedWindow( image_window, WINDOW_AUTOSIZE );
38
namedWindow( result_window, WINDOW_AUTOSIZE );
41
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";
42
createTrackbar( trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod );
44
MatchingMethod( 0, 0 );
51
* @function MatchingMethod
52
* @brief Trackbar callback
54
void MatchingMethod( int, void* )
56
/// Source image to display
58
img.copyTo( img_display );
60
/// Create the result matrix
61
int result_cols = img.cols - templ.cols + 1;
62
int result_rows = img.rows - templ.rows + 1;
64
result.create( result_rows, result_cols, CV_32FC1 );
66
/// Do the Matching and Normalize
67
matchTemplate( img, templ, result, match_method );
68
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
70
/// Localizing the best match with minMaxLoc
71
double minVal; double maxVal; Point minLoc; Point maxLoc;
74
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
77
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
78
if( match_method == TM_SQDIFF || match_method == TM_SQDIFF_NORMED )
79
{ matchLoc = minLoc; }
81
{ matchLoc = maxLoc; }
83
/// Show me what you got
84
rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
85
rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
87
imshow( image_window, img_display );
88
imshow( result_window, result );