1

How do i match multiple objects using a single template?
i want to match multiple objects by threshold value.

When i matched a single object, i used this code.

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

1 Answers1

2

This one is working for me:

    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

for example

the template: coin

and the result: marioWorld

Tom
  • 21
  • 4