【问题标题】:How can I get rid of internal contours? python我怎样才能摆脱内部轮廓? Python
【发布时间】:2018-07-12 07:06:30
【问题描述】:

我正在使用 cv2.findContours 定位卫星照片中的光污染区域。它们中的许多内部并没有完全污染,我的意思是它们内部有黑洞,它们不应该被视为轮廓的一部分,也不是单独的轮廓,因为我只是在描绘光污染区域。当我开始按大小索引轮廓时,我注意到黑洞被视为单独的轮廓。

处理后的图像

如您所见,例如 #0、#67 和 #64 被归类为轮廓区域,即使它们不应该是

找到我正在使用的轮廓

# Reading image
image_orig = cv2.imread("india_night.jpg")
# Processing to make contours smoother
image_gray = cv2.cvtColor(image_orig, cv2.COLOR_BGR2GRAY)
image_blurred = cv2.GaussianBlur(image_gray, (5, 5), 0)
image_blurred = cv2.dilate(image_blurred, None)
_, image_threshold = cv2.threshold(image_blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#sorting contours by size
_, contours, _ = cv2.findContours(image_threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contours = sorted(contours, key=cv2.contourArea)

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

【问题讨论】:

    标签: opencv find contour area


    【解决方案1】:

    我相信您可以通过查看层次结构来做到这一点。基本上,如果您传递 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))
    

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

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

    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 以更好地了解其工作原理

    【讨论】:

    • 但是如果我需要外部区域的平均亮度怎么办?这种方式看起来会给我外部区域+内部区域的平均亮度
    • @Krulg 我也更新了我的答案来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2021-01-27
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2022-12-18
    相关资源
    最近更新 更多