簡體   English   中英

在OpenCV中的findContours()中使用層次結構?

[英]Using hierarchy in findContours () in OpenCV?

找到輪廓時,我使用了CV_RETR_CCOMP參數。 這應該創建一個兩級層次結構 - 第一個級別用於外部輪廓,第二個級別用於孔的邊界。 但是,我之前從未使用過層次結構,因此我對此並不熟悉。

有人可以指導我如何訪問洞的邊界嗎? 我想忽略外部輪廓,只繪制孔邊界。 代碼示例將不勝感激。 我使用的是C ++接口而不是C,所以請不要建議C函數(即使用findContours()而不是cvFindContours())。

findContours返回的層次結構具有以下形式: hierarchy[idx][{0,1,2,3}]={next contour (same level), previous contour (same level), child contour, parent contour}

CV_RETR_CCOMP返回外輪廓和孔的層次結構。 這意味着hierarchy[idx]元素2和3最多只有一個不等於-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 );
        }
    }
}

AFAIK使用CV_RETR_CCOMP時,所有的孔都在同一級別。

int firstHoleIndex = hierarchy[0][2];
for (int i = firstHoleIndex; i >= 0 ; i = hierarchy[i][0])
// contours.at(i) is a hole. Do something with it.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM