recognizer.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. import cv2
  2. def triple(centers):
  3. return len(centers) == 3 and abs(centers[0][1] - centers[1][1]) < 100 and abs(centers[2][1] - centers[1][1]) < 100
  4. def quadriple(centers):
  5. return len(centers) == 4 and abs(centers[0][1] - centers[1][1]) < 100 and abs(centers[2][1] - centers[3][1]) < 100 and abs(centers[0][0] - centers[2][0]) < 100
  6. def color_distance(color1, color2):
  7. return ((color1[0] - color2[0])**2 + (color1[1] - color2[1])**2 + (color1[2] - color2[2])**2)**0.5
  8. def recognize(image, rtype, ncolors):
  9. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  10. _, hsv = cv2.threshold(hsv[:,:,1], 100, 255, cv2.THRESH_BINARY)
  11. hsv = cv2.erode(hsv, None, iterations=5)
  12. hsv = cv2.dilate(hsv, None, iterations=10)
  13. contours = cv2.findContours(hsv, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
  14. centers = []
  15. colors = []
  16. for i,contour in enumerate(contours):
  17. rot_react = cv2.minAreaRect(contour)
  18. centers.append(rot_react[0])
  19. color = tuple(map(int, image[int(centers[-1][1]), int(centers[-1][0]+10)]))
  20. colors.append(color)
  21. cv2.circle(image, tuple(map(int, rot_react[0])), radius=2, color=color, thickness=10)
  22. cv2.drawContours(image, contours, i, color, 10)
  23. colors_approve = all([color_distance(ncolors[i], colors[i]) < 100 for i in range(len(ncolors))])
  24. return colors_approve and rtype(centers), image