在OpenCV中的findContours()中使用层次结构? [英] Using hierarchy in findContours () in OpenCV?

查看:993
本文介绍了在OpenCV中的findContours()中使用层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找到轮廓时,我使用了CV_RETR_CCOMP参数。这应该创建一个两级层次结构 - 第一级为外轮廓,第二级为孔的边界。但是,我从来没有使用过层次结构,所以我不熟悉这一点。

When finding contours, I used the CV_RETR_CCOMP argument. This is supposed to create a two level hierarchy - the the first level are for outer contours, the second level are for boundaries of the holes. However, I have never used a hierarchy before so I am not familiar with this.

有人可以告诉我如何访问洞的边界?我想忽略外轮廓,只画出孔边界。代码示例将不胜感激。我使用C ++接口不是C,所以请不要建议C函数(即使用findContours()而不是cvFindContours())。

Could someone instruct my on how to access the boundaries of the holes only? I want to disregard the outer contours and only draw the hole boundaries. Code examples will be appreciated. I am using the C++ interface not the C, so please don't suggest C functions (i.e. use findContours () instead of cvFindContours ()).

推荐答案

findContours 返回的层次结构具有以下形式:
hierarchy [idx] [{0,1,2 ,3}] = {下一个轮廓(相同级别),上一个轮廓(相同级别),子轮廓,父轮廓}

The hierarchy returned by findContours has the following form: 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:也就是说,每个元素都没有父元素

CV_RETR_CCOMP, returns a hierarchy of outer contours and holes. This means elements 2 and 3 of hierarchy[idx] have at most one of these not equal to -1: that is, each element has either no parent or child, or a parent but no child, or a child but no parent.

具有父项但没有子项的元素将是洞的边界。

An element with a parent but no child would be a boundary of a hole.

这意味着你基本上通过 hierarchy [idx] ,并绘制任何 hierarchy [idx] 3]> -1

That means you basically go through hierarchy[idx] and draw anything with hierarchy[idx][3]>-1.

有点像(在Python中有效,但没有测试C ++。 :

Something like (works in Python, but haven't tested the C++. Idea is fine though.):

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 );
        }
    }
}

这篇关于在OpenCV中的findContours()中使用层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