在Java OpenCV中,Imgproc.findContours函数可以用来提取二值图形的轮廓线,其用法大多数博客都有讲解,但是唯独没有介绍如何获取这些轮廓线的等级。
参数hierarchy的类型为Mat,使用System.out.println(hierarchy)打印,其值为:Mat [ 1*7*CV_32SC4, isCont=true, isSubmat=false, nativeObj=0x131ce00, dataAddr=0x1319280 ],但是还是不知道里面的轮廓等级关系;
不慌,使用如下代码可以打印出hierarchy存储的值,其中
sImage为一幅Mat类型二值图像;
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat(); Imgproc.findContours(sImage, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_NONE);int[] current_hierarchy = new int[4];
for (int i = 0; i < contours.size(); i++) {
System.out.print(i);
System.out.print(" : ");
System.out.println(contours.get(i).size().height);
System.out.println(contours.get(i));
hierarchy.get(0, i, current_hierarchy);
System.out.print(current_hierarchy[0]);
System.out.print(", ");
System.out.print(current_hierarchy[1]);
System.out.print(", ");
System.out.print(current_hierarchy[2]);
System.out.print(", ");
System.out.println(current_hierarchy[3]);
}
hierarchy :4通道矩阵,元素个数为轮廓数量。通道【0】~ 通道【3】对应保存:后一个轮廓下标,前一个轮廓下标,父轮廓下标,内嵌轮廓下标。如果没有后一个,前一个,父轮廓,内嵌轮廓,那么该通道的值为 -1。
本例中总共提取到7条轮廓线,每条轮廓线的等级关系如下:
0 : 1, -1, -1, -1
1 : 3, 0, 2, -1
2 : -1, -1, -1, 1
3 : -1, 1, 4, -1
4 : 5, -1, -1, 3
5 : 6, 4, -1, 3
6 : -1, 5, -1, 3