【问题标题】:Only find contour without child只找到没有孩子的轮廓
【发布时间】:2019-02-23 03:22:07
【问题描述】:

早安,

我在图像上使用了 cv2.findContours。之后,我提取了轮廓和层次信息。从那里,我如何过滤和仅绘制没有子级的轮廓(据我了解,在层次结构数组的第 3 列中的值为 -1)?

下面是我的代码:my image

from imutils import perspective
from imutils import contours
import numpy as np
import imutils
import cv2

img = cv2.imread('TESTING.png') 
imgs = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edged = imgs

cnts = cv2.findContours(edged,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = cnts[2]
ChildContour = hierarchy [0, :,2]
WithoutChildContour = (ChildContour==-1).nonzero()[0]

cntsA = cnts[0] if imutils.is_cv2() else cnts[1]
if not cntsA:
    print ("no contours")



(cntsB, _) = contours.sort_contours(cntsA)

orig = cv2.imread('TESTING.png')
for c in cntsB:


    if cv2.contourArea(c) < 100: 
        continue

    box = cv2.minAreaRect(c)
    box = cv2.boxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
    box = np.array(box, dtype="int")
    box = perspective.order_points(box)
    cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)

screen_res = 972, 648
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Image', window_width, window_height)

cv2.imshow("Image", orig)
cv2.waitKey(0)       
cv2.destroyAllWindows()

【问题讨论】:

  • “没有孩子”是指排除内部轮廓,对吧?
  • 没有子级意味着轮廓下没有任何子级(或最内层轮廓)

标签: python opencv opencv-contour


【解决方案1】:

findContours 返回的hierarchy 有四列:[Next, Previous, First_Child, Parent]。正如您所指出的,我们对索引 2 即 First_Child 感兴趣。要过滤和仅绘制没有子项的轮廓,您可以循环 WithoutChildContour 中存在的索引。

cntsA=[ cntsA[i] for i in WithoutChildContour]

这是对应的sn-p:

注意:从opencv 4.0开始,findContours只返回2个值(cnts和hierarchy)。

# ...
hierarchy = cnts[1] #changed index
ChildContour = hierarchy [0, :,2]
WithoutChildContour = (ChildContour==-1).nonzero()[0]

cntsA = cnts[0]
# get contours from indices
cntsA=[ cntsA[i] for i in WithoutChildContour]
# ...

在您的示例图像上运行:

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 2011-11-27
    相关资源
    最近更新 更多