-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcar_counter.py
More file actions
77 lines (57 loc) · 2.93 KB
/
Copy pathcar_counter.py
File metadata and controls
77 lines (57 loc) · 2.93 KB
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
68
69
70
71
72
73
74
75
76
77
import cv2
from ultralytics import YOLO
# 1. Initialize the YOLO model (Pre-trained on 80 common object classes)
# 'yolov8n.pt' is the nano model - incredibly fast and ideal for CPUs/laptops
model = YOLO("yolov8n.pt")
# Define target COCO dataset class IDs for vehicles we want to count
# Class 2 = car, Class 3 = motorcycle, Class 5 = bus, Class 7 = truck
VEHICLE_CLASSES = [2, 3, 5, 7]
# 2. Choose your input source:
# For a video file: put the video in your project folder and replace with "traffic.mp4"
# For live webcam/traffic camera feed: use 0
source ="video.mp4"
cap = cv2.VideoCapture(source)
print("\n🚀 Vehicle Counter Active! Press 'q' to quit.")
while cap.isOpened():
success, frame = cap.read()
if not success:
print("End of video stream or camera unavailable.")
break
# 3. Pass the frame to YOLO (stream=True optimizes memory for loops)
# verbose=False keeps our terminal clean from clutter
results = model(frame, stream=True, verbose=False)
car_count = 0
# 4. Process the detection results
for result in results:
boxes = result.boxes # Box coordinates for detected items
for box in boxes:
# Extract the class ID integer
cls_id = int(box.cls[0])
# If the detected object is a car, truck, bus, or motorcycle
if cls_id in VEHICLE_CLASSES:
car_count += 1
# Get bounding box coordinates: Top-Left (x1, y1) and Bottom-Right (x2, y2)
x1, y1, x2, y2 = map(int, box.xyxy[0])
# Extract the confidence score (e.g., 0.85 means 85% sure it's a car)
confidence = float(box.conf[0])
# Get the human-readable class name text (e.g., "car")
class_name = model.names[cls_id]
# Draw a bounding box rectangle around the vehicle (Green color)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Draw a text label stating the object type and confidence score
label = f"{class_name.upper()} {confidence:.2f}"
cv2.putText(frame, label, (x1, max(0, y1 - 10)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 5. Display the overall tally count on the Screen (HUD Overlay)
hud_text = f"Total Vehicles Spotted: {car_count}"
# Draw a shadow outline first for high contrast readability
cv2.putText(frame, hud_text, (22, 52), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 4, cv2.LINE_AA)
cv2.putText(frame, hud_text, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2, cv2.LINE_AA)
# Show the output frame window
cv2.imshow("YOLO Real-Time Vehicle Analytics", frame)
# Exit window gracefully on pressing 'q'
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Cleanup
cap.release()
cv2.destroyAllWindows()