def find_contours(mask, smooth_factor=0.005):
""" Find the contours in a given mask """
border = 5
# Canny detection breaks down with the edge of the image
my_mask = cv2.copyMakeBorder(mask, border, border, border, border,
cv2.BORDER_CONSTANT, value=(0, 0, 0))
my_mask = cv2.cvtColor(my_mask, cv2.COLOR_BGR2GRAY)
if is_cv2():
contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
else:
_, contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# shift the contours back down
for contour in contours:
for pnt in contour:
if pnt[0][1] > border:
pnt[0][1] = pnt[0][1] - border
else:
pnt[0][1] = 0
if pnt[0][0] > border:
pnt[0][0] = pnt[0][0] - border
else:
pnt[0][0] = 0
closed_contours = []
for contour in contours:
epsilon = smooth_factor*cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
area = cv2.contourArea(approx)
# if they are too small they are not edges
if area < 200:
continue
closed_contours.append(approx)
return closed_contours
评论列表
文章目录