cv.py 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. import cv2
  2. import numpy as np
  3. def recognize(image):
  4. board1 = cv2.imread("project/board1.png")
  5. board2 = cv2.imread("project/board2.png")
  6. _, thrash, t_min_loc1, t_max_loc = cv2.minMaxLoc(
  7. cv2.matchTemplate(image, board1, cv2.TM_SQDIFF_NORMED)
  8. )
  9. _, thrash, t_min_loc2, t_max_loc = cv2.minMaxLoc(
  10. cv2.matchTemplate(image, board2, cv2.TM_SQDIFF_NORMED)
  11. )
  12. image = image[t_min_loc1[1] + 20:t_min_loc2[1], t_min_loc1[0] + 20:t_min_loc2[0]]
  13. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  14. hsv = cv2.GaussianBlur(hsv, (9, 9), 0)
  15. _, thresh = cv2.threshold(hsv[:, :, 1], 27, 255, cv2.THRESH_BINARY)
  16. cnts, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  17. polys = []
  18. for cont in cnts:
  19. eps = 0.044 * cv2.arcLength(cont, True)
  20. rect = cv2.minAreaRect(cont)
  21. box = cv2.boxPoints(rect)
  22. box = np.intp(box)
  23. approx = cv2.approxPolyDP(box, eps, True)
  24. approx = approx[:, 0, :].tolist()
  25. polys.append(approx)
  26. return polys, (t_min_loc2[0] + 20, t_min_loc2[1] + 20)