减少opencv中模板匹配的错误检测 [英] Reduce false detection of template matching in opencv

查看:796
本文介绍了减少opencv中模板匹配的错误检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在图像中找到特定图案的存在。我使用matchTemplate()函数进行模板匹配但是即使图像中没有这样的模式,也会出现错误的检测。有没有办法过滤掉这些错误的匹配,或者是否有任何参数可以告诉我们找到的匹配正确性的百分比

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

推荐答案

你想要玩matchTemplate的方法参数。各种方法是用于比较模板和图像的度量标准。请注意,在其名称中带有normed的方法表示相似度,该相似度针对图像和模板中的最大变化量进行了标准化。如果您的模板或图片或两者没有太多对比,则无论您在何处放置模板,匹配都将是平均值。在这种情况下,使用非规范化指标时会收到更多相关结果。
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.


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;
}


这篇关于减少opencv中模板匹配的错误检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