spray_pesticide.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import cv2
  2. from cv2 import aruco
  3. import numpy as np
  4. import time
  5. import sys
  6. import os
  7. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  8. from default_config import *
  9. visualization = True
  10. def is_in_center(x_px, y_px, frame_w, frame_h, margin_ratio=0.25):
  11. margin_x = frame_w * margin_ratio
  12. margin_y = frame_h * margin_ratio
  13. return (margin_x < x_px < frame_w - margin_x) and (margin_y < y_px < frame_h - margin_y)
  14. def get_euler_angles_from_rvec(rvec):
  15. rot_matrix, _ = cv2.Rodrigues(rvec)
  16. sy = np.sqrt(rot_matrix[0, 0]**2 + rot_matrix[1, 0]**2)
  17. singular = sy < 1e-6
  18. if not singular:
  19. roll = np.arctan2(rot_matrix[2, 1], rot_matrix[2, 2])
  20. pitch = np.arctan2(-rot_matrix[2, 0], sy)
  21. yaw = np.arctan2(rot_matrix[1, 0], rot_matrix[0, 0])
  22. else:
  23. roll = np.arctan2(-rot_matrix[1, 2], rot_matrix[1, 1])
  24. pitch = np.arctan2(-rot_matrix[2, 0], sy)
  25. yaw = 0
  26. return np.degrees(roll), np.degrees(pitch), np.degrees(yaw)
  27. def is_roll_valid(roll):
  28. return (abs(roll) < ALLOWED_ANGLE_DEG) or (160 <= abs(roll) <= 180)
  29. def spray_pesticide(marker_id):
  30. print(f"✅ SPRAYING! Marker ID: {marker_id}")
  31. calib_data_path = f"camera_calibration/calib_data/{set_resolution}/MultiMatrix.npz"
  32. calib_data = np.load(calib_data_path)
  33. print('resolution:', set_resolution)
  34. cam_mat = calib_data["camMatrix"]
  35. dist_coef = calib_data["distCoef"]
  36. marker_dict = aruco.getPredefinedDictionary(aruco.DICT_7X7_50)
  37. param_markers = aruco.DetectorParameters()
  38. cap = cv2.VideoCapture(0)
  39. # Thay đổi độ phân giải phù hợp với yêu cầu ban đầu
  40. new_height = RESOLUTION_STANDARDS[set_resolution]
  41. new_width, new_height = change_resolution(cap,new_height)
  42. print(f'Resolution camera {new_width}x{new_height}')
  43. fps = cap.get(cv2.CAP_PROP_FPS)
  44. print(f"Frames per second: {fps}")
  45. def start_spraying(marker_id):
  46. print(f"🟡 SPRAYING marker {marker_id}...")
  47. def stop_spraying(marker_id):
  48. print(f"✅ SPRAYED marker {marker_id}")
  49. # --- Track state ---
  50. marker_states = {} # marker_id -> {"state": "NOT_SPRAYED"/"SPRAYING"/"SPRAYED", "start_time": float}
  51. while True:
  52. ret, frame = cap.read()
  53. if not ret:
  54. break
  55. gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  56. detector = cv2.aruco.ArucoDetector(marker_dict, param_markers)
  57. marker_corners, marker_IDs, _ = detector.detectMarkers(gray_frame)
  58. current_time = time.time()
  59. if marker_corners:
  60. rVec, tVec, _ = aruco.estimatePoseSingleMarkers(marker_corners, MARKER_SIZE, cam_mat, dist_coef)
  61. for i, (ids, corners) in enumerate(zip(marker_IDs, marker_corners)):
  62. marker_id = int(ids[0])
  63. corners = corners.reshape(4, 2).astype(int)
  64. cx = int(np.mean(corners[:, 0]))
  65. cy = int(np.mean(corners[:, 1]))
  66. x, y, z = tVec[i][0]
  67. roll, pitch, yaw = get_euler_angles_from_rvec(rVec[i])
  68. # Kiểm tra đủ điều kiện
  69. in_center = is_in_center(cx, cy, new_width, new_height)
  70. within_angle = is_roll_valid(roll)
  71. within_xyz = (
  72. ALLOWED_XYZ_RANGE["x"][0] <= x <= ALLOWED_XYZ_RANGE["x"][1] and
  73. ALLOWED_XYZ_RANGE["y"][0] <= y <= ALLOWED_XYZ_RANGE["y"][1] and
  74. ALLOWED_XYZ_RANGE["z"][0] <= z <= ALLOWED_XYZ_RANGE["z"][1]
  75. )
  76. if marker_id not in marker_states:
  77. marker_states[marker_id] = {"state": "NOT_SPRAYED", "start_time": 0}
  78. state_info = marker_states[marker_id]
  79. if in_center and within_angle and within_xyz:
  80. if state_info["state"] == "NOT_SPRAYED":
  81. start_spraying(marker_id)
  82. marker_states[marker_id] = {
  83. "state": "SPRAYING",
  84. "start_time": current_time
  85. }
  86. elif state_info["state"] == "SPRAYING":
  87. elapsed = current_time - state_info["start_time"]
  88. if elapsed >= SPRAY_DURATION:
  89. stop_spraying(marker_id)
  90. marker_states[marker_id]["state"] = "SPRAYED"
  91. # --- Visualization ---
  92. status = marker_states[marker_id]["state"]
  93. color = {"NOT_SPRAYED": (0, 0, 255), "SPRAYING": (0, 255, 255), "SPRAYED": (0, 255, 0)}[status]
  94. if visualization:
  95. cv2.polylines(frame, [corners], True, color, 2)
  96. cv2.drawFrameAxes(frame, cam_mat, dist_coef, rVec[i], tVec[i], 4, 4)
  97. cv2.putText(frame, f"ID: {marker_id}", (cx + 10, cy), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
  98. cv2.putText(frame, f"{status}", (cx + 10, cy + 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
  99. cv2.putText(frame, f"x:{x:.1f} y:{y:.1f} z:{z:.1f}", (cx + 10, cy + 45), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)
  100. cv2.putText(frame, f"roll:{roll:.1f} pitch:{pitch:.1f} yaw:{yaw:.1f}", (cx + 10, cy + 65), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 255), 1)
  101. if visualization:
  102. cv2.imshow("frame", frame)
  103. key = cv2.waitKey(1)
  104. if key == ord("q"):
  105. break
  106. cap.release()
  107. cv2.destroyAllWindows()