limits_maker.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import cv2
  2. class LimitsMaker:
  3. def __init__(self, img, scale, window_name, name):
  4. self.limits = []
  5. self.max_limits = 4
  6. self.orig = img
  7. self.img = img.copy()
  8. self.scale = scale
  9. self.window_name = window_name
  10. self.done = False
  11. self.limits_drawn = False
  12. self.name = name
  13. def add_limit(self, x, y):
  14. x_img = int(x / self.scale)
  15. y_img = int(y / self.scale)
  16. self.limits.append((x_img, y_img))
  17. cv2.drawMarker(self.img, (x_img, y_img), (0, 0, 255), thickness=5)
  18. def draw(self):
  19. if len(self.limits) == self.max_limits and not self.limits_drawn:
  20. for i, limit in enumerate(self.limits):
  21. cv2.line(self.img, self.limits[i-1], limit, (0, 0, 255), thickness=3)
  22. self.limits_drawn = True
  23. cv2.imshow(self.window_name, cv2.resize(self.img, (0, 0), fx=self.scale, fy=self.scale))
  24. if self.enough_data():
  25. self.confirm()
  26. def enough_data(self):
  27. return len(self.limits) == self.max_limits
  28. def compute(self):
  29. return self.limits
  30. def toJSON(self):
  31. return {'Limits': self.limits}
  32. def help(self):
  33. print("--- " + self.name + ": Click on the {} corners.".format(self.max_limits))
  34. print("--- " + self.name + ": Please start from left corner and do it in the right order")
  35. def on_mouse(self, event, x, y, flags, param):
  36. if event == cv2.EVENT_LBUTTONUP and not self.enough_data():
  37. if len(self.limits) < self.max_limits:
  38. self.add_limit(x, y)
  39. def clear(self):
  40. self.limits = []
  41. self.limits_drawn = False
  42. self.img = self.orig.copy()
  43. self.done = False
  44. def confirm(self):
  45. print("--- " + self.name + ": Press enter if you're ok with data or any other key if you want to restart "
  46. "setup...")
  47. key = cv2.waitKey(0) & 0xFF
  48. if key == 13: # Enter
  49. print("--- " + self.name + ": " + str(self.compute()))
  50. self.done = True
  51. else:
  52. self.clear()
  53. self.help()