OpenCV层次结构始终为空

问题描述 投票:0回答:2

我有一个轮廓重叠的图像,当我找到轮廓时,我一直在尝试使用层次结构过滤轮廓。我想做的是滤除父母不等于-1的轮廓。但是,当我尝试获取包含层次结构的信息时,父索引几乎每次都等于null。我不是在寻找正确的信息来获取当前轮廓父级的状态吗?这是我的代码。

List<MatOfPoint> contours = new ArrayList<>();
    List<MatOfPoint> squareContours = new ArrayList<>();
    Mat hierarchy = new Mat();
    //find all contours
    Imgproc.findContours(dilated, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

    //Remove contours that aren't close to a square shape.
    for(int i = 0; i < contours.size(); i++){
        if(hierarchy != null){
            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);

            if(squareness >= 0.7 && squareness <= 0.9 && area >= 2000){
                squareContours.add(contours.get(i));
            }
        }
    }
    //remove contour if it has a parent 
    List<MatOfPoint> finalContours = new ArrayList<>();
    for(int i = 0; i < squareContours.size();i++){
        if(hierarchy.get(i, 3)[3] == -1){ //this should be checking parent index I think.
            finalContours.add(squareContours.get(i));
        }
    }

这是当我打印包含父信息Arrays.toString(hierarchy.get(i,3)))的层次结构矩阵时程序的输出>

[-1.0, -1.0, -1.0, 2.0]
null
null
null
null
null
null
null
null
null
null

我有一个轮廓重叠的图像,当我找到轮廓时,我一直在尝试使用层次结构过滤轮廓。我想做的是滤除父母不相等的轮廓...

java opencv hierarchy
2个回答
3
投票

[当您使用Mat表示findContours返回的层次结构时,将得到一个包含以下内容的数组:


0
投票

当您从网络列表中删除项目时,还需要检查已删除项目的关系。我首先像这样将完整的层次结构Mat传输到List:

© www.soinside.com 2019 - 2024. All rights reserved.