def get_largest(im, n):
# Find contours of the shape
major = cv2.__version__.split('.')[0]
if major == '3':
_, contours, _ = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
else:
contours, _ = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Cycle through contours and add area to array
areas = []
for c in contours:
areas.append(cv2.contourArea(c))
# Sort array of areas by size
sorted_areas = sorted(zip(areas, contours), key=lambda x: x[0], reverse=True)
if sorted_areas and len(sorted_areas) >= n:
# Find nth largest using data[n-1][1]
return sorted_areas[n - 1][1]
else:
return None
评论列表
文章目录