2013-11-25 70 views
0

如何使用單個模板匹配多個對象?
我想通過閾值匹配多個對象。如何匹配多個對象

當我匹配單個對象時,我使用了這段代碼。

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 
+0

閾值'result'。找到輪廓。爲了獲得更好的結果,應用非最大值抑制。 – William

+0

@威廉謝謝你的建議。 – Laura

回答

0

這一個是爲我工作:

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 

例如

模板: coin

和結果: marioWorld