首页 文章

matchTemplate与java中的openCV

提问于
浏览
2

我有这样的代码:

Mat img = Highgui.imread(inFile);
Mat templ = Highgui.imread(templateFile);
int result_cols = img.cols() - templ.cols() + 1;
int result_rows = img.rows() - templ.rows() + 1;
Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);
Imgproc.matchTemplate(img, templ, result, Imgproc.TM_CCOEFF);
/////Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
for (int i = 0; i < result_rows; i++)
for (int j = 0; j < result_cols; j++) 
  if(result.get(i, j)[0]>?)

     //match!

我需要解析输入图像以找到模板图像的多个副本 . 我希望得到这样的结果:

result[0][0]= 15%
result[0][1]= 17%
result[x][y]= 47%

如果我使用TM_COEFF,所有结果都是[-xxxxxxxx.xxx,xxxxxxxx.xxx]

如果我使用TM_SQDIFF,则所有结果都是xxxxxxxx.xxx

如果我使用TM_CCORR,则所有结果都是xxxxxxxx.xxx

如何检测匹配或不匹配? if的正确条件是什么?如果我对矩阵进行了规范化,则应用程序将值设置为1,并且我无法检测模板是否未存储到图像中(所有不匹配) .

提前致谢

2 回答

  • 3

    您可以将“_NORMED”附加到方法名称(例如:C中的CV_TM_COEFF_NORMED;在Java中可能略有不同),以便为您的目的获得合理的值 .

    通过'明智',我的意思是你会得到0到1范围内的值,可以乘以100来达到你的目的 .

    注意:对于CV_TM_SQDIFF_NORMED,它将在-1到0的范围内,您必须从1中减去该值才能理解它,因为如果在此方法中使用该值,则为最小值 .

    Tip :您可以使用等效的minMaxLoc()来获取最小值和最大值 . 它's very useful when used in conjunction with matchtemplate. I believe ' minMaxLoc'位于类Core内 .

    这是一个C实现:

    matchTemplate( input_mat, template_mat, result_mat, method_NORMED );
    
    double minVal, maxVal; 
    
    double percentage;
    
    Point minLoc; Point maxLoc;
    
    minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
    if( method_NORMED == CV_TM_SQDIFF_NORMED )
    {
       percentage=1-minVal;
    }
    else
    {
       percentage=maxVal;
    }
    

    有用的C文档:匹配模板描述以及可用方法:http://docs.opencv.org/modules/imgproc/doc/object_detection.html MinMaxLoc文档:http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=minmaxloc#minmaxloc

  • 1

    另一种方法是背景差分 . 你可以观察失真 .

    import org.opencv.core.Core;
    import org.opencv.core.Mat;
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    
    public class BackgroundDifference {
        public static void main(String[] arg){
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
            Mat model = Highgui.imread("e:\\answers\\template.jpg",Highgui.CV_LOAD_IMAGE_GRAYSCALE);
            Mat scene = Highgui.imread("e:\\answers\\front7.jpg",Highgui.CV_LOAD_IMAGE_GRAYSCALE);
            Mat diff = new Mat();
            Core.absdiff(model,scene,diff);
            Imgproc.threshold(diff,diff,15,255,Imgproc.THRESH_BINARY);
            int distortion = Core.countNonZero(diff);
            System.out.println("distortion:"+distortion);
            Highgui.imwrite("e:\\answers\\diff.jpg",diff);
        }
    }
    

    enter image description here

    enter image description here

    enter image description here

相关问题