【问题标题】:Template matching false positive模板匹配误报
【发布时间】:2017-01-07 07:28:31
【问题描述】:

我在 openCV java 上使用模板匹配来识别较大图像中是否存在子图像。只有在更大的图像中有确切的子图像时,我才想获得匹配的坐标。我正在使用这段代码,但得到了很多误报。附件是子图和大图。子图像不存在于较大的图像中,但我在 (873,715) larger image subimage 得到匹配

    public void run(String inFile, String templateFile, String outFile,
    int match_method) {
    System.out.println("Running Template Matching");

    Mat img = Imgcodecs.imread(inFile);
    Mat templ = Imgcodecs.imread(templateFile);

    // / Create the result matrix
    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);

    // / Do the Matching and Normalize
    Imgproc.matchTemplate(img, templ, result, match_method);
    // Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new
    // Mat());
    Imgproc.threshold(result, result, 0.1, 1.0, Imgproc.THRESH_TOZERO);
    // / Localizing the best match with minMaxLoc
    MinMaxLocResult mmr = Core.minMaxLoc(result);

    Point matchLoc;
    if (match_method == Imgproc.TM_SQDIFF
            || match_method == Imgproc.TM_SQDIFF_NORMED) {
        matchLoc = mmr.minLoc;
    } else {
        matchLoc = mmr.maxLoc;
    }
    double threashhold = 1.0;
    if (mmr.maxVal > threashhold) {
        System.out.println(matchLoc.x+" "+matchLoc.y);  
       Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
                matchLoc.y + templ.rows()), new Scalar(0, 255, 0));
    }
    // Save the visualized detection.
    Imgcodecs.imwrite(outFile, img);
}

【问题讨论】:

    标签: java opencv template-matching


    【解决方案1】:

    这是同一问题的答案:Determine if an image exists within a larger image, and if so, find it, using Python

    您必须将 python 代码转换为 Java

    【讨论】:

    • 谢谢它非常有帮助。!解决了我的问题。
    【解决方案2】:

    我不熟悉 Java 中的 OpenCV,但不熟悉 OpenCV C++。

    我不认为下面的代码是必要的。

    Imgproc.threshold(result, result, 0.1, 1.0, Imgproc.THRESH_TOZERO);
    

    如果您使用标准化选项,“Mat result”的最小/最大值将介于 -1 和 1 之间。因此,如果您使用规范化选项,您的以下代码将不起作用,因为您的阈值是 1.0。

    if (mmr.maxVal > threshold) 
    

    另外,如果你使用CV_TM_SQDIFF,上面的代码应该是

    if (mmr.minVal < threshold)
    

    具有适当的阈值。

    在将 minVal/maxVal 与阈值进行比较之前绘制 minMaxLoc 怎么样?看到它给出正确的结果?因为在 (873,715) 的匹配是荒谬的。

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 2021-08-24
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多