food_colors.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import cv2
  2. import numpy as np
  3. class FoodColors:
  4. def __init__(self, img, scale, window_name):
  5. self.colors = []
  6. self.orig = img
  7. self.img = img.copy()
  8. self.scale = scale
  9. self.window_name = window_name
  10. self.done = False
  11. def add(self, x, y):
  12. x_img = int(x / self.scale)
  13. y_img = int(y / self.scale)
  14. self.colors.append(self.orig[y_img, x_img])
  15. self.show_selected()
  16. def show_selected(self):
  17. if len(self.colors) >= 2:
  18. low, high = self.compute()
  19. mask = cv2.inRange(self.img, np.array(low, dtype=np.uint8), np.array(high, dtype=np.uint8))
  20. maskrgb = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
  21. selected = np.zeros(self.img.shape, dtype=np.uint8)
  22. selected[:, :, 2] = mask
  23. self.img = cv2.add(cv2.subtract(self.img, maskrgb), selected)
  24. def draw(self):
  25. cv2.imshow(self.window_name, cv2.resize(self.img, (0, 0), fx=self.scale, fy=self.scale))
  26. self.confirm()
  27. def compute(self):
  28. low_color = [255, 255, 255]
  29. high_color = [0, 0, 0]
  30. if len(self.colors) == 0:
  31. return tuple(high_color), tuple(low_color)
  32. for color in self.colors:
  33. for i, c in enumerate(color):
  34. if c < low_color[i]:
  35. low_color[i] = c
  36. if c > high_color[i]:
  37. high_color[i] = c
  38. return tuple(low_color), tuple(high_color)
  39. def toJSON(self):
  40. l, h = self.compute()
  41. l = tuple([int(x) for x in l])
  42. h = tuple([int(x) for x in h])
  43. return {'Low Food Color': l, 'High Food Color': h}
  44. def help(self):
  45. print("--- Color Setup: Click several times on foods to setup food color and then press enter.")
  46. def clear(self):
  47. self.colors = []
  48. self.img = self.orig.copy()
  49. self.done = False
  50. def on_mouse(self, event, x, y, flags, param):
  51. if event == cv2.EVENT_LBUTTONUP:
  52. self.add(x, y)
  53. def confirm(self):
  54. key = cv2.waitKey(10) & 0xFF
  55. if key == 13: # Enter
  56. print("--- Color Setup: " + str(self.compute()))
  57. self.done = True
  58. elif len(self.colors) > 0 and key == 8: # Backspace
  59. del self.colors[len(self.colors)-1]
  60. self.img = self.orig.copy()
  61. self.show_selected()
  62. print("Last color removed. {} remaining(s).".format(len(self.colors)))