Ask Your Question
0

Getting coordinates from template matching

asked 2015-04-22 05:32:10 -0600

Storiy gravatar image
#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

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2015-04-22 14:43:37 -0600

Eduardo gravatar image

In the matrix res, you have at each pixel location the correlation score between the template image and the query image.

The function minMaxLoc will return the global minimum and maximum in an array" and also the pixel locations.

In case of possible multiple matches:

  • if all the matches have the same score, minMaxLoc will return the first location found (searching direction from top to bottom and from left to right)
  • otherwise, it will return the location of the best score and if the others matches have the same score, the order will depend of their location in the image

If you want to order the matches, I think that you just have to test the coordinates manually.

edit flag offensive delete link more

Comments

please provide Python script

manoharsonwan gravatar imagemanoharsonwan ( 2018-12-29 05:31:39 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2015-04-22 05:32:10 -0600

Seen: 4,118 times

Last updated: Apr 22 '15