self.cap = cv2.VideoCapture(camera_id) # Camera capture
if not self.cap.isOpened():
# logger.error(f"Failed to open camera {camera_id}")
raise RuntimeError(f"Camera {camera_id} not accessible")
def detect_marker(self):
"""Detect ArUco marker in camera frame."""
ret, frame = self.cap.read()
if not ret:
print("Failed to capture frame")
return None, None
# Convert to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect markers
corners, ids, _ = self.detector.detectMarkers(gray)
if ids is not None and len(ids) > 0:
for i, marker_id in enumerate(ids.flatten()):
print(f"the marker id is {marker_id}")
# calculate distance to marker
camera_mtx , distort_coeffs = read_calibration()
rvec, tvec, _ = cv2.aruco.estimatePoseSingleMarkers(
corners[i], self.marker_length, self.camera_mtx, self.dist_coeffs
)
self.distance = tvec[0][0][2]
print(f"the distance to the marker is {self.distance}")
# logger.info(f"the distance to the marker is", self.distance)
# Calculate marker center
marker_corners = corners[i][0]
center_x = int(np.mean(marker_corners[:, 0]))
center_y = int(np.mean(marker_corners[:, 1]))
self.visualization(center_x, center_y, frame, corners, ids)
return (center_x, center_y), frame, marker_id
return None, frame, None
def run(self, driver):
"""Run the state machine."""
try:
while True:
marker_pos, frame, marker_id = self.detect_marker()
current_time = time.time()
if self.state == State.MOVE_STRAIGHT:
if marker_pos is not None:
print(f"the current state is {self.state}")
# logger.info(f"the current state is", self.state)
# Marker detected, continue moving straight
center_x, _ = marker_pos
frame_width = frame.shape[1]
# Simple proportional control for steering
error = center_x - frame_width / 2
if self.distance > self.min_distance:
driver.move_forward(float(error))
if error > 0:
print("the command is turn right with error ", error)
# logger.info("the command is turn Right with error ", error)
else:
# logger.info("the command is turn Left with error ", error)
print("the command is turn Left with error ", error)
self.last_seen_time = current_time
elif self.distance> self.stop_distance:
driver.stop()
print("Switching to ROTATE state")
self.previous_marker_id = marker_id
self.state = State.ROTATE
else:
driver.stop()
self.state = State.Stop
print("Switching to Stop state")
self.previous_marker_id = marker_id
elif current_time - self.last_seen_time > 30000.0:
# Marker lost for too long, switch to rotate
print(" IN the time limitation")
driver.stop()
self.state = State.ROTATE
print("Switching to ROTATE state")
elif self.state == State.ROTATE:
if marker_pos is not None and marker_id != self.previous_marker_id:
# Marker found, switch to move straight
self.rotate_count = 0
driver.stop()
self.state = State.MOVE_STRAIGHT
self.last_seen_time = current_time
print("Switching to MOVE_STRAIGHT state")
else:
if self.rotate_count < self.max_rotation:
driver.rotate(self.rotation_angle)
# logger.info(f"Rotating, count: {self.rotate_count}")
print(f"Rotating, count: {self.rotate_count}")
time.sleep(ROTATION_SLEEP_TIME)
else:
driver.stop()
# logger.info("One turn limitation rotations reached, stopping")
print("One turn limitation rotations reached, stopping")
self.rotate_count += 1
# Display frame for debugging (optional)
if frame is not None:
cv2.imshow("AGV Camera", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
print("Shutting down AGV")
finally:
driver.stop()
self.cap.release()
cv2.destroyAllWindows()
def visualization(self, center_x, center_y, frame, corners, ids):
# find the marker and frame center
center = (center_x, center_y)
height, width = frame.shape[:2]
# Draw image center
cv2.circle(frame, (int(width / 2), int(height / 2)), 5, (0, 255, 0), -1)
# Draw Aurco center
cv2.circle(frame,center, 5, (0, 0, 255), -1)
# Draw detected ids
cv2.aruco.drawDetectedMarkers(frame, corners, ids)