如评论中所述,您需要使用cv2.RETR_CCOMP
。以下是Python的实现:
img = cv2.imread(os.path.join(r'C:\Users\Jackson\Desktop\stack\contour', FILE_NAME))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Don't use magic numbers
thresh = cv2.threshold(gray, thresh=BLACK_THRESHOLD, maxval=255, type=cv2.THRESH_BINARY)[1]
#--- Find the contours ---
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
#--- get hierarchy descriptions ---
print(hierarchy)
返回:
[[-1 -1 1 -1]
[-1 -1 -1 0]]
这是什么意思?
层次结构有助于在轮廓之间建立父子关系。 子轮廓是指在称为父级的外部轮廓内的轮廓。
层次结构返回一个具有以下含义的数组:
[下一个,上一个,第一个子元素,父级]
这份文档对这个主题进行了详细介绍。
#--- creating a copy of original image ---
img2 = img.copy()
#--- checking whether the contour in hierarchy is a child and if it is then draw it ---
for i in hierarchy:
print(i)
if i[2] > 0:
cv2.drawContours(img2, [contours[i[2]]], 0, (0,255,0), 2)
cv2.imshow('img2', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
CV_RETR_CCOMP
标志,它应该会给你一个2级层次列表,一个是外部的,另一个是“孔洞”的。 - api55