据我所知,你试图区分外部轮廓和内部轮廓.要确定哪些轮廓在内外,只需使用轮廓层次来区分两者.具体来说,当使用cv2.findContours
时,可以使用cv2.RETR_TREE
来提取外部或内部轮廓.完整解释见understanding contour hierarchies: how to distinguish between contours.从我们给出的完整拓Flutter 图中,我们可以过滤出轮廓,其 idea 是,如果父轮廓有内部轮廓,这意味着它是OUT
轮廓,内部的子轮廓是IN
轮廓.另一种情况是,如果一个轮廓没有内部子对象,那么我们知道它是一个IN
轮廓.
以下是一个例子:
输入图像
后果
密码
import cv2
# Load image, grayscale, Otsu's threshold
image = cv2.imread('2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Filter using contour hierarchy
cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
hierarchy = hierarchy[0]
for component in zip(cnts, hierarchy):
currentContour = component[0]
currentHierarchy = component[1]
x,y,w,h = cv2.boundingRect(currentContour)
# Has inner contours which means it is IN
if currentHierarchy[2] < 0:
cv2.putText(image, 'IN', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)
# No child which means it is OUT
elif currentHierarchy[3] < 0:
cv2.putText(image, 'OUT', (x,y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)
cv2.imshow('image', image)
cv2.waitKey()