Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/decision-log.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,4 @@ decisions with full context and alternatives are the ADRs in
- 2026-11-16: **Submersion also requires the person last seen past the edge margin** (Sean). The day walk raised a false `SUBMERSION` at 100.8 s: Sean was last seen toes-on-coping at the far edge (depth 0 to +0.02), the tracker lost him as he walked on, and the coasting track timed out after 12 s. This applies in every mode. **It is a sensitivity trade:** a person who slips in at the very edge and is lost in the same instant, before their box is past 0.2, would not time out. Accepted because the one real swimmer was last seen at +1.97 and never measured below +0.53, while deck walkers who leave the camera's view near the edge would otherwise raise false drowning alarms on every walk past the pool. In armed mode such a person still raises the edge warning. `in_water` stays on `TrackedPerson` (foot point inside the bare outline) but no rule reads it any more; the HUD's entry count and submersion meter use the margin too, so the overlay matches the rules.
- 2026-11-16: Regression suite with the edge margin, 9 shot-mode pairs: every event verdict passes (all six swim clips, `drowning-test.mp4` in both modes, both armed cover-on clips). Three tracker checks fail, all already known and none caused by this change: `adult-exits` headcount (2026-10-13), `armed-cover-on-night.mp4` 3 phantom tracks for 0 people (deck furniture at night), and `armed-cover-on-day-walk.mp4` 8 track IDs for 1 person (phantoms on the far patio plus ID changes as Sean walks; not separated).
- 2026-11-16: **Fall-in footage is the next priority** (Sean: a fall-in is the main use case). The only entry on footage so far is a deliberate jump, and the edge-margin trade (2026-11-16) is untested against the case it risks: a slip-in at the edge. Planned takes, camera untouched, 30 s empty lead-in each: (1) cover on, weighted dummy off the near edge; (2) cover on, dummy off the far edge, where foreshortening may keep the depth under the 0.2 margin; (3) cover off, an adult slipping in sideways from the coping and staying under about 15 s; (4) the same at the far wall. **Cover-on falls are staged with a dummy only, never a person:** the cover is a floating solar cover, so someone who goes through it surfaces under it. People-in-water takes need a wetsuit (cold water in November), the shallow end and a second adult on the deck.
- 2026-11-16: Replay overlay made fit for a demo video. (1) It scales with frame width: sizes are given for 960 px and multiplied up (2x at 1080p); a 1080p render shrunk to phone size had unreadable text. (2) A "RAISED" row keeps every event raised so far on screen with its time, one entry per event type plus a repeat count. The status line only shows what is true on the current frame, so the armed entry on `drowning-test.mp4` (1.2 s, mid-jump) was visible for a fraction of a second. (3) A status line for `PERSON_AT_EDGE` (orange, below the submersion clock). The panel grows from 74 to 96 px at 1x.
120 changes: 99 additions & 21 deletions src/poolguard/vision/hud.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@
_MUTED_COLOR = (150, 150, 150)
_FONT = cv2.FONT_HERSHEY_SIMPLEX
_PANEL_ALPHA = 0.65
HUD_REFERENCE_WIDTH = 960
"""Frame width the overlay's sizes are given for; wider frames scale up."""

_ALERT_COLOR = (60, 60, 230) # red — the rule would fire now
_WARN_COLOR = (40, 220, 220) # yellow — a clock is running
_EDGE_COLOR = (0, 150, 255) # orange — armed, someone at the coping
_BLIND_COLOR = (200, 160, 40) # teal — detector sees nothing
_CALM_COLOR = (80, 220, 60) # green — nominal

Expand All @@ -42,7 +45,12 @@ class HudState(BaseModel):

armed: bool = False
in_water_tracks: int = Field(default=0, ge=0)
"""Live tracks whose box is in the pool zone; while armed, each is an entry."""
"""Live tracks past the edge margin inside the pool; while armed, each is an entry."""
edge_tracks: int = Field(default=0, ge=0)
"""Live tracks within the edge margin of the outline; while armed, a warning."""

raised: tuple[tuple[str, float], ...] = ()
"""Every event raised so far as (event name, seconds in), oldest first."""

