1

如何使用单个模板匹配多个对象?
我想通过阈值匹配多个对象。

当我匹配一个对象时,我使用了这个代码。

System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat img = Highgui.imread("/test/test_img.jpg");//input image
if(img.empty())
throw new Exception("no image");
Mat tpl = Highgui.imread("/test/test_tpl.jpg");//template image
if(tpl.empty())
throw new Exception("no template");
Mat result = new Mat();
Imgproc.matchTemplate(img, tpl,result,Imgproc.TM_CCOEFF_NORMED);//Template Matching
Core.MinMaxLocResult maxr = Core.minMaxLoc(result);
Point maxp = maxr.maxLoc;
Point maxop = new Point(maxp.x + tpl.width(), maxp.y + tpl.height());
Mat dst = img.clone();
Core.rectangle(dst, maxp, maxop, new Scalar(255,0,0), 2);//draw a rectangle                                 
Highgui.imwrite("/test/test.jpg", dst);//save image
4

1 回答 1

2

这个对我有用:

    Mat img = Highgui.imread("/test/test_img.jpg");//input image
    if(img.empty())
    throw new Exception("no image");
    Mat tpl = Highgui.imread("/test/test_tpl.jpg");//template image
    if(tpl.empty())
    throw new Exception("no template");
    Mat result = new Mat();
    Imgproc.matchTemplate(img, tpl,result,Imgproc.TM_CCOEFF_NORMED);//Template Matching
    Imgproc.threshold(result, result, 0.1, 1, Imgproc.THRESH_TOZERO);  
    double threshold = 0.95;
    double maxval;
    Mat dst;
    while(true) 
    {
        Core.MinMaxLocResult maxr = Core.minMaxLoc(result);
        Point maxp = maxr.maxLoc;
        maxval = maxr.maxVal;
        Point maxop = new Point(maxp.x + tpl.width(), maxp.y + tpl.height());
        dst = img.clone();
        if(maxval >= threshold)
        {
            System.out.println("Template Matches with input image");

            Core.rectangle(img, maxp, new Point(maxp.x + tpl.cols(),
                    maxp.y + tpl.rows()), new Scalar(0, 255, 0),5);
            Core.rectangle(result, maxp, new Point(maxp.x + tpl.cols(),
                    maxp.y + tpl.rows()), new Scalar(0, 255, 0),-1);
        }else{
            break;
        }
    }
    Highgui.imwrite("test.jpg", dst);//save image

例如

模板: 硬币

结果: marioWorld

于 2016-08-10T10:49:52.473 回答