2016-04-02 72 views
0

這裏是我的代碼:凸包返回java.lang.IndexOutOfBoundsException OpenCV的機器人

public void findHull(){ 
    int h = 0; 
    double area_Hull = 0; 
    hullArea = 0; 
    List<MatOfInt> hull = new ArrayList<MatOfInt>(); 
    hull.add(new MatOfInt()); 

    Imgproc.convexHull(contours2.get(largest_contour_index), hull.get(largest_contour_index)); 

    Point[] points = new Point[hull.get(largest_contour_index).rows()]; 

    for(h=0; h < hull.get(largest_contour_index).rows(); h++) { 
     int index = (int)hull.get(largest_contour_index).get(h, 0)[0]; 
     points[h] = new Point(contours2.get(largest_contour_index).get(index, 0)[0],contours2.get(largest_contour_index).get(index, 0)[1]); 
    } 
    List<Point[]> hullpoints = new ArrayList<Point[]>(); 
    hullpoints.add(points); 

    noOfDent = h; 

    List<MatOfPoint> hullmop = new ArrayList<MatOfPoint>(); 

    MatOfPoint mop = new MatOfPoint(); 
    mop.fromArray(hullpoints.get(0)); 
    hullmop.add(mop); 

    area_Hull = Imgproc.contourArea(hullmop.get(0)); 

    hullArea = area_Hull; 
    MatOfPoint2f Hullpt = new MatOfPoint2f(); 
    hullmop.get(0).convertTo(Hullpt, CvType.CV_32FC2); 
    hullPerimeter=Imgproc.arcLength(Hullpt, false); 
} 

contours2是這是以前檢索使用findcontours.And largest_contour_index是最大的輪廓的索引圖像中的所有輪廓。但我收到一個異常錯誤:

Imgproc.convexHull(contours2.get(largest_contour_index), hull.get(largest_contour_index)); 

你能告訴問題出在哪?

預先感謝您的幫助

+1

我建議你調試它以查看每個集合的大小:'contours2'和'hull'。因爲其中一個或其他(甚至兩個)沒有'largest_contour_index'元素。 – aribeiro

+0

我發現錯誤,我只向船體添加一個值,並且當我使用largest_contour_index時,它不指向任何東西。我的壞,愚蠢的錯誤 – adams

回答

0

因爲你hull收藏有1個元素上初始化索引0 (new MatOfInt()),和ArrayList的其餘持有空引用。 Imgproc.convexHull方法試圖轉換您的輪廓(MatOfPoint)元素爲一個船體(MatOfInt),但爲了做到這一點,它需要進行初始化。具體來說,當你打電話給hull.get(largest_contour_index)時,它會得到一個空引用,除非你的largest_contour_index是0.

編輯:啊我看你回答了你自己的問題。 Nevermind then