expected: tuple[tuple[str, tuple[float, float]], ...] = ()
"""The label's expected events as (event name, onset window) pairs."""
Expand Down Expand Up @@ -74,43 +82,109 @@ def status_line(state: HudState) -> tuple[str, tuple[int, int, int]]:
return f"ENTRY — {state.in_water_tracks} in the water while armed", _ALERT_COLOR
if state.longest_unseen_seconds > 0:
return f"in-water track lost {state.longest_unseen_seconds:.1f}s", _WARN_COLOR
if state.armed and state.edge_tracks > 0:
return f"EDGE — {state.edge_tracks} at the pool edge while armed", _EDGE_COLOR
if state.live_tracks == 0:
return "NO ONE DETECTED", _BLIND_COLOR
if state.expecting_now is not None:
return f"in onset window — expecting {state.expecting_now}", _WARN_COLOR
return f"tracking {state.live_tracks}", _CALM_COLOR


_ALARM_NAMES = {
"unsupervised_entry": "ENTRY",
"submersion": "SUBMERSION",
"person_at_edge": "EDGE",
"distress": "DISTRESS",
"system_degraded": "DEGRADED",
}
_WARNING_EVENTS = frozenset({"person_at_edge"})


def alarm_line(state: HudState) -> tuple[str, tuple[int, int, int]] | None:
"""Everything raised so far, so an alarm stays on screen after its frame passes.

One entry per event type at its first time, with a count of repeats (a person
whose track fragments raises the same warning once per track). Red if any
emergency was raised, orange if only warnings.
"""
if not state.raised:
return None
first: dict[str, float] = {}
count: dict[str, int] = {}
for event, seconds in state.raised:
first.setdefault(event, seconds)
count[event] = count.get(event, 0) + 1
parts = []
for event, seconds in first.items():
repeats = f" (+{count[event] - 1})" if count[event] > 1 else ""
parts.append(f"{_ALARM_NAMES.get(event, event.upper())} {seconds:.1f}s{repeats}")
only_warnings = all(event in _WARNING_EVENTS for event in first)
return "RAISED " + " | ".join(parts), _EDGE_COLOR if only_warnings else _ALERT_COLOR


def hud_scale(width: int) -> float:
"""Size multiplier for overlay text and lines: 1 at HUD_REFERENCE_WIDTH, never below."""
return max(1.0, width / HUD_REFERENCE_WIDTH)


def draw_hud(canvas: np.ndarray, state: HudState) -> np.ndarray:
"""Draw the HUD panel onto a copy of the frame."""
"""Draw the HUD panel onto a copy of the frame, scaled to the frame's width."""
out = canvas.copy()
height, width = out.shape[:2]
panel_height = 74
k = hud_scale(width)
panel_height = round(96 * k)

overlay = out.copy()
cv2.rectangle(overlay, (0, 0), (width, panel_height), _PANEL_COLOR, -1)
cv2.addWeighted(overlay, _PANEL_ALPHA, out, 1 - _PANEL_ALPHA, 0, out)

clock = f"t={state.elapsed_seconds:5.2f}s f{state.frame_index:04d}"
cv2.putText(out, clock, (8, 20), _FONT, 0.5, _TEXT_COLOR, 1, cv2.LINE_AA)
_text(out, clock, (8, 20), 0.5, _TEXT_COLOR, 1, k)

tracks = (
f"live {state.live_tracks} coasting {state.coasting_tracks} "
f"det {state.detection_rate * 100:3.0f}%"
)
cv2.putText(out, tracks, (8, 40), _FONT, 0.45, _MUTED_COLOR, 1, cv2.LINE_AA)
_text(out, tracks, (8, 40), 0.45, _MUTED_COLOR, 1, k)

text, color = status_line(state)
if text:
cv2.putText(out, text, (8, 62), _FONT, 0.55, color, 2, cv2.LINE_AA)
_text(out, text, (8, 62), 0.55, color, 2, k)
alarms = alarm_line(state)
if alarms is not None:
_text(out, alarms[0], (8, 86), 0.55, alarms[1], 2, k)

_draw_expectation(out, state, width)
_draw_expectation(out, state, width, k)
if state.longest_unseen_seconds > 0:
_draw_submersion_meter(out, state, width, panel_height)
_draw_submersion_meter(out, state, width, panel_height, k)
return out


def _draw_expectation(canvas: np.ndarray, state: HudState, width: int) -> None:
def _text(
canvas: np.ndarray,
text: str,
origin: tuple[int, int],
font_scale: float,
color: tuple[int, int, int],
thickness: int,
k: float,
) -> None:
"""putText with the position, size and stroke given at 1x and multiplied by k."""
x, y = origin
cv2.putText(
canvas,
text,
(round(x * k), round(y * k)),
_FONT,
font_scale * k,
color,
max(1, round(thickness * k)),
cv2.LINE_AA,
)


