-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
122 lines (95 loc) · 3.58 KB
/
main.py
File metadata and controls
122 lines (95 loc) · 3.58 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import cv2
import numpy as np
import csv
import os
from datetime import datetime
import time
# === Configuration ===
VIDEO_SOURCE = 0 # Replace with 0 for webcam or path to CCTV footage
CASCADE_PATH = "haarcascade_car.xml" # Pre-trained car detector
# === Initialize video ===
cap = cv2.VideoCapture(VIDEO_SOURCE)
car_cascade = cv2.CascadeClassifier(CASCADE_PATH)
if not cap.isOpened():
print("❌ Error: Cannot open video source!")
exit()
# === Setup counters and parameters ===
line_y = 400
counter = 0
object_id = 0
objects = {}
counted = set()
paused = False
# === Setup log folder ===
if not os.path.exists("logs"):
os.makedirs("logs")
csv_path = "logs/car_log.csv"
if not os.path.exists(csv_path):
with open(csv_path, "w", newline="") as f:
csv.writer(f).writerow(["Car_ID", "Timestamp", "Count", "X", "Y"])
def distance(p1, p2):
return np.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
# === FPS calculation ===
prev_time = time.time()
fps = 0
print("🚗 Car Detection & Counting Started...")
print("Press 'q' to quit, 'p' to pause/resume, 'r' to reset counter.")
while True:
if not paused:
ret, frame = cap.read()
if not ret:
print("End of video or camera disconnected.")
break
# Convert to grayscale (for Haar cascade)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, 1.1, 4)
current_objects = {}
cv2.line(frame, (0, line_y), (frame.shape[1], line_y), (0, 0, 255), 2)
for (x, y, w, h) in cars:
cx, cy = x + w // 2, y + h // 2
matched = False
for oid, (ox, oy) in objects.items():
if distance((cx, cy), (ox, oy)) < 50:
current_objects[oid] = (cx, cy)
matched = True
# Count when crossing the red line
if oid not in counted and line_y - 10 <= cy <= line_y + 10:
counter += 1
counted.add(oid)
with open(csv_path, "a", newline="") as f:
csv.writer(f).writerow([
oid, datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
counter, cx, cy
])
cv2.imwrite(f"logs/car_{oid}_{counter}.jpg", frame[y:y+h, x:x+w])
break
if not matched:
object_id += 1
current_objects[object_id] = (cx, cy)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, f'Car {object_id}', (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
objects = current_objects.copy()
# === FPS Calculation ===
curr_time = time.time()
fps = 1 / (curr_time - prev_time)
prev_time = curr_time
cv2.putText(frame, f'Cars Counted: {counter}', (30, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.putText(frame, f'FPS: {int(fps)}', (30, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
cv2.imshow("🚘 Real-Time Car Tracker (CCTV)", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('p'):
paused = not paused
elif key == ord('r'):
counter = 0
counted.clear()
print("Counter reset!")
cap.release()
cv2.destroyAllWindows()
print("\n🟢 Tracking Ended")
print(f"🔹 Total Cars Counted: {counter}")
print(f"🔹 Logs saved at: {csv_path}")