1#include "opencv2/imgproc.hpp" 2#include "opencv2/highgui.hpp" 3 4#include <cctype> 5#include <iostream> 6#include <iterator> 7#include <stdio.h> 8 9using namespace std; 10using namespace cv; 11 12static void help() 13{ 14 cout << "\nThis program demonstrates template match with mask.\n" 15 "Usage:\n" 16 "./mask_tmpl <image_name> <template_name> <mask_name>, Default is ../data/lena_tmpl.jpg\n" 17 << endl; 18} 19 20int main( int argc, const char** argv ) 21{ 22 const char* filename = argc == 4 ? argv[1] : "../data/lena_tmpl.jpg"; 23 const char* tmplname = argc == 4 ? argv[2] : "../data/tmpl.png"; 24 const char* maskname = argc == 4 ? argv[3] : "../data/mask.png"; 25 26 Mat img = imread(filename); 27 Mat tmpl = imread(tmplname); 28 Mat mask = imread(maskname); 29 Mat res; 30 31 if(img.empty()) 32 { 33 help(); 34 cout << "can not open " << filename << endl; 35 return -1; 36 } 37 38 if(tmpl.empty()) 39 { 40 help(); 41 cout << "can not open " << tmplname << endl; 42 return -1; 43 } 44 45 if(mask.empty()) 46 { 47 help(); 48 cout << "can not open " << maskname << endl; 49 return -1; 50 } 51 52 //int method = CV_TM_SQDIFF; 53 int method = CV_TM_CCORR_NORMED; 54 matchTemplate(img, tmpl, res, method, mask); 55 56 double minVal, maxVal; 57 Point minLoc, maxLoc; 58 Rect rect; 59 minMaxLoc(res, &minVal, &maxVal, &minLoc, &maxLoc); 60 61 if(method == CV_TM_SQDIFF || method == CV_TM_SQDIFF_NORMED) 62 rect = Rect(minLoc, tmpl.size()); 63 else 64 rect = Rect(maxLoc, tmpl.size()); 65 66 rectangle(img, rect, Scalar(0, 255, 0), 2); 67 68 imshow("detected template", img); 69 waitKey(); 70 71 return 0; 72} 73