Spaces:
Sleeping
Sleeping
| import cv2 | |
| from ultralytics import YOLO | |
| from deep_sort_realtime.deepsort_tracker import DeepSort | |
| import os | |
| # Load YOLOv8 model | |
| model = YOLO('yolov8n.pt') | |
| tracker = DeepSort(max_age=30) | |
| # Local video file | |
| video_path = r'C:\Users\alyhi\Desktop\Football Player Tracker\video\vid.mp4' | |
| if not os.path.exists(video_path): | |
| raise FileNotFoundError(f"Video file not found: {video_path}") | |
| cap = cv2.VideoCapture(video_path) | |
| if not cap.isOpened(): | |
| raise IOError(f"Could not open video: {video_path}") | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| results = model(frame)[0] | |
| detections = [] | |
| for result in results.boxes.data.tolist(): | |
| x1, y1, x2, y2, score, class_id = result | |
| if int(class_id) == 0 and score > 0.4: | |
| bbox = [x1, y1, x2 - x1, y2 - y1] | |
| detections.append((bbox, score, 'player')) | |
| tracks = tracker.update_tracks(detections, frame=frame) | |
| for track in tracks: | |
| if not track.is_confirmed(): | |
| continue | |
| track_id = track.track_id | |
| l, t, r, b = track.to_ltrb() | |
| cv2.rectangle(frame, (int(l), int(t)), (int(r), int(b)), (0, 255, 0), 2) | |
| cv2.putText(frame, f'Player {track_id}', (int(l), int(t - 10)), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) | |
| cv2.imshow("⚽ Football Player Tracker", frame) | |
| if cv2.waitKey(1) & 0xFF == ord('q'): | |
| break | |
| cap.release() | |
| cv2.destroyAllWindows() | |