java - 使用 OpenCV 匹配多个对象

标签 java opencv template-matching

我正在尝试仅使用一个模板来匹配多个对象。 但问题是我的程序正在匹配输入图像中每个对象的多次出现。 如何在输入图像中仅匹配一次多个对象和每个对象?

这是我的代码

public void run(String inFile, String templateFile, String outFile, int match_method) {
    System.out.println("\nRunning 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());

    while(true)
    {
    // / Localizing the best match with minMaxLoc
    Core.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;
    }      

        if(mmr.maxVal >=0.97)
         {
            // / Show me what you got
            Imgproc.rectangle(img, matchLoc, 
                new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), 
                new    Scalar(0,255,0),2);
            //Imgproc.putText(img, "Edited by me",
              //  new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()),
                //Core.FONT_HERSHEY_PLAIN, 1.0 ,new  Scalar(0,255,255));
            Imgproc.rectangle(result, matchLoc, 
                new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), 
                new    Scalar(0,255,0),-1);                 
         }
         else
         {
             break; //No more results within tolerance, break search
         }
    }

    // / Show me what you got
    //Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(), 
    //matchLoc.y + templ.rows()), new Scalar(0, 255, 0),2);

    // Save the visualized detection.
    System.out.println("Writing "+ outFile);
    Imgcodecs.imwrite(outFile, img);

}



public static void main(String[] args) {
    System.loadLibrary("opencv_java310");
    run("test.jpg", "temp.png",  "output.png", Imgproc.TM_CCOEFF_NORMED);
}

测试.jpg

enter image description here temp.png

enter image description here

结果 enter image description here

最佳答案

您需要非最大抑制步骤。

是这样的:NMS for python 1或更快的版本 NMS for python 2 .

关于java - 使用 OpenCV 匹配多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40817802/

相关文章:

java - Hibernate Custom 查询可以返回 Map 而不是 List 吗?

java - 在 Java 中查找 List 中具有重复项的唯一元素

python-3.x - 如何在图像中找到对象的方向?

opencv - Emgu Cv MatchTemplate可在C#中处理数百万个图像?

java - 如何在这样的 java 静态方法中实例化 BigInteger?

java - 确定悬停在哪个形状上 - Java

java - 如何在Android中使用Opencv在图像上有效应用Canny边缘检测器?

python-3.x - 没有名为 cy_yolo_findboxes 的模块

匹配两个矩形的位置和大小的算法

python - 多尺度模板匹配不正确