cv.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import cv2
  2. import numpy as np
  3. cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
  4. def chose(contour):
  5. sm = cv2.arcLength(contour, True)
  6. approx = cv2.approxPolyDP(contour, sm*0.025, True)
  7. if len(approx) == 8: return 'circle'
  8. def recognize(image):
  9. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  10. binary = np.zeros(hsv.shape[:-1])
  11. binary[np.any(hsv > 190, axis=2)] = 1
  12. cv2.imshow('Image', binary)
  13. while cv2.waitKey(1) != ord('q'): continue
  14. labels, labeledScreen = cv2.connectedComponents(binary)
  15. cnts, hierrache = cv2.findContours(labels, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
  16. for label in labels:
  17. print(chose(label))
  18. # image = image[t_min_loc1[1] + 20:t_min_loc2[1], t_min_loc1[0] + 20:t_min_loc2[0]]
  19. # hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  20. # hsv = cv2.GaussianBlur(hsv, (9, 9), 0)
  21. # _, thresh = cv2.threshold(hsv[:, :, 1], 27, 255, cv2.THRESH_BINARY)
  22. # cnts, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  23. # polys = []
  24. # for cont in cnts:
  25. # eps = 0.044 * cv2.arcLength(cont, True)
  26. # rect = cv2.minAreaRect(cont)
  27. # box = cv2.boxPoints(rect)
  28. # box = np.intp(box)
  29. # approx = cv2.approxPolyDP(box, eps, True)
  30. # approx = approx[:, 0, :].tolist()
  31. # polys.append(approx)
  32. # return polys, (t_min_loc2[0] + 20, t_min_loc2[1] + 20)
  33. if __name__ == "__main__":
  34. image = cv2.imread('falling_ball/image.png')
  35. print(recognize(image))