使用层次结构删除不需要的轮廓

时间:2017-08-16 15:59:28

标签: java c++ opencv contour

我的问题是如何像在Java中使用C ++一样访问父值。在C ++中,我得到了矩阵的索引。在我的C ++中,我if(hierarchy[i][4] == -1)检查父值。当我尝试在Java hierarchy[i][4]中这样做时,是一个双数组。就像[2.0,1.3, 3.1, 0.5]一样,如何在Java中访问矩阵的double数组的最后一个索引?

C ++ 中查找轮廓和检查层次结构将是这样的

findContours( image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE );
// loop through the contours/hierarchy
    for ( int i=0; i<contours.size(); i++ ) {
        // look for hierarchy[i][3]!=-1, look at hierarchy index.
        if ( hierarchy[i][4] == -1 ) {
            //once this is true you can do whatever 
            Scalar colour( (rand()&255), (rand()&255), (rand()&255) );
            drawContours( outImage, contours, i, colour );
        }
    }
}

以下是我的 Java 等效内容

//define hierarchy
Mat hierarchy = new Mat();
//find contours
Imgproc.findContours(dilated, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_NONE);
double[] whatParentShouldBe = {-1.0}; //This doesn't do what I want it to.

//Remove iterate through contours 
for(int i = 0; i < contours.size(); i++){

    double area = Imgproc.contourArea(contours.get(i)); 
    MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(i).toArray());

    double perimeter = Imgproc.arcLength(contour2f, true);
    //Found squareness equation on wiki... 
    //https://en.wikipedia.org/wiki/Shape_factor_(image_analysis_and_microscopy)
    double squareness = 4 * Math.PI * area / Math.pow(perimeter, 2);

    System.out.println("4:" + Arrays.toString(hierarchy.get(i, 4)));
    //This prints out something like [3.0,2.1,1.9,-1]    
    //I want to get the last index and of it see if it is -1 like the C++ example
    //Instead what it turns out I am doing is 'if [3.0,2.1,1.9,-1] == [-1.0]

    //add contour to new List if it has a square shape and no parent contours
    if(squareness >= 0.7 && squareness <= 0.9 && area >= 2000 && hierarchy.get(i, 4) == whatParentShouldBe){
       squareContours.add(contours.get(i));
    }
}

0 个答案:

没有答案