File: mask_tmpl.cpp

package info (click to toggle)
opencv 4.5.1%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 268,248 kB
  • sloc: cpp: 969,170; xml: 682,525; python: 36,732; lisp: 30,170; java: 25,155; ansic: 7,927; javascript: 5,643; objc: 2,041; sh: 935; cs: 601; perl: 494; makefile: 145
file content (74 lines) | stat: -rw-r--r-- 2,195 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int main( int argc, const char** argv )
{
    CommandLineParser parser(argc, argv,
        "{ i | lena_tmpl.jpg |image name }"
        "{ t | tmpl.png |template name }"
        "{ m | mask.png |mask name }"
        "{ cm| 3 |comparison method }");

    cout << "This program demonstrates the use of template matching with mask." << endl
         << endl
         << "Available methods: https://docs.opencv.org/master/df/dfb/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d" << endl
         << "    TM_SQDIFF = " << (int)TM_SQDIFF << endl
         << "    TM_SQDIFF_NORMED = " << (int)TM_SQDIFF_NORMED << endl
         << "    TM_CCORR = " << (int)TM_CCORR << endl
         << "    TM_CCORR_NORMED = " << (int)TM_CCORR_NORMED << endl
         << "    TM_CCOEFF = " << (int)TM_CCOEFF << endl
         << "    TM_CCOEFF_NORMED = " << (int)TM_CCOEFF_NORMED << endl
         << endl;

    parser.printMessage();

    string filename = samples::findFile(parser.get<string>("i"));
    string tmplname = samples::findFile(parser.get<string>("t"));
    string maskname = samples::findFile(parser.get<string>("m"));
    Mat img = imread(filename);
    Mat tmpl = imread(tmplname);
    Mat mask = imread(maskname);
    Mat res;

    if(img.empty())
    {
        cout << "can not open " << filename << endl;
        return -1;
    }

    if(tmpl.empty())
    {
        cout << "can not open " << tmplname << endl;
        return -1;
    }

    if(mask.empty())
    {
        cout << "can not open " << maskname << endl;
        return -1;
    }

    int method = parser.get<int>("cm"); // default 3 (CV_TM_CCORR_NORMED)
    matchTemplate(img, tmpl, res, method, mask);

    double minVal, maxVal;
    Point minLoc, maxLoc;
    Rect rect;
    minMaxLoc(res, &minVal, &maxVal, &minLoc, &maxLoc);

    if(method == TM_SQDIFF || method == TM_SQDIFF_NORMED)
        rect = Rect(minLoc, tmpl.size());
    else
        rect = Rect(maxLoc, tmpl.size());

    rectangle(img, rect, Scalar(0, 255, 0), 2);

    imshow("detected template", img);
    waitKey();

    return 0;
}