返回的层次结构findContours
具有以下形式:hierarchy[idx][{0,1,2,3}]={next contour (same level), previous contour (same level), child contour, parent contour}
CV_RETR_CCOMP
,返回外部轮廓和孔的层次结构。
这意味着元素 2 和 3hierarchy[idx]
其中最多有一个不等于 -1:也就是说,每个元素要么没有父元素,要么没有子元素,或者有父元素但没有子元素,或者有子元素但没有父元素。
具有父元素但没有子元素的元素将是孔的边界。
这意味着你基本上会经历hierarchy[idx]
并绘制任何东西hierarchy[idx][3]>-1
.
类似的东西(在Python中工作,但还没有测试C++。不过想法很好。):
findContours( image, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
if ( !contours.empty() && !hierarchy.empty() ) {
// loop through the contours/hierarchy
for ( int i=0; i<contours.size(); i++ ) {
// look for hierarchy[i][3]!=-1, ie hole boundaries
if ( hierarchy[i][3] != -1 ) {
// random colour
Scalar colour( (rand()&255), (rand()&255), (rand()&255) );
drawContours( outImage, contours, i, colour );
}
}
}