Spaces:
Sleeping
Sleeping
File size: 9,599 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 | """Unit tests for model-free violation rules using synthetic trajectories."""
import numpy as np
import pytest
from core.rules import (
PARKING,
RED_LIGHT,
STOP_LINE,
WRONG_SIDE,
Head,
LaneZone,
ParkingRule,
SignalFilter,
StopLine,
StopLineRule,
TemporalVote,
TrackHistory,
WrongSideRule,
assign_heads,
classify_traffic_light,
nms_heads,
)
FPS = 25.0
def box_at(cx, bottom, w=80, h=60):
return (int(cx - w / 2), int(bottom - h), int(cx + w / 2), int(bottom))
def run_track(rule_update, path, fps=FPS, start_t=0.0):
"""path: list of (cx, bottom). Calls rule_update(bbox, t) and collects hits."""
hits = []
for i, (cx, bottom) in enumerate(path):
out = rule_update(box_at(cx, bottom), start_t + i / fps)
if out:
hits.extend(out if isinstance(out, list) else [out])
return hits
# ---------------------------------------------------------------------------
# Wrong side
# ---------------------------------------------------------------------------
LANE = LaneZone(np.array([[0, 0], [1000, 0], [1000, 1000], [0, 1000]], dtype=np.float32),
np.array([0.0, 1.0]), "southbound") # legal: down the image
def _wrong_side_run(path):
hist, rule = TrackHistory(), WrongSideRule([LANE])
def upd(b, t):
hist.update(7, b, t)
return rule.update(7, b, hist)
return run_track(upd, path)
def test_wrong_side_flags_vehicle_moving_against_lane():
path = [(500, 900 - 6 * i) for i in range(60)] # moving up 6 px/frame
hits = _wrong_side_run(path)
assert [h.violation for h in hits] == [WRONG_SIDE]
def test_wrong_side_ignores_legal_direction():
assert _wrong_side_run([(500, 100 + 6 * i) for i in range(60)]) == []
def test_wrong_side_ignores_stationary_jitter():
rng = np.random.default_rng(0)
path = [(500 + rng.normal(0, 3), 500 + rng.normal(0, 3)) for _ in range(80)]
assert _wrong_side_run(path) == []
def test_wrong_side_ignores_crossing_traffic():
assert _wrong_side_run([(100 + 8 * i, 500) for i in range(60)]) == [] # perpendicular
def test_wrong_side_only_inside_lane_zone():
lane = LaneZone(np.array([[0, 0], [400, 0], [400, 1000], [0, 1000]], dtype=np.float32), np.array([0.0, 1.0]))
hist, rule = TrackHistory(), WrongSideRule([lane])
hits = []
for i in range(60):
b = box_at(700, 900 - 6 * i) # outside lane polygon (x=700)
hist.update(1, b, i / FPS)
if (h := rule.update(1, b, hist)):
hits.append(h)
assert hits == []
def test_wrong_side_reported_once_per_track():
path = [(500, 950 - 6 * i) for i in range(150)]
assert len(_wrong_side_run(path)) == 1
# ---------------------------------------------------------------------------
# Stop line / red light
# ---------------------------------------------------------------------------
# Horizontal stop line at y=500, traffic flows up the image (approach from the bottom).
LINE = StopLine((100.0, 500.0), (900.0, 500.0), np.array([0.0, -1.0]))
def _stop_run(path, signals):
rule = StopLineRule(LINE)
hits = []
for i, (cx, bottom) in enumerate(path):
hits.extend(rule.update(3, box_at(cx, bottom), signals[i]))
return hits
def test_crossing_on_red_is_stop_line_then_red_light_jump():
path = [(500, 700 - 5 * i) for i in range(100)] # crosses y=500 at i=40, continues to y=205
hits = _stop_run(path, ["RED"] * 100)
assert [h.violation for h in hits] == [STOP_LINE, RED_LIGHT]
def test_creeping_over_line_on_red_is_stop_line_only():
path = [(500, 600 - 5 * i) for i in range(25)] + [(500, 480)] * 40 # stops 20 px past the line
hits = _stop_run(path, ["RED"] * len(path))
assert [h.violation for h in hits] == [STOP_LINE]
def test_crossing_on_green_is_legal():
path = [(500, 700 - 5 * i) for i in range(100)]
assert _stop_run(path, ["GREEN"] * 100) == []
def test_vehicle_already_past_line_when_light_turns_red_is_not_flagged():
path = [(500, 400 - 3 * i) for i in range(60)] # starts beyond the line
assert _stop_run(path, ["RED"] * 60) == []
def test_crossing_outside_painted_segment_ignored():
path = [(1300, 700 - 5 * i) for i in range(100)] # x=1300 is far beyond the line end (900)
assert _stop_run(path, ["RED"] * 100) == []
def test_reverse_direction_crossing_ignored():
path = [(500, 300 + 5 * i) for i in range(100)] # moving away from junction, after -> before
assert _stop_run(path, ["RED"] * 100) == []
def test_static_image_check():
rule = StopLineRule(LINE)
assert rule.evaluate_static(1, box_at(500, 470), "RED", 1080) is not None # 30 px past line
assert rule.evaluate_static(1, box_at(500, 560), "RED", 1080) is None # waiting behind line
assert rule.evaluate_static(1, box_at(500, 470), "GREEN", 1080) is None
assert rule.evaluate_static(1, box_at(500, 100), "RED", 1080) is None # far into junction: unrelated
# ---------------------------------------------------------------------------
# Parking
# ---------------------------------------------------------------------------
ZONE = np.array([[0, 0], [600, 0], [600, 600], [0, 600]], dtype=np.float32)
def test_parked_vehicle_flagged_after_dwell_time():
rule = ParkingRule([ZONE], dwell_s=10)
rng = np.random.default_rng(1)
hits = []
for i in range(int(12 * FPS)):
b = box_at(300 + rng.normal(0, 2), 400 + rng.normal(0, 2))
hits += rule.update([(5, b)], i / FPS)
assert [h.violation for h in hits] == [PARKING]
assert 10 <= hits[0].metadata["dwell_s"] < 10.2
def test_slow_moving_traffic_not_flagged():
rule = ParkingRule([ZONE], dwell_s=10)
hits = []
for i in range(int(20 * FPS)):
hits += rule.update([(5, box_at(50 + i * 1.5, 400))], i / FPS) # 37 px/s crawl
assert hits == []
def test_vehicle_outside_zone_not_flagged():
rule = ParkingRule([ZONE], dwell_s=5)
hits = []
for i in range(int(10 * FPS)):
hits += rule.update([(5, box_at(900, 900))], i / FPS)
assert hits == []
def test_parking_survives_tracker_id_switch():
rule = ParkingRule([ZONE], dwell_s=10)
hits = []
t = 0.0
for i in range(int(6 * FPS)): # 6 s as id 5
t = i / FPS
hits += rule.update([(5, box_at(300, 400))], t)
for k in range(int(1 * FPS)): # occluded for 1 s
t += 1 / FPS
hits += rule.update([], t)
for k in range(int(5 * FPS)): # re-appears as id 9
t += 1 / FPS
hits += rule.update([(9, box_at(302, 401))], t)
assert [h.track_id for h in hits] == [9]
def test_parking_no_zones_is_noop():
assert ParkingRule([], dwell_s=1).update([(1, box_at(10, 10))], 100.0) == []
# ---------------------------------------------------------------------------
# Traffic light colour
# ---------------------------------------------------------------------------
def _light(color_bgr):
img = np.full((90, 30, 3), 30, dtype=np.uint8)
import cv2
cy = {"RED": 15, "YELLOW": 45, "GREEN": 75}
for name, y in cy.items():
cv2.circle(img, (15, y), 10, (50, 50, 50), -1)
return img
@pytest.mark.parametrize("state,bgr,y", [("RED", (30, 30, 240), 15), ("YELLOW", (20, 200, 250), 45),
("GREEN", (90, 220, 40), 75)])
def test_traffic_light_colour(state, bgr, y):
import cv2
img = _light(state)
cv2.circle(img, (15, y), 10, bgr, -1)
assert classify_traffic_light(img)[0] == state
def test_traffic_light_dark_is_unknown():
assert classify_traffic_light(np.full((90, 30, 3), 20, np.uint8))[0] == "UNKNOWN"
def test_signal_filter_majority():
f = SignalFilter(window=5)
for s in ["RED", "RED", "UNKNOWN", "GREEN", "RED"]:
out = f.update(s)
assert out == "RED"
# ---------------------------------------------------------------------------
# Riders: helmet + triple riding association
# ---------------------------------------------------------------------------
def test_heads_assigned_to_nearest_bike_in_dense_traffic():
bikes = [(1, (100, 200, 200, 400)), (2, (190, 200, 290, 400))] # overlapping neighbours
heads = [Head((135, 170, 165, 200), True, 0.9), Head((225, 170, 255, 200), False, 0.8),
Head((235, 205, 260, 230), False, 0.7)]
out = assign_heads(bikes, heads)
assert len(out[1]) == 1 and out[1][0].helmet
assert len(out[2]) == 2
def test_triple_riding_three_distinct_heads():
bike = [(1, (100, 200, 260, 420))]
heads = nms_heads([Head((110, 170, 140, 200), True, 0.9), Head((150, 180, 180, 210), False, 0.8),
Head((190, 190, 220, 220), False, 0.85),
Head((112, 171, 141, 201), False, 0.4)]) # duplicate of first head
out = assign_heads(bike, heads)
assert len(out[1]) == 3
def test_head_far_below_rider_zone_not_assigned():
out = assign_heads([(1, (100, 200, 200, 400))], [Head((140, 380, 160, 400), False, 0.9)])
assert out[1] == []
def test_temporal_vote_requires_repeated_evidence():
v = TemporalVote(min_hits=2, min_ratio=0.35)
assert v.add(1, "No Helmet", 0.8) is None
assert v.add(1, "No Helmet", None) is None
hit = v.add(1, "No Helmet", 0.7)
assert hit is not None and abs(hit.confidence - 0.75) < 1e-6
assert v.add(1, "No Helmet", 0.9) is None # reported once
def test_temporal_vote_rejects_rare_flicker():
v = TemporalVote(min_hits=2, min_ratio=0.35)
results = [v.add(1, "No Seatbelt", 0.9 if i in (0, 9) else None) for i in range(10)]
assert all(r is None for r in results)
|