import cv2 import numpy as np def ai_decision(center, frame_width): """ Simple AI rule-based path optimization: - If line is left -> turn LEFT - If line is right -> turn RIGHT - Otherwise -> go STRAIGHT """ if center < frame_width * 0.4: return "LEFT" elif center > frame_width * 0.6: return "RIGHT" else: return "STRAIGHT" # Open webcam (0 = default camera) cap = cv2.VideoCapture(0) print("Press 'q' to exit...") while True: ret, frame = cap.read() if not ret: break # Convert to gray gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Threshold to detect black line _, thresh = cv2.threshold(gray, 100, 265, cv2.THRESH_BINARY_INV) # Take bottom part of the frame (region of interest) roi = thresh[int(thresh.shape[0]*0.7):, :] # Find contours contours, _ = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if contours: largest_contour = max(contours, key=cv2.contourArea) M = cv2.moments(largest_contour) if M["m00"] != 0: cx = int(M["m10"] / M["m00"]) # line center cy = int(M["m01"] / M["m00"]) # Draw center point on frame cv2.circle(frame, (cx, int(cy + thresh.shape[0]*0.7)), 5, (0, 0, 255), -1) # AI decision move = ai_decision(cx, frame.shape[1]) cv2.putText(frame, f"Decision: {move}", (30, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2) print("MOVE:", move) # Show camera feed cv2.imshow("Line Follower Simulation", frame) # Quit with q if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()