"""轻量多目标跟踪:IoU + 质心匹配,带历史轨迹。 仅依赖 numpy,无需额外权重;用于跌倒判据、越线计数、物资位移判定。 """ from __future__ import annotations import itertools from dataclasses import dataclass, field def iou(a, b) -> float: ax1, ay1, ax2, ay2 = a bx1, by1, bx2, by2 = b ix1, iy1 = max(ax1, bx1), max(ay1, by1) ix2, iy2 = min(ax2, bx2), min(ay2, by2) iw, ih = max(0.0, ix2 - ix1), max(0.0, iy2 - iy1) inter = iw * ih if inter <= 0: return 0.0 area_a = max(0.0, ax2 - ax1) * max(0.0, ay2 - ay1) area_b = max(0.0, bx2 - bx1) * max(0.0, by2 - by1) return inter / (area_a + area_b - inter + 1e-9) def centroid(box) -> tuple[float, float]: return ((box[0] + box[2]) / 2.0, (box[1] + box[3]) / 2.0) @dataclass class Track: track_id: int box: list[float] cls: int name: str conf: float raw: str = "" hits: int = 1 age: int = 0 history: list[tuple[float, float]] = field(default_factory=list) meta: dict = field(default_factory=dict) # 连续满足自定义条件帧数 streak: int = 0 @property def center(self) -> tuple[float, float]: return centroid(self.box) @property def aspect(self) -> float: w = max(1.0, self.box[2] - self.box[0]) h = max(1.0, self.box[3] - self.box[1]) return w / h def displacement(self, n: int = 1) -> float: """相对 n 帧前质心的位移(像素)。""" if len(self.history) <= n: return 0.0 cx, cy = self.history[-1] px, py = self.history[-1 - n] return ((cx - px) ** 2 + (cy - py) ** 2) ** 0.5 class Tracker: """按类别分池跟踪,避免人与车辆互相抢 ID。""" def __init__(self, iou_threshold: float = 0.25, max_age: int = 30, history: int = 90): self.iou_threshold = iou_threshold self.max_age = max_age self.history = history self._ids = itertools.count(1) self.tracks: dict[int, Track] = {} def update(self, detections: list[dict]) -> list[Track]: """detections: [{cls,name,conf,xyxy}] -> 更新的活跃 track 列表。""" for t in self.tracks.values(): t.age += 1 t.streak = 0 unmatched = list(detections) # 贪心匹配:优先高 IoU for tid, track in list(self.tracks.items()): if not unmatched: break best_i, best_iou = -1, self.iou_threshold for i, det in enumerate(unmatched): if det["cls"] != track.cls: continue v = iou(track.box, det["xyxy"]) if v > best_iou: best_i, best_iou = i, v if best_i >= 0: det = unmatched.pop(best_i) track.box = det["xyxy"] track.conf = det["conf"] track.raw = det.get("raw_name", track.raw) track.hits += 1 track.age = 0 self._push(track) for det in unmatched: tid = next(self._ids) t = Track( track_id=tid, box=det["xyxy"], cls=det["cls"], name=det["name"], conf=det["conf"], raw=det.get("raw_name", det["name"]), ) self._push(t) self.tracks[tid] = t for tid in [k for k, t in self.tracks.items() if t.age > self.max_age]: del self.tracks[tid] return list(self.tracks.values()) def _push(self, t: Track) -> None: t.history.append(t.center) if len(t.history) > self.history: t.history.pop(0) def reset(self) -> None: self.tracks.clear()