Guest User

Untitled

a guest
Mar 21st, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. sc = ShapeContext()
  2.  
  3. def get_contour_bounding_rectangles(gray):
  4. """
  5. Getting all 2nd level bouding boxes based on contour detection algorithm.
  6. """
  7. cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  8. res = []
  9. for cnt in cnts[1]:
  10. (x, y, w, h) = cv2.boundingRect(cnt)
  11. res.append((x, y, x + w, y + h))
  12.  
  13. return res
  14.  
  15. def parse_nums(sc, path):
  16. img = cv2.imread(path, 0)
  17. # invert image colors
  18. img = cv2.bitwise_not(img)
  19. _, img = cv2.threshold(img, 254, 255, cv2.THRESH_BINARY)
  20. # making numbers fat for better contour detectiion
  21. kernel = np.ones((2, 2), np.uint8)
  22. img = cv2.dilate(img, kernel, iterations=1)
  23.  
  24. # getting our numbers one by one
  25. rois = get_contour_bounding_rectangles(img)
  26. grayd = cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2BGR)
  27. nums = []
  28. for r in rois:
  29. grayd = cv2.rectangle(grayd, (r[0], r[1]), (r[2], r[3]), (0, 255, 0), 1)
  30. nums.append((r[0], r[1], r[2], r[3]))
  31. # we are getting contours in different order so we need to sort them by x1
  32. nums = sorted(nums, key=lambda x: x[0])
  33. descs = []
  34. for i, r in enumerate(nums):
  35. if img[r[1]:r[3], r[0]:r[2]].mean() < 50:
  36. continue
  37. points, _ = sc.get_points_from_img(img[r[1]:r[3], r[0]:r[2]], 50, 15)
  38. descriptor = sc.compute(points).flatten()
  39. descs.append(descriptor)
  40. return np.array(descs)
  41.  
  42. def match(base, current):
  43. """
  44. Here we are using cosine diff instead of "by paper" diff, cause it's faster
  45. """
  46. res = cdist(base, current.reshape((1, current.shape[0])), metric="cosine")
  47. char = str(np.argmin(res.reshape(11)))
  48. if char == '10':
  49. char = "/"
  50. return char
  51.  
  52. base_0123456789 = parse_nums(sc, 'numbers.png')
  53. recognize = parse_nums(sc, 'numbers_test3.png')
  54. res = ""
  55. for r in recognize:
  56. res += match(base_0123456789, r)
  57.  
  58. img = cv2.imread('numbers_test3.png')
  59. plt.imshow(img)
  60. plt.show()
  61. print res
Add Comment
Please, Sign In to add comment