def _draw_expectation(canvas: np.ndarray, state: HudState, width: int, k: float) -> None:
"""Right-aligned reminder of what the label expects, so drift is obvious."""
if not state.expected:
label = "label: must stay quiet"
Expand All @@ -119,33 +193,37 @@ def _draw_expectation(canvas: np.ndarray, state: HudState, width: int) -> None:
f"{event} @ {start:.1f}-{end:.1f}s" for event, (start, end) in state.expected
)
color = _TEXT_COLOR if state.expecting_now is not None else _MUTED_COLOR
(text_width, _), _ = cv2.getTextSize(label, _FONT, 0.45, 1)
cv2.putText(canvas, label, (width - text_width - 8, 20), _FONT, 0.45, color, 1, cv2.LINE_AA)
thickness = max(1, round(k))
(text_width, _), _ = cv2.getTextSize(label, _FONT, 0.45 * k, thickness)
x = width - text_width - round(8 * k)
cv2.putText(canvas, label, (x, round(20 * k)), _FONT, 0.45 * k, color, thickness, cv2.LINE_AA)


def _draw_submersion_meter(
canvas: np.ndarray, state: HudState, width: int, panel_height: int
canvas: np.ndarray, state: HudState, width: int, panel_height: int, k: float
) -> None:
"""A bar filling toward the submersion timeout — the rule's clock, visible.

Coasting time is the submersion signal, so watching this bar fill is the
fastest way to see whether a track was lost long enough to matter.
"""
bar_width = 160
left = width - bar_width - 8
top = panel_height - 26
cv2.rectangle(canvas, (left, top), (left + bar_width, top + 10), _MUTED_COLOR, 1)
bar_width = round(160 * k)
bar_height = round(10 * k)
left = width - bar_width - round(8 * k)
top = round(48 * k)
line = max(1, round(k))
cv2.rectangle(canvas, (left, top), (left + bar_width, top + bar_height), _MUTED_COLOR, line)
filled = int(bar_width * state.submersion_progress)
color = (60, 60, 230) if state.submersion_progress >= 1.0 else (40, 220, 220)
color = _ALERT_COLOR if state.submersion_progress >= 1.0 else _WARN_COLOR
if filled > 0:
cv2.rectangle(canvas, (left, top), (left + filled, top + 10), color, -1)
cv2.rectangle(canvas, (left, top), (left + filled, top + bar_height), color, -1)
cv2.putText(
canvas,
f"unseen {state.longest_unseen_seconds:4.1f}s / {state.submersion_timeout_seconds:.0f}s",
(left, top + 24),
(left, top + round(24 * k)),
_FONT,
0.4,
0.4 * k,
_MUTED_COLOR,
1,
line,
cv2.LINE_AA,
)
65 changes: 35 additions & 30 deletions src/poolguard/vision/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from poolguard.geometry import Polygon
from poolguard.replay import TrackedFrameResult, run_tracked_replay
from poolguard.vision.frames import Frame, FrameSource
from poolguard.vision.hud import HudState, draw_hud
from poolguard.vision.hud import HudState, draw_hud, hud_scale
from poolguard.vision.pose import PoseEstimator

