repository to manage all files for 1_2_oder_3 interaction game for Inf2/2 Interaktionen SoSe23 from Engert, Caliskan and Bachiri
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

camera.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import cv2
  2. import numpy as np
  3. class Camera():
  4. def __init__(self) -> None:
  5. self.colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]
  6. self.color_names = ["Rot", "Gruen", "Blau"]
  7. self.lower_red = np.array([80, 160, 150])
  8. self.upper_red = np.array([255, 255, 255])
  9. self.lower_green = np.array([40, 50, 160])
  10. self.upper_green = np.array([80, 255, 255])
  11. self.lower_blue = np.array([95, 180, 90])
  12. self.upper_blue = np.array([130, 255, 255])
  13. self.video = cv2.VideoCapture(0)
  14. self.image = np.ndarray([])
  15. self.picture_counter = 0
  16. self.evaluate_picture = False
  17. def get_frame(self) -> np.ndarray:
  18. try:
  19. _, self.image = self.video.read(0)
  20. except Exception as err:
  21. print("Can not capture the video..\n")
  22. print(err)
  23. return self.image
  24. def set_take_picture(self, take: bool):
  25. self.evaluate_picture = take
  26. def take_picture(self) -> None:
  27. file_name = 'score_round'+ str(self.picture_counter) + '.png'
  28. cv2.imwrite(file_name, self.image)
  29. self.picture_counter = self.picture_counter + 1
  30. self.set_take_picture(False)
  31. def detect_color(self, image):
  32. hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  33. count_red, count_green, count_blue= 0,0,0
  34. results = []
  35. for i, color in enumerate(self.colors):
  36. if i == 0:
  37. lower = self.lower_red
  38. upper = self.upper_red
  39. elif i == 1:
  40. lower = self.lower_green
  41. upper = self.upper_green
  42. elif i == 2:
  43. lower = self.lower_blue
  44. upper = self.upper_blue
  45. mask = cv2.inRange(hsv_img, lower, upper)
  46. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  47. center = None
  48. count = 0
  49. for contour in contours:
  50. if count < 3:
  51. if 100 < cv2.contourArea(contour):
  52. M = cv2.moments(contour)
  53. if M["m00"] > 0:
  54. cX = int(M["m10"] / M["m00"])
  55. cY = int(M["m01"] / M["m00"])
  56. center = (cX, cY)
  57. count += 1
  58. x, y, w, h = cv2.boundingRect(contour)
  59. cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
  60. cv2.putText(image, self.color_names[i], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
  61. if i == 0:
  62. count_red += 1
  63. elif i == 1:
  64. count_green += 1
  65. elif i == 2:
  66. count_blue += 1
  67. results.append(center)
  68. current_score= {'score_red': count_red,
  69. 'score_green': count_green,
  70. 'score_blue': count_blue
  71. }
  72. return results, image, current_score
  73. def determine_position(self,results, img_width):
  74. positions = []
  75. for result in results:
  76. if result is None:
  77. position = 0
  78. else:
  79. x = result[0]
  80. if x < img_width / 3:
  81. position = 3
  82. elif x < 2 * img_width / 3:
  83. position = 2
  84. else:
  85. position = 1
  86. positions.append(position)
  87. return positions
  88. def check_correct_field(self, correct_field: int):
  89. pass
  90. def current_score(self, scores: dict):
  91. return scores
  92. def main():
  93. my_camera = Camera()
  94. while True:
  95. frame = my_camera.get_frame()
  96. results, image, current_score = my_camera.detect_color(frame)
  97. if my_camera.evaluate_picture:
  98. my_camera.take_picture()
  99. my_camera.current_score(current_score)
  100. cv2.putText(frame, f"Rot: {current_score['score_red']}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, my_camera.colors[0], 2)
  101. cv2.putText(frame, f"Gruen: {current_score['score_green']}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, my_camera.colors[1], 2)
  102. cv2.putText(frame, f"Blau: {current_score['score_blue']}", (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 1, my_camera.colors[2], 2)
  103. img_width = frame.shape[1]
  104. positions = my_camera.determine_position(results, img_width)
  105. for i, position in enumerate(positions):
  106. cv2.putText(image, f"{my_camera.color_names[i]}: {position}", (10, 150 + 30 * i),
  107. cv2.FONT_HERSHEY_SIMPLEX, 1, my_camera.colors[i], 2)
  108. cv2.line(img=image, pt1=(img_width // 3, 0), pt2=(img_width // 3, frame.shape[0]), color=(0, 0, 0), thickness=2)
  109. cv2.line(img=image, pt1=(2 * img_width // 3, 0), pt2=(2 * img_width // 3, frame.shape[0]), color=(0, 0, 0), thickness=2)
  110. cv2.imshow("Farberkennung", frame)
  111. print(current_score)
  112. if cv2.waitKey(1) & 0xFF == ord('q'):
  113. break
  114. my_camera.video.release()
  115. cv2.destroyAllWindows()
  116. if __name__ == "__main__":
  117. main()