Opencv for android 模板匹配

因为有这方面的需要所以,对模板查找搜寻了相关资料,只是对于算法的东西很难看得动,特别是opencv涉及的很多的数学方法。

所以只为了实现这个功能,因为需求比较简单,在网上也搜寻到了相关代码,就直接拿来用了,这里也相当于转载一下:

代码上,亲测可以用的,效果也不错,确实将嘴巴给找出来了。

原文:http://www.itstrike.cn/Question/645ffff0-2862-46b6-a421-b76a37dfc660.html

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

        Mat img = Highgui.imread(inFile);
        Mat templ = Highgui.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());

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

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

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

    }
}

public class TemplateMatching {
    public static void main(String[] args) {
        System.loadLibrary("opencv_java246");
        new MatchingDemo().run(args[0], args[1], args[2], Imgproc.TM_CCOEFF);
    }
}

  目标图像:

模板图像:

查找后图像:

posted @ 2015-10-08 17:59  草人木  阅读(3035)  评论(0编辑  收藏  举报