ByteTrack-Based Tracker
Browse files
app.py
CHANGED
|
@@ -1,289 +1,330 @@
|
|
| 1 |
import torch
|
| 2 |
import gradio as gr
|
| 3 |
import cv2, os, numpy as np, tempfile, time, json
|
| 4 |
-
from filterpy.kalman import KalmanFilter
|
| 5 |
from scipy.optimize import linear_sum_assignment
|
| 6 |
-
from
|
| 7 |
from sklearn.cluster import KMeans
|
|
|
|
| 8 |
|
| 9 |
-
# ---
|
|
|
|
|
|
|
| 10 |
import ultralytics.nn.tasks as ultralytics_tasks
|
| 11 |
torch.serialization.add_safe_globals([ultralytics_tasks.DetectionModel])
|
| 12 |
-
# -----------------------------------
|
| 13 |
-
|
| 14 |
-
from ultralytics import YOLO
|
| 15 |
-
|
| 16 |
|
| 17 |
-
# --------------------------------------------
|
| 18 |
-
# ⚙️
|
| 19 |
-
# --------------------------------------------
|
| 20 |
MODEL_PATH = "yolov8n.pt"
|
| 21 |
model = YOLO(MODEL_PATH)
|
| 22 |
|
| 23 |
VEHICLE_CLASSES = [2, 3, 5, 7] # car, motorcycle, bus, truck
|
| 24 |
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
#
|
| 28 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
class Track:
|
| 30 |
-
def __init__(self,
|
| 31 |
self.id = track_id
|
| 32 |
-
self.
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
self.trace = []
|
| 44 |
self.vel_history = []
|
| 45 |
|
| 46 |
-
def get_centroid(self, bbox):
|
| 47 |
-
x1,y1,x2,y2 = bbox
|
| 48 |
-
return [(x1+x2)/2,(y1+y2)/2]
|
| 49 |
-
|
| 50 |
def predict(self):
|
| 51 |
self.kf.predict()
|
| 52 |
-
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
cx, cy = self.kf.x[:2].reshape(2)
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
self.
|
| 62 |
|
| 63 |
-
self.
|
| 64 |
-
|
|
|
|
| 65 |
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
def compute_dominant_direction(all_velocities):
|
| 71 |
-
if len(all_velocities) <
|
| 72 |
-
return np.array([0, -1])
|
| 73 |
|
| 74 |
V = np.array(all_velocities)
|
| 75 |
-
|
| 76 |
-
# Filter out tiny noise
|
| 77 |
mags = np.linalg.norm(V, axis=1)
|
| 78 |
-
V = V[mags > 0.
|
| 79 |
if len(V) < 10:
|
| 80 |
return np.array([0, -1])
|
| 81 |
|
| 82 |
-
# Normalize velocities
|
| 83 |
Vn = V / (np.linalg.norm(V, axis=1, keepdims=True) + 1e-6)
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
labels =
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
-
counts = np.bincount(labels)
|
| 91 |
-
dominant_cluster = np.argmax(counts)
|
| 92 |
|
| 93 |
-
dominant_vec = Vn[labels == dominant_cluster].mean(axis=0)
|
| 94 |
-
dominant_vec /= (np.linalg.norm(dominant_vec) + 1e-6)
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# ---------------------------------------------------------
|
| 100 |
# 🎥 MAIN PROCESSOR
|
| 101 |
-
#
|
| 102 |
def process_video(video_path):
|
| 103 |
cap = cv2.VideoCapture(video_path)
|
| 104 |
fps = cap.get(cv2.CAP_PROP_FPS) or 25
|
| 105 |
-
|
| 106 |
-
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
| 110 |
|
| 111 |
tracks = []
|
| 112 |
next_id = 0
|
| 113 |
trajectories = {}
|
| 114 |
-
all_velocities = []
|
| 115 |
-
|
| 116 |
-
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 117 |
-
pbar = tqdm(total=total_frames if total_frames>0 else 100, desc="Processing")
|
| 118 |
|
| 119 |
frame_count = 0
|
| 120 |
-
|
|
|
|
| 121 |
|
| 122 |
while True:
|
| 123 |
-
|
| 124 |
-
if not
|
| 125 |
break
|
| 126 |
|
| 127 |
frame_count += 1
|
| 128 |
|
| 129 |
-
#
|
| 130 |
results = model(frame, verbose=False)[0]
|
| 131 |
-
|
| 132 |
-
for
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
if
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
for j, det in enumerate(detections):
|
| 158 |
-
if j not in assigned:
|
| 159 |
-
trk = Track(det, next_id)
|
| 160 |
-
next_id += 1
|
| 161 |
-
trk.update(det)
|
| 162 |
-
tracks.append(trk)
|
| 163 |
-
|
| 164 |
-
# --- COLLECT VELOCITIES FOR DOMINANT FLOW ---
|
| 165 |
-
if frame_count < int(fps * 4): # first 4 seconds for learning
|
| 166 |
-
for trk in tracks:
|
| 167 |
-
if len(trk.vel_history) > 1:
|
| 168 |
-
all_velocities.append(trk.vel_history[-1])
|
| 169 |
-
|
| 170 |
-
# Compute dominant flow once enough samples are available
|
| 171 |
-
if frame_count == int(fps * 4):
|
| 172 |
-
dominant_vector = compute_dominant_direction(all_velocities)
|
| 173 |
-
else:
|
| 174 |
-
# Fallback if video too short
|
| 175 |
-
if dominant_vector is None:
|
| 176 |
-
dominant_vector = compute_dominant_direction(all_velocities)
|
| 177 |
-
|
| 178 |
-
# --- DRAW OUTPUT ---
|
| 179 |
-
for trk in tracks:
|
| 180 |
-
if len(trk.trace) < 2:
|
| 181 |
continue
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
vx, vy = trk.vel_history[-1]
|
| 188 |
-
mv = np.array([vx, vy])
|
| 189 |
-
else:
|
| 190 |
-
mv = np.array([0, 0])
|
| 191 |
|
| 192 |
-
|
| 193 |
|
| 194 |
-
# cosine similarity with dominant direction
|
| 195 |
-
if dominant_vector is not None:
|
| 196 |
-
cos_sim = float(np.dot(mv_norm, dominant_vector))
|
| 197 |
-
else:
|
| 198 |
-
cos_sim = 1.0
|
| 199 |
-
|
| 200 |
-
# wrong-way logic
|
| 201 |
if cos_sim < -0.3:
|
| 202 |
-
color = (0,
|
| 203 |
-
label = f"ID:{
|
| 204 |
elif cos_sim < 0.1:
|
| 205 |
-
color = (0,
|
| 206 |
-
label = f"ID:{
|
| 207 |
else:
|
| 208 |
-
color = (0,
|
| 209 |
-
label = f"ID:{
|
| 210 |
|
| 211 |
-
|
| 212 |
-
cv2.circle(frame, (x, y), 4, color, -1)
|
| 213 |
-
cv2.putText(frame, label, (x-10, y-10),
|
| 214 |
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
|
|
|
| 215 |
|
| 216 |
-
for i in range(1, len(
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
color, 1)
|
| 221 |
|
| 222 |
-
trajectories[
|
| 223 |
|
| 224 |
-
|
| 225 |
-
pbar.update(1)
|
| 226 |
|
| 227 |
cap.release()
|
| 228 |
-
|
| 229 |
-
pbar.close()
|
| 230 |
|
| 231 |
-
#
|
| 232 |
-
|
| 233 |
-
with open(
|
| 234 |
json.dump(trajectories, f)
|
| 235 |
|
| 236 |
-
return
|
| 237 |
-
|
| 238 |
|
| 239 |
|
| 240 |
-
#
|
| 241 |
-
#
|
| 242 |
-
#
|
| 243 |
def run_app(video_file):
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
if isinstance(video_file, dict) and "name" in video_file:
|
| 247 |
-
src_path = video_file["name"]
|
| 248 |
-
else:
|
| 249 |
-
src_path = video_file
|
| 250 |
-
with open(src_path, "rb") as src, open(temp_path, "wb") as dst:
|
| 251 |
dst.write(src.read())
|
| 252 |
|
| 253 |
-
|
| 254 |
-
out_path, json_path = process_video(
|
| 255 |
-
|
| 256 |
|
| 257 |
summary = {
|
| 258 |
-
"total_time_sec": round(
|
| 259 |
-
"
|
| 260 |
-
"
|
| 261 |
}
|
| 262 |
|
| 263 |
return out_path, json.load(open(json_path)), summary
|
| 264 |
|
| 265 |
|
| 266 |
-
#
|
| 267 |
-
# 🖥️
|
| 268 |
-
#
|
| 269 |
-
description_text = """
|
| 270 |
-
### 🚦 Dominant Flow Tracker (Stage 1)
|
| 271 |
-
Now with **Auto-Learn Wrong-Way Detection**
|
| 272 |
-
- YOLOv8 + Kalman Tracking
|
| 273 |
-
- Auto-dominant direction estimation
|
| 274 |
-
- Wrong-Way annotation (RED)
|
| 275 |
-
"""
|
| 276 |
-
|
| 277 |
demo = gr.Interface(
|
| 278 |
fn=run_app,
|
| 279 |
inputs=gr.Video(label="Upload Video (.mp4)"),
|
| 280 |
outputs=[
|
| 281 |
-
gr.Video(label="
|
| 282 |
-
gr.JSON(label="
|
| 283 |
-
gr.JSON(label="Summary
|
| 284 |
],
|
| 285 |
-
title="🚗 Stage-1
|
| 286 |
-
description=
|
| 287 |
)
|
| 288 |
|
| 289 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import torch
|
| 2 |
import gradio as gr
|
| 3 |
import cv2, os, numpy as np, tempfile, time, json
|
|
|
|
| 4 |
from scipy.optimize import linear_sum_assignment
|
| 5 |
+
from filterpy.kalman import KalmanFilter
|
| 6 |
from sklearn.cluster import KMeans
|
| 7 |
+
from ultralytics import YOLO
|
| 8 |
|
| 9 |
+
# --------------------------------------------
|
| 10 |
+
# 🔧 Safe-load fix for PyTorch 2.6
|
| 11 |
+
# --------------------------------------------
|
| 12 |
import ultralytics.nn.tasks as ultralytics_tasks
|
| 13 |
torch.serialization.add_safe_globals([ultralytics_tasks.DetectionModel])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# --------------------------------------------
|
| 16 |
+
# ⚙️ YOLO model
|
| 17 |
+
# --------------------------------------------
|
| 18 |
MODEL_PATH = "yolov8n.pt"
|
| 19 |
model = YOLO(MODEL_PATH)
|
| 20 |
|
| 21 |
VEHICLE_CLASSES = [2, 3, 5, 7] # car, motorcycle, bus, truck
|
| 22 |
|
| 23 |
|
| 24 |
+
# ============================================
|
| 25 |
+
# 📌 IOU Utility
|
| 26 |
+
# ============================================
|
| 27 |
+
def iou(boxA, boxB):
|
| 28 |
+
xA = max(boxA[0], boxB[0])
|
| 29 |
+
yA = max(boxA[1], boxB[1])
|
| 30 |
+
xB = min(boxA[2], boxB[2])
|
| 31 |
+
yB = min(boxA[3], boxB[3])
|
| 32 |
+
|
| 33 |
+
inter = max(0, xB - xA) * max(0, yB - yA)
|
| 34 |
+
if inter == 0:
|
| 35 |
+
return 0.0
|
| 36 |
+
|
| 37 |
+
areaA = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
|
| 38 |
+
areaB = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
|
| 39 |
+
|
| 40 |
+
return inter / (areaA + areaB - inter + 1e-6)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ============================================
|
| 44 |
+
# 🟦 ByteTrack Track Object
|
| 45 |
+
# ============================================
|
| 46 |
class Track:
|
| 47 |
+
def __init__(self, det, track_id):
|
| 48 |
self.id = track_id
|
| 49 |
+
self.bbox = det[:4].copy()
|
| 50 |
+
|
| 51 |
+
self.kf = KalmanFilter(dim_x=8, dim_z=4)
|
| 52 |
+
dt = 1
|
| 53 |
+
self.kf.F = np.array([
|
| 54 |
+
[1,0,0,0, dt,0,0,0],
|
| 55 |
+
[0,1,0,0, 0,dt,0,0],
|
| 56 |
+
[0,0,1,0, 0,0,dt,0],
|
| 57 |
+
[0,0,0,1, 0,0,0,dt],
|
| 58 |
+
[0,0,0,0, 1,0,0,0],
|
| 59 |
+
[0,0,0,0, 0,1,0,0],
|
| 60 |
+
[0,0,0,0, 0,0,1,0],
|
| 61 |
+
[0,0,0,0, 0,0,0,1],
|
| 62 |
+
])
|
| 63 |
+
self.kf.H = np.eye(4, 8)
|
| 64 |
+
self.kf.P *= 10
|
| 65 |
+
|
| 66 |
+
z = np.array([
|
| 67 |
+
det[0], det[1], det[2], det[3]
|
| 68 |
+
])
|
| 69 |
+
self.kf.x[:4] = z.reshape(4,1)
|
| 70 |
+
|
| 71 |
+
self.hits = 0
|
| 72 |
+
self.age = 0
|
| 73 |
+
self.time_since_update = 0
|
| 74 |
+
|
| 75 |
self.trace = []
|
| 76 |
self.vel_history = []
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
def predict(self):
|
| 79 |
self.kf.predict()
|
| 80 |
+
self.age += 1
|
| 81 |
+
self.time_since_update += 1
|
| 82 |
|
| 83 |
+
pred_bbox = self.kf.x[:4].reshape(-1)
|
| 84 |
+
self.bbox = pred_bbox
|
| 85 |
+
return pred_bbox
|
|
|
|
| 86 |
|
| 87 |
+
def update(self, det):
|
| 88 |
+
z = np.array([det[0], det[1], det[2], det[3]])
|
| 89 |
+
self.kf.update(z)
|
| 90 |
|
| 91 |
+
self.bbox = self.kf.x[:4].reshape(-1)
|
| 92 |
+
self.time_since_update = 0
|
| 93 |
+
self.hits += 1
|
| 94 |
|
| 95 |
+
vx, vy = self.kf.x[4], self.kf.x[5]
|
| 96 |
+
self.vel_history.append([float(vx), float(vy)])
|
| 97 |
|
| 98 |
+
cx = (self.bbox[0] + self.bbox[2]) / 2
|
| 99 |
+
cy = (self.bbox[1] + self.bbox[3]) / 2
|
| 100 |
+
self.trace.append([float(cx), float(cy)])
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# ============================================
|
| 104 |
+
# 🧠 ByteTrack Association
|
| 105 |
+
# ============================================
|
| 106 |
+
def byte_track(tracks, detections, next_id):
|
| 107 |
+
high_conf = [d for d in detections if d[4] >= 0.5]
|
| 108 |
+
low_conf = [d for d in detections if 0.1 <= d[4] < 0.5]
|
| 109 |
+
|
| 110 |
+
# -------------------------
|
| 111 |
+
# STEP 1 – Match high-conf
|
| 112 |
+
# -------------------------
|
| 113 |
+
unmatched_tracks = list(range(len(tracks)))
|
| 114 |
+
unmatched_dets = list(range(len(high_conf)))
|
| 115 |
+
|
| 116 |
+
if tracks and high_conf:
|
| 117 |
+
cost = np.zeros((len(tracks), len(high_conf)))
|
| 118 |
+
for i, trk in enumerate(tracks):
|
| 119 |
+
for j, det in enumerate(high_conf):
|
| 120 |
+
cost[i, j] = 1 - iou(trk.bbox, det[:4])
|
| 121 |
+
|
| 122 |
+
row, col = linear_sum_assignment(cost)
|
| 123 |
+
|
| 124 |
+
matched = set()
|
| 125 |
+
for r, c in zip(row, col):
|
| 126 |
+
if cost[r, c] < 0.8: # iou > 0.2
|
| 127 |
+
tracks[r].update(high_conf[c])
|
| 128 |
+
matched.add((r, c))
|
| 129 |
+
|
| 130 |
+
# remaining unmatched indices
|
| 131 |
+
unmatched_tracks = [i for i in range(len(tracks)) if i not in [m[0] for m in matched]]
|
| 132 |
+
unmatched_dets = [j for j in range(len(high_conf)) if j not in [m[1] for m in matched]]
|
| 133 |
+
|
| 134 |
+
# --------------------------------
|
| 135 |
+
# STEP 2 – Second match with low-conf
|
| 136 |
+
# --------------------------------
|
| 137 |
+
if unmatched_tracks and low_conf:
|
| 138 |
+
cost = np.zeros((len(unmatched_tracks), len(low_conf)))
|
| 139 |
+
for i, t_idx in enumerate(unmatched_tracks):
|
| 140 |
+
for j, det in enumerate(low_conf):
|
| 141 |
+
cost[i, j] = 1 - iou(tracks[t_idx].bbox, det[:4])
|
| 142 |
+
|
| 143 |
+
row, col = linear_sum_assignment(cost)
|
| 144 |
+
matched2 = set()
|
| 145 |
+
for r, c in zip(row, col):
|
| 146 |
+
if cost[r, c] < 0.8:
|
| 147 |
+
trk_idx = unmatched_tracks[r]
|
| 148 |
+
tracks[trk_idx].update(low_conf[c])
|
| 149 |
+
matched2.add((trk_idx, c))
|
| 150 |
+
|
| 151 |
+
unmatched_tracks = [t for t in unmatched_tracks if t not in [m[0] for m in matched2]]
|
| 152 |
+
|
| 153 |
+
# --------------------------------
|
| 154 |
+
# STEP 3 – Create new tracks
|
| 155 |
+
# --------------------------------
|
| 156 |
+
for d in high_conf:
|
| 157 |
+
if d not in high_conf: continue
|
| 158 |
+
for idx in unmatched_dets:
|
| 159 |
+
trk = Track(high_conf[idx], next_id)
|
| 160 |
+
next_id += 1
|
| 161 |
+
tracks.append(trk)
|
| 162 |
+
|
| 163 |
+
# --------------------------------
|
| 164 |
+
# STEP 4 – Remove dead tracks
|
| 165 |
+
# --------------------------------
|
| 166 |
+
tracks = [t for t in tracks if t.time_since_update <= 20]
|
| 167 |
+
|
| 168 |
+
return tracks, next_id
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# ============================================
|
| 172 |
+
# 🧠 Auto-Learn Dominant Flow
|
| 173 |
+
# ============================================
|
| 174 |
def compute_dominant_direction(all_velocities):
|
| 175 |
+
if len(all_velocities) < 15:
|
| 176 |
+
return np.array([0, -1])
|
| 177 |
|
| 178 |
V = np.array(all_velocities)
|
|
|
|
|
|
|
| 179 |
mags = np.linalg.norm(V, axis=1)
|
| 180 |
+
V = V[mags > 0.3]
|
| 181 |
if len(V) < 10:
|
| 182 |
return np.array([0, -1])
|
| 183 |
|
|
|
|
| 184 |
Vn = V / (np.linalg.norm(V, axis=1, keepdims=True) + 1e-6)
|
| 185 |
|
| 186 |
+
km = KMeans(n_clusters=2, n_init=10)
|
| 187 |
+
labels = km.fit_predict(Vn)
|
| 188 |
+
dominant = Vn[labels == labels.argmax()].mean(axis=0)
|
| 189 |
+
dominant /= (np.linalg.norm(dominant) + 1e-6)
|
| 190 |
|
| 191 |
+
return dominant
|
|
|
|
|
|
|
| 192 |
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
# ============================================
|
|
|
|
|
|
|
|
|
|
| 195 |
# 🎥 MAIN PROCESSOR
|
| 196 |
+
# ============================================
|
| 197 |
def process_video(video_path):
|
| 198 |
cap = cv2.VideoCapture(video_path)
|
| 199 |
fps = cap.get(cv2.CAP_PROP_FPS) or 25
|
| 200 |
+
W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 201 |
+
H = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 202 |
|
| 203 |
+
out_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
|
| 204 |
+
writer = cv2.VideoWriter(out_file.name,
|
| 205 |
+
cv2.VideoWriter_fourcc(*"mp4v"),
|
| 206 |
+
fps, (W, H))
|
| 207 |
|
| 208 |
tracks = []
|
| 209 |
next_id = 0
|
| 210 |
trajectories = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
frame_count = 0
|
| 213 |
+
all_velocities = []
|
| 214 |
+
dominant_vec = None
|
| 215 |
|
| 216 |
while True:
|
| 217 |
+
ok, frame = cap.read()
|
| 218 |
+
if not ok:
|
| 219 |
break
|
| 220 |
|
| 221 |
frame_count += 1
|
| 222 |
|
| 223 |
+
# YOLO
|
| 224 |
results = model(frame, verbose=False)[0]
|
| 225 |
+
dets = []
|
| 226 |
+
for b in results.boxes:
|
| 227 |
+
if int(b.cls) in VEHICLE_CLASSES:
|
| 228 |
+
x1,y1,x2,y2 = b.xyxy[0].cpu().numpy()
|
| 229 |
+
conf = float(b.conf)
|
| 230 |
+
dets.append([x1, y1, x2, y2, conf])
|
| 231 |
+
dets = np.array(dets)
|
| 232 |
+
|
| 233 |
+
# ByteTrack update
|
| 234 |
+
tracks, next_id = byte_track(tracks, dets, next_id)
|
| 235 |
+
|
| 236 |
+
# collect velocities
|
| 237 |
+
if frame_count < fps * 4:
|
| 238 |
+
for t in tracks:
|
| 239 |
+
if len(t.vel_history) > 1:
|
| 240 |
+
all_velocities.append(t.vel_history[-1])
|
| 241 |
+
|
| 242 |
+
if frame_count == fps * 4:
|
| 243 |
+
dominant_vec = compute_dominant_direction(all_velocities)
|
| 244 |
+
|
| 245 |
+
if dominant_vec is None:
|
| 246 |
+
dominant_vec = np.array([0, -1])
|
| 247 |
+
|
| 248 |
+
# DRAW
|
| 249 |
+
for t in tracks:
|
| 250 |
+
if len(t.trace) < 2:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
continue
|
| 252 |
|
| 253 |
+
cx, cy = t.trace[-1]
|
| 254 |
+
vx, vy = t.vel_history[-1] if t.vel_history else (0, 0)
|
| 255 |
+
mv = np.array([vx, vy])
|
| 256 |
+
mv_n = mv / (np.linalg.norm(mv) + 1e-6)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
+
cos_sim = np.dot(mv_n, dominant_vec)
|
| 259 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
if cos_sim < -0.3:
|
| 261 |
+
color = (0,0,255)
|
| 262 |
+
label = f"ID:{t.id} WRONG"
|
| 263 |
elif cos_sim < 0.1:
|
| 264 |
+
color = (0,140,255)
|
| 265 |
+
label = f"ID:{t.id} ?"
|
| 266 |
else:
|
| 267 |
+
color = (0,255,0)
|
| 268 |
+
label = f"ID:{t.id}"
|
| 269 |
|
| 270 |
+
cv2.putText(frame, label, (int(cx)-10, int(cy)-10),
|
|
|
|
|
|
|
| 271 |
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
| 272 |
+
cv2.circle(frame, (int(cx), int(cy)), 4, color, -1)
|
| 273 |
|
| 274 |
+
for i in range(1, len(t.trace)):
|
| 275 |
+
x1, y1 = t.trace[i-1]
|
| 276 |
+
x2, y2 = t.trace[i]
|
| 277 |
+
cv2.line(frame, (int(x1),int(y1)), (int(x2),int(y2)), color, 2)
|
|
|
|
| 278 |
|
| 279 |
+
trajectories[t.id] = t.trace
|
| 280 |
|
| 281 |
+
writer.write(frame)
|
|
|
|
| 282 |
|
| 283 |
cap.release()
|
| 284 |
+
writer.release()
|
|
|
|
| 285 |
|
| 286 |
+
# save JSON
|
| 287 |
+
jfile = tempfile.NamedTemporaryFile(delete=False, suffix=".json")
|
| 288 |
+
with open(jfile.name, "w") as f:
|
| 289 |
json.dump(trajectories, f)
|
| 290 |
|
| 291 |
+
return out_file.name, jfile.name
|
|
|
|
| 292 |
|
| 293 |
|
| 294 |
+
# ============================================
|
| 295 |
+
# 🎛️ Gradio Wrapper
|
| 296 |
+
# ============================================
|
| 297 |
def run_app(video_file):
|
| 298 |
+
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
|
| 299 |
+
with open(video_file.name, "rb") as src, open(temp, "wb") as dst:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
dst.write(src.read())
|
| 301 |
|
| 302 |
+
t1 = time.time()
|
| 303 |
+
out_path, json_path = process_video(temp)
|
| 304 |
+
t2 = time.time()
|
| 305 |
|
| 306 |
summary = {
|
| 307 |
+
"total_time_sec": round(t2-t1, 2),
|
| 308 |
+
"avg_fps": round(cv2.VideoCapture(temp).get(cv2.CAP_PROP_FPS), 2),
|
| 309 |
+
"num_tracks": len(json.load(open(json_path)))
|
| 310 |
}
|
| 311 |
|
| 312 |
return out_path, json.load(open(json_path)), summary
|
| 313 |
|
| 314 |
|
| 315 |
+
# ============================================
|
| 316 |
+
# 🖥️ Gradio UI
|
| 317 |
+
# ============================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
demo = gr.Interface(
|
| 319 |
fn=run_app,
|
| 320 |
inputs=gr.Video(label="Upload Video (.mp4)"),
|
| 321 |
outputs=[
|
| 322 |
+
gr.Video(label="ByteTrack Output (Wrong-Way Highlighted)"),
|
| 323 |
+
gr.JSON(label="Trajectory JSON"),
|
| 324 |
+
gr.JSON(label="Summary")
|
| 325 |
],
|
| 326 |
+
title="🚗 Stage-1 ByteTrack-Based Tracker + Wrong-Way Detector",
|
| 327 |
+
description="High-accuracy tracking, zero ID switching, auto-learn dominant flow."
|
| 328 |
)
|
| 329 |
|
| 330 |
if __name__ == "__main__":
|