2016-11-26 112 views
1

我想只用一個模板來匹配多個對象的多個對象。 但問題是我的計劃是爲輸入圖像中evrey對象匹配多個次數。 我如何在輸入圖像中匹配多個對象和evrey對象一次?匹配使用OpenCV的

這是我的代碼

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

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

    while(true) 
    { 
    ///Localizing the best match with minMaxLoc 
    Core.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; 
    }  

     if(mmr.maxVal >=0.97) 
     { 
      ///Show me what you got 
      Imgproc.rectangle(img, matchLoc, 
       new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), 
       new Scalar(0,255,0),2); 
      //Imgproc.putText(img, "Edited by me", 
       // new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), 
       //Core.FONT_HERSHEY_PLAIN, 1.0 ,new Scalar(0,255,255)); 
      Imgproc.rectangle(result, matchLoc, 
       new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), 
       new Scalar(0,255,0),-1);     
     } 
     else 
     { 
      break; //No more results within tolerance, break search 
     } 
    } 

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

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

} 



public static void main(String[] args) { 
    System.loadLibrary("opencv_java310"); 
    run("test.jpg", "temp.png", "output.png", Imgproc.TM_CCOEFF_NORMED); 
} 

test.jpg放在

enter image description here temp.png

enter image description here

結果 enter image description here

+0

嘿,你有沒有發現這方面的任何解決方案? –

回答