Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Getting coordinates from template matching

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

int main()
{
    cv::Mat ref = cv::imread("image.png");
    cv::Mat tpl = cv::imread("template1.png");
    if (ref.empty() || tpl.empty())
        return -1;

    cv::Mat gref, gtpl;
    cv::cvtColor(ref, gref, CV_BGR2GRAY);
    cv::cvtColor(tpl, gtpl, CV_BGR2GRAY);

    cv::Mat res(ref.rows-tpl.rows+1, ref.cols-tpl.cols+1, CV_32FC1);
    cv::matchTemplate(gref, gtpl, res, CV_TM_CCOEFF_NORMED);
    cv::threshold(res, res, 0.8, 1., CV_THRESH_TOZERO);

    while (true)
    {
        double minval, maxval, threshold = 0.8;
        cv::Point minloc, maxloc;
        cv::minMaxLoc(res, &minval, &maxval, &minloc, &maxloc);

        if (maxval >= threshold)
        {
            cv::rectangle(
                ref,
                maxloc,
                cv::Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows),
                CV_RGB(255,0,0), 2
            );
            cv::floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(.1), cv::Scalar(1.));
        }
        else
            break;
    }

    cv::imshow("reference", ref);
    cv::waitKey();
    return 0;
}

I am using this code for multiple matching to find 3 images on the screen. But how can i get coordinates from those images? I need bottom-right from the first one, bottom-left from the second and top-left from third. I understand that i am using them to draw a rectangle, but i dont know in what order it is finding the images. C:\fakepath\image.png