OpenCV模板将多个出现与容差匹配

时间:2019-01-09 16:17:45

标签: java opencv template-matching

大图景是超级马里奥; Big Picture 模板是金; Template

当我运行程序时,返回此内容; Result

我设置了阈值,但是模板匹配了主画面中的所有内容。所以我真的不理解阈值或匹配机制,或者代码中没有逻辑错误。

代码为;

package matchtemplatedemo_1;

import org.opencv.core.Core;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class MatchTemplateDemo_1 {

    public static void main(String[] args) {

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat img = Imgcodecs.imread("C:/Users/Lacrymae/Desktop/bigpicture.png");
        Mat templ = Imgcodecs.imread("C:/Users/Lacrymae/Desktop/template.png");
        String outFile = "C:/Users/Lacrymae/Desktop/result.png";

        // 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 Normalize and Perform the template matching operation
        Imgproc.matchTemplate(img, templ, result, 1);
        // Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
        Imgproc.threshold(result, result,0.8,1,Imgproc.THRESH_TOZERO); 

        // Localizing the best match with minMaxLoc. We localize the minimum and maximum values in the result matrix R by using minMaxLoc.
        Point matchLoc;
        Point maxLoc;
        Point minLoc;

        MinMaxLocResult mmr;


        while(true)
        {
            mmr = Core.minMaxLoc(result);
            matchLoc = mmr.maxLoc;
            if(mmr.maxVal >=0.9)
            {
                Imgproc.rectangle(img, matchLoc, 
                    new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), 
                    new    Scalar(0,255,0));
                Imgproc.rectangle(result, matchLoc, 
                    new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), 
                    new    Scalar(0,255,0),-1);
                //break;
            }
            else
            {
                break; //No more results within tolerance, break search

            }
        }

        Imgcodecs.imwrite(outFile, img);

    }

}

编辑:

我改变了

Imgproc.matchTemplate(img, templ, result, 1);

Imgproc.matchTemplate(img, templ, result, 3);

Imgproc.threshold(result, result,0.8,1,Imgproc.THRESH_TOZERO);

Imgproc.threshold(result, result,0.98,1,Imgproc.THRESH_TOZERO);

完美标记所有金币。

0 个答案:

没有答案