PYTHON   86

match shapes

Guest on 15th June 2022 05:11:55 AM

  1. import cv2
  2.  
  3. def do_contours(filename):
  4.     colors = [(0,0,255), (0,255,0), (255,0,0),
  5.               (255,255,0), (255,0,255), (0,255,255),
  6.               (0,0,128), (0,128,0), (128,0,0),
  7.               (128,128,0), (0,128,128), (128,0,128),
  8.               (255,255,255)]
  9.     image = cv2.imread(filename)
  10.     image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
  11.     ret, image_thresh = cv2.threshold(image_gray, 127, 255, 0)
  12.     contours, hierarchy = \
  13.             cv2.findContours(image_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  14.     areas = [(i, cv2.contourArea(contours[i])) for i in range(len(contours))]
  15.     areas.sort(key=lambda x: x[1])
  16.     areas.reverse()
  17.     minArea = 50
  18.     result = []
  19.     print(hierarchy)
  20.     for area_entry in areas:
  21.         if area_entry[1] < minArea:
  22.             break
  23.         temp = index = area_entry[0]
  24.         depth = -1
  25.         while temp != -1 and depth < len(colors)-1:
  26.             depth += 1
  27.             temp = hierarchy[0,temp,3]
  28.         contour = contours[index]
  29.         cv2.drawContours(image, [contour], 0, colors[depth], 1)
  30.         result.append(contour)
  31.     cv2.namedWindow(filename)
  32.     cv2.imshow(filename, image)
  33.     return result
  34.  
  35.  
  36. res_a = do_contours('star-a.jpg')
  37. print('res_a %d contours' % len(res_a))
  38.  
  39. res_b = do_contours('star-b.jpg')
  40. print('res_b %d contours' % len(res_b))
  41.  
  42. res_c = do_contours('star-c.png')
  43. print('res_c %d contours' % len(res_c))
  44.  
  45. print('match A-B = ', cv2.matchShapes(res_a[0], res_b[0], 1, 0.0))
  46.  
  47. print('match A-C0 = ', cv2.matchShapes(res_a[0], res_c[0], 1, 0.0))
  48. print('match A-C1 = ', cv2.matchShapes(res_a[0], res_c[1], 1, 0.0))
  49. print('match A-C2 = ', cv2.matchShapes(res_a[0], res_c[2], 1, 0.0))
  50.  
  51. print('match B-C0 = ', cv2.matchShapes(res_b[0], res_c[0], 1, 0.0))
  52. print('match B-C1 = ', cv2.matchShapes(res_b[0], res_c[1], 1, 0.0))
  53. print('match B-C2 = ', cv2.matchShapes(res_b[0], res_c[2], 1, 0.0))
  54.  
  55. cv2.waitKey(0)

Raw Paste


Login or Register to edit or fork this paste. It's free.