cv.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import cv2
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
  5. def chose(contour):
  6. sm = cv2.arcLength(contour, True)
  7. approx = cv2.approxPolyDP(contour, sm*0.025, True)
  8. if len(approx) == 7 or len(approx) == 8: return 'circle'
  9. lower = 100
  10. upper = 200
  11. def lower_update(value):
  12. global lower
  13. lower = value
  14. def upper_update(value):
  15. global upper
  16. upper = value
  17. cv2.createTrackbar("Lower", "Image", lower, 255, lower_update)
  18. cv2.createTrackbar("Upper", "Image", upper, 255, upper_update)
  19. def recognize(image):
  20. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  21. binary = np.zeros(hsv.shape[:-1])
  22. binary[np.any(hsv > 190, axis=2)] = 1
  23. contours = cv2.findContours(binary.astype('uint8'), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
  24. corner_left_up, corner_right_down = None, None
  25. for i,contour in enumerate(contours):
  26. if chose(contour) == 'circle':
  27. x = contour[:, 0, 0]
  28. y = contour[:, 0, 1]
  29. x_max, x_min, y_max, y_min = x.max(), x.min(), y.max(), y.min()
  30. if not corner_left_up or corner_left_up[0] < x_min or corner_left_up[1] < y_min:
  31. corner_left_up = (x_max, y_max)
  32. elif not corner_right_down or corner_right_down[0] < x_min or corner_right_down[1] < y_min:
  33. corner_right_down = (x_min, y_min)
  34. shape = (corner_left_up[0]-corner_right_down[0], corner_left_up[1]-corner_right_down[1])
  35. image = image[corner_right_down[1]:corner_left_up[1],corner_right_down[0]:corner_left_up[0]]
  36. # hsv = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2HSV)
  37. # hsv = cv2.GaussianBlur(hsv, (1, 1), 0)
  38. # _, thresh = cv2.threshold(hsv[:, :, 1], lower, upper, cv2.THRESH_BINARY)
  39. # cnts, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  40. # cv2.drawContours(image, cnts, -1, (0, 255, 0), 2)
  41. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  42. thresh = cv2.threshold(image, lower, upper, cv2.THRESH_BINARY)[0]
  43. # thresh = cv2.adaptiveThreshold(image,upper,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,3,2)
  44. binary = np.zeros(image.shape)
  45. binary[image < thresh] = 1
  46. # polys = []
  47. # for cont in cnts:
  48. # eps = 0.044 * cv2.arcLength(cont, True)
  49. # rect = cv2.minAreaRect(cont)
  50. # box = cv2.boxPoints(rect)
  51. # box = np.intp(box)
  52. # approx = cv2.approxPolyDP(box, eps, True)
  53. # approx = approx[:, 0, :].tolist()
  54. # polys.append(approx)
  55. cv2.imshow('Image', binary)
  56. cv2.waitKey(1)
  57. # return polys, shape
  58. if __name__ == "__main__":
  59. while True:
  60. image = cv2.imread('falling_ball/image.png')
  61. print(recognize(image))