""" ============================================================ BASIC YOLO TASK 2 : OBJECT TRACKING ============================================================ WHAT THIS FILE DOES: - Same detection as 01_detection.py (boxes + class + conf) - PLUS: gives every object a persistent "track ID" number that stays the same across frames, as long as the object stays visible (e.g. "person #4" keeps ID 4 as it walks across the screen) - Draws a short "trail" showing where each object's center point has moved over the last N frames WHEN TO USE THIS: Use tracking (instead of plain detection) any time you need to know "is this the SAME object I saw 2 seconds ago?" — for example: - counting how many unique people/vehicles crossed a line - measuring how long an object stayed in frame - measuring speed (distance moved / time) of a vehicle - avoiding double-counting the same object every frame HOW IT WORKS UNDER THE HOOD: Ultralytics has tracking built in — instead of calling model(frame) like in detection, we call model.track(frame). It runs detection AND a tracking algorithm (ByteTrack or BoT-SORT) together, matching new detections to existing tracks frame-to-frame. Install deps: pip install ultralytics opencv-python lap (lap = the library the tracker uses for ID matching) ============================================================ """ import cv2 import time from collections import defaultdict, deque from ultralytics import YOLO # ------------------------------------------------------------ # SETTINGS # ------------------------------------------------------------ CAMERA_INDEX = 0 FRAME_W = 1280 FRAME_H = 720 CONF_THRESHOLD = 0.45 MODEL_WEIGHTS = 'yolo26n.pt' TRACKER_CFG = 'bytetrack.yaml' # alt: 'botsort.yaml' (slower, more accurate) TRAIL_LENGTH = 30 # how many past points to remember per object def load_model(): print("Loading YOLO26n model for tracking...") model = YOLO(MODEL_WEIGHTS) return model def run(): model = load_model() cap = cv2.VideoCapture(CAMERA_INDEX) cap.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_W) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_H) if not cap.isOpened(): print(f"ERROR: could not open camera {CAMERA_INDEX}") return # track_id -> deque of past (x, y) center points, used to draw trails trails = defaultdict(lambda: deque(maxlen=TRAIL_LENGTH)) print("Running tracking — press Q to quit") prev_t = time.time() while True: ok, frame = cap.read() if not ok: continue # ---- Core tracking call ---------------------------------- # persist=True tells the tracker "this is the next frame of # the SAME video", so it keeps matching IDs frame-to-frame # instead of resetting every call. results = model.track( frame, conf=CONF_THRESHOLD, tracker=TRACKER_CFG, persist=True, verbose=False ) boxes = results[0].boxes names = results[0].names # boxes.id is None on frames where nothing was tracked yet if boxes.id is not None: ids = boxes.id.int().tolist() for box, track_id in zip(boxes, ids): cls_id = int(box.cls[0]) conf = float(box.conf[0]) x1, y1, x2, y2 = map(int, box.xyxy[0]) cx, cy = (x1 + x2) // 2, (y1 + y2) // 2 # center point # remember this object's center for the trail trails[track_id].append((cx, cy)) label = f"ID {track_id} {names[cls_id]} {conf:.2f}" cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 200, 255), 2) cv2.putText(frame, label, (x1, y1 - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 200, 255), 2) # draw the trail (line through past center points) pts = list(trails[track_id]) for i in range(1, len(pts)): cv2.line(frame, pts[i - 1], pts[i], (0, 200, 255), 2) # ---- FPS --------------------------------------------------- now = time.time() fps = 1.0 / (now - prev_t) if now != prev_t else 0.0 prev_t = now cv2.putText(frame, f"FPS: {fps:.1f} Tracked: {len(trails)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2) cv2.imshow("YOLO - Tracking", frame) if cv2.waitKey(1) & 0xFF in (ord('q'), ord('Q')): break cap.release() cv2.destroyAllWindows() if __name__ == '__main__': run()