Spaces:
No application file
No application file
File size: 1,748 Bytes
565dac0 1ba89c1 565dac0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 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()
|