TobiasLogic commited on
Commit
e13bc33
·
verified ·
1 Parent(s): 911143d

Add restricted zone detection module and demo

Browse files
Files changed (1) hide show
  1. src/objectmodel_v1/zones.py +63 -0
src/objectmodel_v1/zones.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass
7
+ class ZoneEvent:
8
+ track_id: int
9
+ label: int
10
+ kind: str
11
+ frame_index: int
12
+ position: tuple[float, float]
13
+
14
+
15
+ def point_in_polygon(point: tuple[float, float], polygon: list[tuple[float, float]]) -> bool:
16
+ x, y = point
17
+ inside = False
18
+ n = len(polygon)
19
+ j = n - 1
20
+ for i in range(n):
21
+ xi, yi = polygon[i]
22
+ xj, yj = polygon[j]
23
+ if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
24
+ inside = not inside
25
+ j = i
26
+ return inside
27
+
28
+
29
+ class RestrictedZoneMonitor:
30
+ """Fires an event when a tracked object's ground position crosses a zone boundary.
31
+
32
+ Consumes `Track` objects from `SortTracker.update()`. The zone is a polygon in
33
+ the same pixel coordinates as the tracked boxes (a rectangle is just a
34
+ four-point polygon). Uses each box's bottom-center point rather than its
35
+ centroid, since a zone drawn on a floor plane should key off where someone is
36
+ standing, not their torso. Only reports the entered/exited transition, not
37
+ every frame a track spends inside the zone.
38
+ """
39
+
40
+ def __init__(self, polygon: list[tuple[float, float]]) -> None:
41
+ self.polygon = polygon
42
+ self._inside_state: dict[int, bool] = {}
43
+
44
+ def update(self, tracks, frame_index: int = 0) -> list[ZoneEvent]:
45
+ events: list[ZoneEvent] = []
46
+ live_ids = set()
47
+ for track in tracks:
48
+ live_ids.add(track.id)
49
+ x0, y0, x1, y1 = track.box
50
+ ground_point = ((x0 + x1) / 2.0, y1)
51
+ is_inside = point_in_polygon(ground_point, self.polygon)
52
+ was_inside = self._inside_state.get(track.id, False)
53
+ if is_inside and not was_inside:
54
+ events.append(ZoneEvent(track.id, track.label, "entered", frame_index, ground_point))
55
+ elif was_inside and not is_inside:
56
+ events.append(ZoneEvent(track.id, track.label, "exited", frame_index, ground_point))
57
+ self._inside_state[track.id] = is_inside
58
+
59
+ for track_id in list(self._inside_state):
60
+ if track_id not in live_ids:
61
+ del self._inside_state[track_id]
62
+
63
+ return events