1/**
2 * @file MatchTemplate_Demo.cpp
3 * @brief Sample code to use the function MatchTemplate
4 * @author OpenCV team
5 */
6
7#include "opencv2/imgcodecs.hpp"
8#include "opencv2/highgui/highgui.hpp"
9#include "opencv2/imgproc/imgproc.hpp"
10#include <iostream>
11#include <stdio.h>
12
13using namespace std;
14using namespace cv;
15
16/// Global Variables
17Mat img; Mat templ; Mat result;
18const char* image_window = "Source Image";
19const char* result_window = "Result window";
20
21int match_method;
22int max_Trackbar = 5;
23
24/// Function Headers
25void MatchingMethod( int, void* );
26
27/**
28 * @function main
29 */
30int main( int, char** argv )
31{
32  /// Load image and template
33  img = imread( argv[1], 1 );
34  templ = imread( argv[2], 1 );
35
36  /// Create windows
37  namedWindow( image_window, WINDOW_AUTOSIZE );
38  namedWindow( result_window, WINDOW_AUTOSIZE );
39
40  /// Create Trackbar
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 );
43
44  MatchingMethod( 0, 0 );
45
46  waitKey(0);
47  return 0;
48}
49
50/**
51 * @function MatchingMethod
52 * @brief Trackbar callback
53 */
54void MatchingMethod( int, void* )
55{
56  /// Source image to display
57  Mat img_display;
58  img.copyTo( img_display );
59
60  /// Create the result matrix
61  int result_cols =  img.cols - templ.cols + 1;
62  int result_rows = img.rows - templ.rows + 1;
63
64  result.create( result_rows, result_cols, CV_32FC1 );
65
66  /// Do the Matching and Normalize
67  matchTemplate( img, templ, result, match_method );
68  normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
69
70  /// Localizing the best match with minMaxLoc
71  double minVal; double maxVal; Point minLoc; Point maxLoc;
72  Point matchLoc;
73
74  minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
75
76
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; }
80  else
81    { matchLoc = maxLoc; }
82
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 );
86
87  imshow( image_window, img_display );
88  imshow( result_window, result );
89
90  return;
91}
92