- import cv2
- def do_contours(filename):
- colors = [(0,0,255), (0,255,0), (255,0,0),
- (255,255,0), (255,0,255), (0,255,255),
- (0,0,128), (0,128,0), (128,0,0),
- (128,128,0), (0,128,128), (128,0,128),
- (255,255,255)]
- image = cv2.imread(filename)
- image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
- ret, image_thresh = cv2.threshold(image_gray, 127, 255, 0)
- contours, hierarchy = \
- cv2.findContours(image_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
- areas = [(i, cv2.contourArea(contours[i])) for i in range(len(contours))]
- areas.sort(key=lambda x: x[1])
- areas.reverse()
- minArea = 50
- result = []
- print(hierarchy)
- for area_entry in areas:
- if area_entry[1] < minArea:
- break
- temp = index = area_entry[0]
- depth = -1
- while temp != -1 and depth < len(colors)-1:
- depth += 1
- temp = hierarchy[0,temp,3]
- contour = contours[index]
- cv2.drawContours(image, [contour], 0, colors[depth], 1)
- result.append(contour)
- cv2.namedWindow(filename)
- cv2.imshow(filename, image)
- return result
- res_a = do_contours('star-a.jpg')
- print('res_a %d contours' % len(res_a))
- res_b = do_contours('star-b.jpg')
- print('res_b %d contours' % len(res_b))
- res_c = do_contours('star-c.png')
- print('res_c %d contours' % len(res_c))
- print('match A-B = ', cv2.matchShapes(res_a[0], res_b[0], 1, 0.0))
- print('match A-C0 = ', cv2.matchShapes(res_a[0], res_c[0], 1, 0.0))
- print('match A-C1 = ', cv2.matchShapes(res_a[0], res_c[1], 1, 0.0))
- print('match A-C2 = ', cv2.matchShapes(res_a[0], res_c[2], 1, 0.0))
- print('match B-C0 = ', cv2.matchShapes(res_b[0], res_c[0], 1, 0.0))
- print('match B-C1 = ', cv2.matchShapes(res_b[0], res_c[1], 1, 0.0))
- print('match B-C2 = ', cv2.matchShapes(res_b[0], res_c[2], 1, 0.0))
- cv2.waitKey(0)