Spaces:
Sleeping
Sleeping
File size: 20,744 Bytes
29088fd | 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 | """
Violation rules as pure, model-free logic.
Every rule here consumes plain tracks (id + bbox + timestamp) and scene geometry,
so it can be unit-tested with synthetic trajectories (see tests/). The detection
engine is responsible only for producing those tracks from images.
Time is measured in seconds (video timestamp), never in frame counts, so results
do not change with frame stride or camera FPS.
"""
from __future__ import annotations
from collections import Counter, defaultdict, deque
from dataclasses import dataclass, field
from typing import Any, Deque, Iterable, Sequence
import cv2
import numpy as np
from core.geometry import (
BBox,
Point,
bbox_bottom_center,
bbox_center,
bbox_diag,
bbox_iou,
containment,
expand_bbox,
point_in_polygon,
projection_t,
signed_side,
distance_to_line,
unit,
)
# Canonical violation names (used everywhere: UI, DB, PDF, tests)
HELMET = "No Helmet"
TRIPLE = "Triple Riding"
SEATBELT = "No Seatbelt"
WRONG_SIDE = "Wrong-side Driving"
STOP_LINE = "Stop-line Violation"
RED_LIGHT = "Red-light Jump"
PARKING = "Illegal Parking"
ALL_VIOLATIONS = (HELMET, TRIPLE, SEATBELT, WRONG_SIDE, STOP_LINE, RED_LIGHT, PARKING)
@dataclass
class RuleHit:
track_id: int
violation: str
confidence: float
reason: str
metadata: dict[str, Any] = field(default_factory=dict)
# ---------------------------------------------------------------------------
# Track history
# ---------------------------------------------------------------------------
class TrackHistory:
"""Per-track (timestamp, bbox) history used for motion estimates."""
def __init__(self, horizon_s: float = 6.0, max_points: int = 240) -> None:
self.horizon_s = horizon_s
self.max_points = max_points
self._data: dict[int, Deque[tuple[float, BBox]]] = defaultdict(lambda: deque(maxlen=self.max_points))
self.first_seen: dict[int, float] = {}
self.last_seen: dict[int, float] = {}
def update(self, track_id: int, bbox: BBox, t: float) -> None:
if track_id < 0:
return
dq = self._data[track_id]
dq.append((t, tuple(int(v) for v in bbox)))
while dq and t - dq[0][0] > self.horizon_s:
dq.popleft()
self.first_seen.setdefault(track_id, t)
self.last_seen[track_id] = t
def prune(self, now: float, max_age_s: float = 3.0) -> list[int]:
stale = [tid for tid, last in self.last_seen.items() if now - last > max_age_s]
for tid in stale:
self._data.pop(tid, None)
self.last_seen.pop(tid, None)
self.first_seen.pop(tid, None)
return stale
def points(self, track_id: int) -> list[tuple[float, BBox]]:
return list(self._data.get(track_id, ()))
def age(self, track_id: int) -> float:
if track_id not in self.first_seen:
return 0.0
return self.last_seen[track_id] - self.first_seen[track_id]
def motion(self, track_id: int, window_s: float) -> tuple[np.ndarray, float, float] | None:
"""
Robust displacement of the bottom-centre over the last ``window_s`` seconds.
Uses the median of the first and last thirds of the window to suppress
detector jitter. Returns (vector, displacement_px, duration_s).
"""
pts = self._data.get(track_id)
if not pts or len(pts) < 4:
return None
t_end = pts[-1][0]
window = [(t, b) for t, b in pts if t_end - t <= window_s]
if len(window) < 4:
return None
k = max(1, len(window) // 3)
start = np.median([bbox_bottom_center(b) for _, b in window[:k]], axis=0)
end = np.median([bbox_bottom_center(b) for _, b in window[-k:]], axis=0)
vec = end - start
duration = window[-1][0] - window[0][0]
return vec, float(np.linalg.norm(vec)), float(duration)
# ---------------------------------------------------------------------------
# Wrong-side driving
# ---------------------------------------------------------------------------
@dataclass
class LaneZone:
polygon: np.ndarray # pixel coordinates, shape (N, 2)
direction: np.ndarray # unit vector of legal travel in image space
name: str = "lane"
class WrongSideRule:
"""
A vehicle is driving on the wrong side when, inside a lane zone, its motion
points against the lane's legal direction (cosine < ``cos_threshold``) for
``confirm_evals`` consecutive evaluations and it has moved a meaningful
distance (relative to its own size, so far-away vehicles are handled too).
Stationary / crawling vehicles never trigger.
"""
def __init__(self, lanes: Sequence[LaneZone], window_s: float = 1.5, cos_threshold: float = -0.5,
min_disp_frac: float = 0.35, min_disp_px: float = 12.0, confirm_evals: int = 3) -> None:
self.lanes = list(lanes)
self.window_s = window_s
self.cos_threshold = cos_threshold
self.min_disp_frac = min_disp_frac
self.min_disp_px = min_disp_px
self.confirm_evals = confirm_evals
self._streak: dict[int, int] = defaultdict(int)
self.flagged: set[int] = set()
self.last_debug: dict[int, dict[str, Any]] = {}
def lane_for(self, point: Point) -> LaneZone | None:
for lane in self.lanes:
if point_in_polygon(point, lane.polygon):
return lane
return None
def update(self, track_id: int, bbox: BBox, history: TrackHistory) -> RuleHit | None:
if not self.lanes or track_id < 0:
return None
lane = self.lane_for(bbox_bottom_center(bbox))
motion = history.motion(track_id, self.window_s)
if lane is None or motion is None:
self._streak[track_id] = 0
return None
vec, disp, duration = motion
min_disp = max(self.min_disp_px, self.min_disp_frac * (bbox[3] - bbox[1]))
if disp < min_disp or duration <= 0:
self._streak[track_id] = 0
self.last_debug[track_id] = {"lane": lane.name, "disp_px": round(disp, 1), "moving": False}
return None
cos = float(unit(vec) @ lane.direction)
self.last_debug[track_id] = {"lane": lane.name, "disp_px": round(disp, 1), "cos": round(cos, 3)}
if cos < self.cos_threshold:
self._streak[track_id] += 1
else:
self._streak[track_id] = 0
if self._streak[track_id] >= self.confirm_evals and track_id not in self.flagged:
self.flagged.add(track_id)
confidence = float(min(0.99, 0.6 + 0.4 * (-cos)))
return RuleHit(track_id, WRONG_SIDE, confidence,
f"Moving against lane '{lane.name}' direction (cos={cos:.2f}, {disp:.0f}px in {duration:.1f}s)",
{"lane": lane.name, "cos": cos, "displacement_px": disp, "duration_s": duration,
"motion": [float(vec[0]), float(vec[1])]})
return None
def forget(self, track_id: int) -> None:
self._streak.pop(track_id, None)
self.last_debug.pop(track_id, None)
# ---------------------------------------------------------------------------
# Stop line / red light
# ---------------------------------------------------------------------------
@dataclass
class StopLine:
a: Point
b: Point
flow: np.ndarray # unit vector: direction traffic moves when it crosses the line legally
def before_sign(self) -> float:
mid = ((self.a[0] + self.b[0]) / 2.0, (self.a[1] + self.b[1]) / 2.0)
probe = (mid[0] - self.flow[0] * 10.0, mid[1] - self.flow[1] * 10.0)
s = signed_side(probe, self.a, self.b)
return 1.0 if s >= 0 else -1.0
def position(self, p: Point) -> tuple[float, float]:
"""(signed distance: +before / -after, projection t along the line)."""
dist = distance_to_line(p, self.a, self.b)
side = signed_side(p, self.a, self.b) * self.before_sign()
return (dist if side >= 0 else -dist), projection_t(p, self.a, self.b)
class StopLineRule:
"""
Video logic
* Stop-line violation: the vehicle's ground point crosses from the approach
side to the far side while the signal is RED.
* Red-light jump: after such a crossing the vehicle keeps going and travels
``run_frac`` x its own height past the line (it did not just creep over).
A vehicle that was already past the line when the signal turned red is not
flagged. Crossings outside the painted segment (t outside [-0.15, 1.15]) are
ignored, so cross traffic and adjacent roads do not trigger.
Image logic (``evaluate_static``)
* With a RED signal, a vehicle whose ground point is past the line by more
than ``tolerance_px`` but less than ``static_max_frac`` of the frame height
is reported as a stop-line violation (lower confidence, flagged as static).
"""
def __init__(self, line: StopLine, tolerance_px: float = 4.0, run_frac: float = 0.9,
static_max_frac: float = 0.25) -> None:
self.line = line
self.tolerance_px = tolerance_px
self.run_frac = run_frac
self.static_max_frac = static_max_frac
self._last_side: dict[int, int] = {}
self._crossed_on_red: dict[int, float] = {}
self.flagged_stop: set[int] = set()
self.flagged_red: set[int] = set()
def _side(self, d: float) -> int:
if d > self.tolerance_px:
return 1 # before
if d < -self.tolerance_px:
return -1 # after
return 0
def update(self, track_id: int, bbox: BBox, signal: str) -> list[RuleHit]:
hits: list[RuleHit] = []
if track_id < 0:
return hits
p = bbox_bottom_center(bbox)
d, t = self.line.position(p)
side = self._side(d)
prev = self._last_side.get(track_id)
within = -0.15 <= t <= 1.15
if side != 0:
self._last_side[track_id] = side
if prev == 1 and side == -1 and within and signal == "RED" and track_id not in self.flagged_stop:
self.flagged_stop.add(track_id)
self._crossed_on_red[track_id] = 0.0
hits.append(RuleHit(track_id, STOP_LINE, 0.9, "Crossed the stop line while the signal was RED",
{"distance_px": d, "line_t": t, "mode": "crossing"}))
if track_id in self._crossed_on_red and track_id not in self.flagged_red:
height = max(1.0, bbox[3] - bbox[1])
if -d > self.run_frac * height:
self.flagged_red.add(track_id)
hits.append(RuleHit(track_id, RED_LIGHT, 0.92,
"Continued through the junction after crossing on RED",
{"distance_past_line_px": -d}))
return hits
def evaluate_static(self, track_id: int, bbox: BBox, signal: str, frame_height: int) -> RuleHit | None:
if signal != "RED":
return None
d, t = self.line.position(bbox_bottom_center(bbox))
if not (-0.15 <= t <= 1.15):
return None
if -d > self.tolerance_px and -d < self.static_max_frac * frame_height:
return RuleHit(track_id, STOP_LINE, 0.7, "Vehicle is past the stop line while the signal is RED",
{"distance_past_line_px": -d, "line_t": t, "mode": "static"})
return None
def forget(self, track_id: int) -> None:
self._last_side.pop(track_id, None)
self._crossed_on_red.pop(track_id, None)
# ---------------------------------------------------------------------------
# Illegal parking
# ---------------------------------------------------------------------------
@dataclass
class _ParkState:
anchor: Point
since: float
bbox: BBox
last_t: float
flagged: bool = False
class ParkingRule:
"""
A vehicle is illegally parked when its ground point stays inside a no-parking
zone and it remains stationary (within ``tol_frac`` x its diagonal of an anchor
position) for ``dwell_s`` seconds.
Tracker ID switches are common for parked vehicles (occlusion by passing
traffic). When a stationary track disappears, its state is kept as a "ghost"
for ``ghost_ttl_s``; a new track whose box overlaps it (IoU >= ``inherit_iou``)
inherits the accumulated dwell time.
"""
def __init__(self, zones: Sequence[np.ndarray], dwell_s: float = 60.0, tol_frac: float = 0.12,
min_tol_px: float = 6.0, ghost_ttl_s: float = 8.0, inherit_iou: float = 0.45) -> None:
self.zones = list(zones)
self.dwell_s = dwell_s
self.tol_frac = tol_frac
self.min_tol_px = min_tol_px
self.ghost_ttl_s = ghost_ttl_s
self.inherit_iou = inherit_iou
self.state: dict[int, _ParkState] = {}
self.ghosts: list[_ParkState] = []
def in_zone(self, bbox: BBox) -> bool:
p = bbox_bottom_center(bbox)
return any(point_in_polygon(p, z) for z in self.zones)
def dwell(self, track_id: int, now: float) -> float:
st = self.state.get(track_id)
return 0.0 if st is None else now - st.since
def update(self, tracks: Iterable[tuple[int, BBox]], now: float) -> list[RuleHit]:
hits: list[RuleHit] = []
if not self.zones:
return hits
seen: set[int] = set()
for tid, bbox in tracks:
if tid < 0:
continue
seen.add(tid)
if not self.in_zone(bbox):
self.state.pop(tid, None)
continue
center = bbox_center(bbox)
st = self.state.get(tid)
if st is None:
st = self._inherit(bbox, now) or _ParkState(center, now, bbox, now)
self.state[tid] = st
tol = max(self.min_tol_px, self.tol_frac * bbox_diag(bbox))
if np.hypot(center[0] - st.anchor[0], center[1] - st.anchor[1]) > tol:
st.anchor, st.since, st.flagged = center, now, False
st.bbox, st.last_t = bbox, now
dwell = now - st.since
if dwell >= self.dwell_s and not st.flagged:
st.flagged = True
hits.append(RuleHit(tid, PARKING, 0.9 if dwell < 2 * self.dwell_s else 0.95,
f"Stationary in no-parking zone for {dwell:.0f}s",
{"dwell_s": dwell, "threshold_s": self.dwell_s}))
# tracks that vanished become ghosts
for tid in list(self.state):
if tid not in seen:
st = self.state.pop(tid)
if now - st.since > 1.0:
self.ghosts.append(st)
self.ghosts = [g for g in self.ghosts if now - g.last_t <= self.ghost_ttl_s]
return hits
def _inherit(self, bbox: BBox, now: float) -> _ParkState | None:
best, best_iou = None, self.inherit_iou
for g in self.ghosts:
iou = bbox_iou(bbox, g.bbox)
if iou >= best_iou:
best, best_iou = g, iou
if best is not None:
self.ghosts.remove(best)
return _ParkState(best.anchor, best.since, bbox, now, best.flagged)
return None
# ---------------------------------------------------------------------------
# Traffic-light colour
# ---------------------------------------------------------------------------
def classify_traffic_light(crop: np.ndarray | None, min_ratio: float = 0.015) -> tuple[str, dict[str, float]]:
"""
Classify a traffic-light crop as RED / YELLOW / GREEN / UNKNOWN by counting
bright, saturated pixels in each hue band (HSV). Robust to housing colour and
to the lamp layout (vertical, horizontal, countdown displays).
"""
if crop is None or crop.size == 0 or min(crop.shape[:2]) < 3:
return "UNKNOWN", {}
hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
lit = (s >= 80) & (v >= 120)
masks = {
"RED": lit & ((h <= 10) | (h >= 165)),
"YELLOW": lit & (h >= 15) & (h <= 35),
"GREEN": lit & (h >= 45) & (h <= 100),
}
total = float(h.size)
ratios = {k: float(m.sum()) / total for k, m in masks.items()}
best = max(ratios, key=ratios.get)
others = max(v_ for k, v_ in ratios.items() if k != best)
if ratios[best] < min_ratio or ratios[best] < 1.5 * others:
return "UNKNOWN", ratios
return best, ratios
class SignalFilter:
"""Majority vote over the last few non-UNKNOWN readings (suppresses flicker / LED PWM)."""
def __init__(self, window: int = 5) -> None:
self._buf: Deque[str] = deque(maxlen=window)
def update(self, state: str) -> str:
if state != "UNKNOWN":
self._buf.append(state)
if not self._buf:
return "UNKNOWN"
return Counter(self._buf).most_common(1)[0][0]
def reset(self) -> None:
self._buf.clear()
# ---------------------------------------------------------------------------
# Two-wheeler riders (helmet + triple riding)
# ---------------------------------------------------------------------------
@dataclass
class Head:
bbox: BBox
helmet: bool
confidence: float
def nms_heads(heads: Sequence[Head], iou: float = 0.4) -> list[Head]:
"""One physical head can be detected as both Helmet and NoHelmet; keep the stronger."""
kept: list[Head] = []
for h in sorted(heads, key=lambda x: x.confidence, reverse=True):
if all(bbox_iou(h.bbox, k.bbox) <= iou and containment(h.bbox, k.bbox) < 0.7 for k in kept):
kept.append(h)
return kept
def rider_zone(two_wheeler_bbox: BBox) -> BBox:
"""Region where a rider's head can be: the box widened a little and extended upwards."""
return expand_bbox(two_wheeler_bbox, 0.12, 0.30, 0.12, -0.35)
def assign_heads(two_wheelers: Sequence[tuple[int, BBox]], heads: Sequence[Head]) -> dict[int, list[Head]]:
"""
Assign every head to at most one two-wheeler. A head belongs to the vehicle whose
rider zone contains the head centre; ties (dense traffic) go to the vehicle whose
horizontal centre is closest.
"""
out: dict[int, list[Head]] = {tid: [] for tid, _ in two_wheelers}
zones = [(tid, b, rider_zone(b)) for tid, b in two_wheelers]
for head in heads:
cx, cy = bbox_center(head.bbox)
best_tid, best_score = None, None
for tid, b, z in zones:
if not (z[0] <= cx <= z[2] and z[1] <= cy <= z[3]):
continue
width = max(1.0, b[2] - b[0])
score = abs(cx - (b[0] + b[2]) / 2.0) / width
if best_score is None or score < best_score:
best_tid, best_score = tid, score
if best_tid is not None:
out[best_tid].append(head)
return out
# ---------------------------------------------------------------------------
# Temporal confirmation for appearance-based violations (video)
# ---------------------------------------------------------------------------
class TemporalVote:
"""
Appearance violations (helmet, seatbelt, triple riding) are confirmed for a track
only after ``min_hits`` positive frames that make up at least ``min_ratio`` of the
frames where the evidence was observable. Prevents single-frame false alarms.
"""
def __init__(self, min_hits: int = 2, min_ratio: float = 0.35) -> None:
self.min_hits = min_hits
self.min_ratio = min_ratio
self._obs: dict[tuple[int, str], list[float]] = defaultdict(list) # conf or 0.0 for negatives
self.confirmed: set[tuple[int, str]] = set()
def add(self, track_id: int, violation: str, positive_conf: float | None) -> RuleHit | None:
key = (track_id, violation)
self._obs[key].append(positive_conf or 0.0)
if key in self.confirmed:
return None
values = self._obs[key]
pos = [v for v in values if v > 0]
if len(pos) >= self.min_hits and len(pos) / len(values) >= self.min_ratio:
self.confirmed.add(key)
return RuleHit(track_id, violation, float(np.mean(pos)),
f"Seen in {len(pos)}/{len(values)} observations", {"hits": len(pos), "observations": len(values)})
return None
def stats(self, track_id: int, violation: str) -> tuple[int, int]:
values = self._obs.get((track_id, violation), [])
return sum(v > 0 for v in values), len(values)
def forget(self, track_id: int) -> None:
for key in [k for k in self._obs if k[0] == track_id]:
self._obs.pop(key, None)
|