├── README.md └── traffic.py /README.md: -------------------------------------------------------------------------------- 1 | # Real-Time-Traffic-Detection-with-YOLOv8-OpenCV-CUDA- -------------------------------------------------------------------------------- /traffic.py: -------------------------------------------------------------------------------- 1 | from ultralytics import YOLO 2 | import torch 3 | import cv2 4 | 5 | device = "cuda" if torch.cuda.is_available() else "cpu" 6 | print(f"Using device: {device}") 7 | 8 | model = YOLO("yolov8n.pt").to(device) 9 | 10 | cap = cv2.VideoCapture("traffic.mp4") 11 | 12 | frame_width = 640 13 | frame_height = 480 14 | 15 | while cap.isOpened(): 16 | ret, frame = cap.read() 17 | if not ret: 18 | break 19 | 20 | 21 | frame = cv2.resize(frame, (frame_width, frame_height)) 22 | 23 | results = model(frame, device=device) 24 | vehicle_count = len(results[0].boxes) 25 | 26 | 27 | for r in results: 28 | for box in r.boxes: 29 | x1, y1, x2, y2 = map(int, box.xyxy[0]) 30 | cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) 31 | 32 | 33 | cv2.putText(frame, f"Vehicles: {vehicle_count}", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2) 34 | 35 | cv2.imshow("Traffic Detection", frame) 36 | if cv2.waitKey(1) & 0xFF == ord("q"): 37 | break 38 | 39 | cap.release() 40 | cv2.destroyAllWindows() 41 | --------------------------------------------------------------------------------