markerDetection.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/python3
  2. import numpy as np
  3. import cv2
  4. import cv2.aruco as aruco
  5. aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)
  6. def saveMarkers():
  7. image = np.zeros((400,400), np.uint8)
  8. image[:,:] = (255)
  9. image[ 50: 50 + 100, 50: 50 + 100] = aruco_dict.drawMarker(0, 100)
  10. image[-50 - 100:-50, 50: 50 + 100] = aruco_dict.drawMarker(1, 100)
  11. image[ 50: 50 + 100,-50 - 100:-50] = aruco_dict.drawMarker(2, 100)
  12. image[-50 - 100:-50,-50 - 100:-50] = aruco_dict.drawMarker(3, 100)
  13. cv2.imwrite("markers.png", image)
  14. parameters = aruco.DetectorParameters_create()
  15. def find_marker(image):
  16. # Our operations on the frame come here
  17. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  18. corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
  19. markers = [None] * 4
  20. if not corners:
  21. return markers
  22. for corner, id in zip(corners, ids.flatten()):
  23. # draw the bounding box of the ArUCo detection
  24. c = corner[0]
  25. cv2.line(image, tuple(c[0]), tuple(c[1]), (0, 255, 0), 2)
  26. cv2.line(image, tuple(c[1]), tuple(c[2]), (0, 255, 0), 2)
  27. cv2.line(image, tuple(c[2]), tuple(c[3]), (0, 255, 0), 2)
  28. cv2.line(image, tuple(c[3]), tuple(c[0]), (0, 255, 0), 2)
  29. cv2.putText(image, str(id), (int(c[0][0]), int(c[0][1]) - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
  30. cX = sum(c[:,0]) / 4
  31. cY = sum(c[:,1]) / 4
  32. cv2.circle(image, (int(cX), int(cY)), 4, (0, 0, 255), -1)
  33. if id < 4:
  34. markers[id] = (cX, cY)
  35. return markers
  36. def measureDistances(image):
  37. markers = find_marker(image)
  38. if markers[0] and markers[1]:
  39. cv2.line(image, (int(markers[0][0]),int(markers[0][1])), (int(markers[1][0]),int(markers[1][1])), (255, 0, 0), 2)
  40. length = np.sqrt((markers[0][0]-markers[1][0])**2 + (markers[0][1]-markers[1][1])**2)
  41. middle = abs(markers[0][0]-markers[1][0])
  42. return middle, length
  43. else:
  44. return None
  45. if __name__ == "__main__":
  46. cap = cv2.VideoCapture(0)
  47. while True:
  48. success, image = cap.read()
  49. markers = find_marker(image)
  50. if markers[0] and markers[1]:
  51. cv2.line(image, (int(markers[0][0]),int(markers[0][1])), (int(markers[1][0]),int(markers[1][1])), (255, 0, 0), 2)
  52. length = np.sqrt((markers[0][0]-markers[1][0])**2 + (markers[0][1]-markers[1][1])**2)
  53. cv2.putText(image, "%.2fpx" % (length), (int(markers[0][0]), int(markers[0][1])), cv2.FONT_HERSHEY_SIMPLEX,
  54. 1.0, (255, 255, 0), 3)
  55. cv2.imshow("image", image)
  56. if cv2.waitKey(1) & 0xFF == ord('q'):
  57. break