Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I was trying to find the presence of a particular pattern in an image. I used template matching using matchTemplate() function But even if no such pattern is there in the image false detections are coming out. Is there any way to filter out these false matches or is there any parameter that will tell us the percentage of correctness of the match found out
Posted

You want to play with the method parameter of matchTemplate. The various methods are the metric used for the comparison of your template with the image. Note that the methods that carry a "normed" in their name, express a similarity that is normalized for the maximum amount of change in your image and your template. If your template or your image or both have not many contrasts, the match will be kind of average, no matter where you place the template. In such case you receive more relevant results when using the non-normalized metrics.
 
Share this answer
 
v2
Comments
RupeshMote 28-Jun-14 6:37am    
Thanks
int MatchingMethod( int iMatchMethod, void* )
{
    cv::Mat ref = cv::imread("D:/Temp/InputImage.png");
    cv::Mat tpl = cv::imread("D:/Temp/TemplateImage.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.1, 1., CV_THRESH_TOZERO);

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

        if(maxval >= threshold)
        {
	    cout <<"\n Template Matches with input image\n";

            cv::rectangle(
                           ref, 
                           maxloc, 
                           cv::Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows), 
                           CV_RGB(0,255,0), 2
                         );
            cv::floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(.1), cv::Scalar(1.));
			break;
        }
        else
	{
	    cout << "\nTemplate does not match with input image\n";
            break;
	}
    }
	
    cv::imshow("reference", ref);
    cv::waitKey();
    ref.release();
    tpl.release();
    return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900