mask_tmpl.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "opencv2/imgproc.hpp"
  2. #include "opencv2/highgui.hpp"
  3. #include <iostream>
  4. using namespace std;
  5. using namespace cv;
  6. int main( int argc, const char** argv )
  7. {
  8. CommandLineParser parser(argc, argv,
  9. "{ i | lena_tmpl.jpg |image name }"
  10. "{ t | tmpl.png |template name }"
  11. "{ m | mask.png |mask name }"
  12. "{ cm| 3 |comparison method }");
  13. cout << "This program demonstrates the use of template matching with mask." << endl
  14. << endl
  15. << "Available methods: https://docs.opencv.org/4.x/df/dfb/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d" << endl
  16. << " TM_SQDIFF = " << (int)TM_SQDIFF << endl
  17. << " TM_SQDIFF_NORMED = " << (int)TM_SQDIFF_NORMED << endl
  18. << " TM_CCORR = " << (int)TM_CCORR << endl
  19. << " TM_CCORR_NORMED = " << (int)TM_CCORR_NORMED << endl
  20. << " TM_CCOEFF = " << (int)TM_CCOEFF << endl
  21. << " TM_CCOEFF_NORMED = " << (int)TM_CCOEFF_NORMED << endl
  22. << endl;
  23. parser.printMessage();
  24. string filename = samples::findFile(parser.get<string>("i"));
  25. string tmplname = samples::findFile(parser.get<string>("t"));
  26. string maskname = samples::findFile(parser.get<string>("m"));
  27. Mat img = imread(filename);
  28. Mat tmpl = imread(tmplname);
  29. Mat mask = imread(maskname);
  30. Mat res;
  31. if(img.empty())
  32. {
  33. cout << "can not open " << filename << endl;
  34. return -1;
  35. }
  36. if(tmpl.empty())
  37. {
  38. cout << "can not open " << tmplname << endl;
  39. return -1;
  40. }
  41. if(mask.empty())
  42. {
  43. cout << "can not open " << maskname << endl;
  44. return -1;
  45. }
  46. int method = parser.get<int>("cm"); // default 3 (CV_TM_CCORR_NORMED)
  47. matchTemplate(img, tmpl, res, method, mask);
  48. double minVal, maxVal;
  49. Point minLoc, maxLoc;
  50. Rect rect;
  51. minMaxLoc(res, &minVal, &maxVal, &minLoc, &maxLoc);
  52. if(method == TM_SQDIFF || method == TM_SQDIFF_NORMED)
  53. rect = Rect(minLoc, tmpl.size());
  54. else
  55. rect = Rect(maxLoc, tmpl.size());
  56. rectangle(img, rect, Scalar(0, 255, 0), 2);
  57. imshow("detected template", img);
  58. waitKey();
  59. return 0;
  60. }