if TYPE_CHECKING:
Expand Down Expand Up @@ -56,11 +56,12 @@ def annotate_frame(
"""Return a copy of the frame with the tracker's view drawn on it."""
canvas = image.copy()
height, width = canvas.shape[:2]
k = hud_scale(width)

zone_pixels = np.array(
[(int(x * width), int(y * height)) for x, y in pool_zone], dtype=np.int32
)
cv2.polylines(canvas, [zone_pixels], isClosed=True, color=_ZONE_COLOR, thickness=1)
cv2.polylines(canvas, [zone_pixels], isClosed=True, color=_ZONE_COLOR, thickness=round(k))

for person in people:
box = person.detection.box
Expand All @@ -71,9 +72,9 @@ def annotate_frame(
)
color = color_for_track(person.track_id)
if person.seconds_since_last_seen == 0.0:
_draw_live(canvas, person, top_left, bottom_right, color)
_draw_live(canvas, person, top_left, bottom_right, color, k)
else:
_draw_coasting(canvas, person, top_left, bottom_right, color)
_draw_coasting(canvas, person, top_left, bottom_right, color, k)
return canvas


Expand All @@ -83,18 +84,10 @@ def _draw_live(
top_left: tuple[int, int],
bottom_right: tuple[int, int],
color: tuple[int, int, int],
k: float,
) -> None:
cv2.rectangle(canvas, top_left, bottom_right, color, 2)
cv2.putText(
canvas,
f"#{person.track_id}",
(top_left[0], max(top_left[1] - 6, 12)),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
color,
1,
cv2.LINE_AA,
)
cv2.rectangle(canvas, top_left, bottom_right, color, round(2 * k))
_label(canvas, f"#{person.track_id}", top_left, color, k)


def _draw_coasting(
Expand All @@ -103,23 +96,30 @@ def _draw_coasting(
top_left: tuple[int, int],
bottom_right: tuple[int, int],
color: tuple[int, int, int],
k: float,
) -> None:
"""Draw a track the detector has lost: the ghost box at its last-seen spot.

This is the frame's most important annotation — it must read as "the
system is watching this spot" and show how long the person has been
unseen (person.seconds_since_last_seen).
"""
cv2.rectangle(canvas, top_left, bottom_right, color, 1)
cv2.rectangle(canvas, top_left, bottom_right, color, round(k))
label = f"#{person.track_id} (unseen/lost {person.seconds_since_last_seen:.1f}s)"
_label(canvas, label, top_left, color, k)


def _label(
canvas: np.ndarray,
text: str,
top_left: tuple[int, int],
color: tuple[int, int, int],
k: float,
) -> None:
"""Track label just above the box, kept on screen when the box touches the top."""
origin = (top_left[0], max(top_left[1] - round(6 * k), round(12 * k)))
cv2.putText(
canvas,
f"#{person.track_id} (unseen/lost {person.seconds_since_last_seen:.1f}s)",
(top_left[0], max(top_left[1] - 6, 12)),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
color,
1,
cv2.LINE_AA,
canvas, text, origin, cv2.FONT_HERSHEY_SIMPLEX, 0.5 * k, color, round(k), cv2.LINE_AA
)


Expand All @@ -131,13 +131,17 @@ def _hud_state(
label: "ShotLabel | None",
rules: RulesSettings,
mode: OperatingMode,
raised: tuple[tuple[str, float], ...] = (),
) -> HudState:
elapsed = (result.ts - start_ts).total_seconds()
raised = raised + tuple((event.event_type.value, elapsed) for event in result.events)
live = tuple(p for p in result.people if p.seconds_since_last_seen == 0.0)
coasting = tuple(p for p in result.people if p.seconds_since_last_seen > 0.0)
return HudState(
frame_index=result.frame_index,
elapsed_seconds=(result.ts - start_ts).total_seconds(),
elapsed_seconds=elapsed,
live_tracks=len(live),
raised=raised,
coasting_tracks=len(coasting),
longest_unseen_seconds=max(
(p.seconds_since_last_seen for p in coasting if p.water_depth > rules.edge_margin),
Expand All @@ -146,6 +150,7 @@ def _hud_state(
detection_rate=frames_with_detections / max(frames_seen, 1),
armed=mode is OperatingMode.ARMED,
in_water_tracks=sum(1 for p in live if p.water_depth > rules.edge_margin),
edge_tracks=sum(1 for p in live if abs(p.water_depth) <= rules.edge_margin),
expected=tuple((e.event.value, e.onset_window) for e in label.expected_events)
if label
else (),
Expand Down Expand Up @@ -177,6 +182,7 @@ def render_tracked_replay(
start_ts = None
frames_seen = 0
frames_with_detections = 0
raised: tuple[tuple[str, float], ...] = ()

def open_writer(canvas: np.ndarray, fps: float) -> cv2.VideoWriter:
height, width = canvas.shape[:2]
Expand All @@ -194,12 +200,11 @@ def open_writer(canvas: np.ndarray, fps: float) -> cv2.VideoWriter:
if result.detections:
frames_with_detections += 1
canvas = annotate_frame(frame.image, result.people, settings.pool_zone)
canvas = draw_hud(
canvas,
_hud_state(
result, start_ts, frames_seen, frames_with_detections, label, rules, mode
),
hud = _hud_state(
result, start_ts, frames_seen, frames_with_detections, label, rules, mode, raised
)
raised = hud.raised
canvas = draw_hud(canvas, hud)
if writer is None:
if pending is None:
pending = (canvas, result)
Expand Down
Loading
Loading