如何摆脱内部轮廓?蟒蛇

时间:2018-02-01 20:51:32

标签: opencv find contour area

我使用cv2.findContours定位来自卫星的照片中的轻度污染区域。它们中的许多都不完全是内部污染,我的意思是它们内部有黑洞,不应该被认为是轮廓的一部分,也不能分开轮廓,因为我只是塑造了轻度污染区域。当我开始按尺寸索引轮廓时,我注意到黑洞被视为单独的轮廓。

已处理的图片 image description

正如您所看到的,例如#0,#67和#64被归类为轮廓区域,即使它们不应该

使用

查找我的轮廓
public void IsMobileBrowser()
{
    String labelText = "";
    System.Web.HttpBrowserCapabilities myBrowserCaps = Request.Browser;
    if (((System.Web.Configuration.HttpCapabilitiesBase)myBrowserCaps).IsMobileDevice)
    {
        labelText = "Browser is a mobile device.";
    }
    else
    {
        labelText = "Browser is not a mobile device.";
    }
    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('"+ labelText + "');", true);
}

我的目标是不将这些未受污染的区域归类为污染区域

1 个答案:

答案 0 :(得分:2)

我相信你可以通过查看层次结构来做到这一点。基本上,如果你传递cv2.RETR_TREE而不是-1的层次结构意味着这个轮廓在另一个内部

_, contours, hierarchy  = cv2.findContours(image_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for i in range(len(contours)):
    if hierarchy[0,i,3] == -1:
        cv2.drawContours(image_orig, contours, i, (0, 255, 0))

这将导致仅绘制外部轮廓,如下图所示 enter image description here

编辑: 那么如果您需要排除形状的内部部分该怎么办呢?现在这不是最优化的解决方案,但我认为它可以让您很好地了解层次结构的工作原理:

enter image description here

for i in range(len(contours)):
    if hierarchy[0, i, 3] == -1:    # this is the outer contour which we need to draw
        cv2.drawContours(image_orig, contours, i, (0, 255, 0), -1)
        if hierarchy[0, i, 2] != -1:    # if this contour has inner contours
            childrenIndex = hierarchy[0, i, 2]
            while hierarchy[0, childrenIndex, 0] != -1:  # get all children for the outer contour
                childrenIndex = hierarchy[0, childrenIndex, 0]
                # now the first inner contour is just near the outer one (from the opposite side of the line)
                # thats why we are drawing that inner contour's children
                if hierarchy[0, childrenIndex, 2] != -1:
                    cv2.drawContours(image_orig, contours, hierarchy[0, childrenIndex, 2], (0, 0, 255), -1)

您还可以阅读opencv hierarchy tutorial以更好地了解其工作原理

相关问题