Optimize counting.py: fast-reject, skip empty tracks, throttle purge

- Return early when tracks list is empty
- Fast-reject centroid by bounding rect before pointPolygonTest
- Purge stale tracks every 30 frames instead of every frame
- Skip deque append when trail_length == 0
This commit is contained in:
proitlab committed 2026-07-22 13:18:05 +07:00
1 parent d31ad05f0a
commit a54d0e6b2c
1 file changed
+22 -4
+22 -4
View File
@@ -51,12 +51,30 @@ class CountingZone:
counting_paused: bool = False,
) -> list[CountEvent]:
events: list[CountEvent] = []
if not tracks:
self.inside_box_count = 0
self.current_inside_ids.clear()
self.prev_inside_ids.clear()
self._purge_stale(frame_index, set())
return events
active_ids = set()
inside_ids = set()
rx1, ry1, rx2, ry2 = self._counting_rect
for track in tracks:
active_ids.add(track.track_id)
self.last_seen_frame[track.track_id] = frame_index
self.histories[track.track_id].append(track.centroid)
if self.trail_length > 0:
self.histories[track.track_id].append(track.centroid)
# fast-reject: bounding rect check before pointPolygonTest
cx, cy = track.centroid
if not (rx1 <= cx <= rx2 and ry1 <= cy <= ry2):
continue
if self._inside_roi(track.centroid):
inside_ids.add(track.track_id)
@@ -64,10 +82,9 @@ class CountingZone:
if counting_paused:
continue
if track.track_id not in inside_ids or track.track_id in self.counted_ids:
if track.track_id in self.counted_ids:
continue
should_validate = False
if self.validate_while_inside:
should_validate = self._meets_validation_thresholds(track)
else:
@@ -102,7 +119,8 @@ class CountingZone:
self.inside_box_count = len(inside_ids)
self.current_inside_ids = inside_ids
self.prev_inside_ids = inside_ids
self._purge_stale(frame_index, active_ids)
if frame_index % 30 == 0:
self._purge_stale(frame_index, active_ids)
return events
def trail_for(self, track_id: int) -> list[tuple[int, int]]: