[英]trouble with findContours and hierarchy (tell if a contour is a hole or not)
我們有多個輪廓。 有些是積極的,有些是消極的(孔)。 這是我正在使用的代碼
def get_corners(grid: np.ndarray, show=False):
corners = set()
hole_corners = set()
# Filter using contour hierarchy
cnts, hierarchy = cv.findContours(grid, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)[-2:]
hierarchy = hierarchy[0]
for component in zip(cnts, hierarchy):
currentContour = component[0]
currentHierarchy = component[1]
# x,y,w,h = cv.boundingRect(currentContour)
# Has hole which means it is IN
if currentHierarchy[2] < 0:
for corner in currentContour[:, 0, :]:
corner_coords = tuple(corner.tolist())
hole_corners.add(corner_coords)
# cv.putText(image, 'IN', (x,y-10), cv.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)
# No child which means it is OUT
elif currentHierarchy[3] < 0:
for corner in currentContour[:, 0, :]:
corner_coords = tuple(corner.tolist())
corners.add(corner_coords)
它的問題是,當有多個正輪廓時,它不會按預期工作。 每個大於 1 的正輪廓都算作一個洞。 這是顯示的。
如您所見,它沒有按預期工作。
都算坑
一個計數正確,rest 大多不正確
帶有正確標記的輪廓的圖像(此處忽略角顏色)
hierarchy for this: [[ 1 -1 -1 -1]
[ 3 0 2 -1]
[-1 -1 -1 1]
[-1 1 -1 -1]]
弄清楚了。 使用 RETR_CCOMP 並檢查 currentHierarchy[3] 對我有用。 Corners 是一個包含所有外輪廓角的集合,hole_corners 是一個包含所有內角或孔輪廓的集合。
(cnts, hierarchy) = cv.findContours(grid,mode=cv.RETR_CCOMP, method=cv.CHAIN_APPROX_TC89_KCOS)
corners = set()
hole_corners = set()
# Filter using contour hierarchy
hierarchy = hierarchy[0]
for component in zip(cnts, hierarchy):
currentContour = component[0]
currentHierarchy = component[1]
# Has inner contours which means it is IN
if currentHierarchy[3] < 0:
for corner in currentContour[:, 0, :]:
corner_coords = tuple(corner.tolist())
corners.add(corner_coords)
# No child which means it is OUT
elif currentHierarchy[3] >= 0:
for corner in currentContour[:, 0, :]:
corner_coords = tuple(corner.tolist())
hole_corners.add(corner_coords)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.