tracking.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. """轻量多目标跟踪:IoU + 质心匹配,带历史轨迹。
  2. 仅依赖 numpy,无需额外权重;用于跌倒判据、越线计数、物资位移判定。
  3. """
  4. from __future__ import annotations
  5. import itertools
  6. from dataclasses import dataclass, field
  7. def iou(a, b) -> float:
  8. ax1, ay1, ax2, ay2 = a
  9. bx1, by1, bx2, by2 = b
  10. ix1, iy1 = max(ax1, bx1), max(ay1, by1)
  11. ix2, iy2 = min(ax2, bx2), min(ay2, by2)
  12. iw, ih = max(0.0, ix2 - ix1), max(0.0, iy2 - iy1)
  13. inter = iw * ih
  14. if inter <= 0:
  15. return 0.0
  16. area_a = max(0.0, ax2 - ax1) * max(0.0, ay2 - ay1)
  17. area_b = max(0.0, bx2 - bx1) * max(0.0, by2 - by1)
  18. return inter / (area_a + area_b - inter + 1e-9)
  19. def centroid(box) -> tuple[float, float]:
  20. return ((box[0] + box[2]) / 2.0, (box[1] + box[3]) / 2.0)
  21. @dataclass
  22. class Track:
  23. track_id: int
  24. box: list[float]
  25. cls: int
  26. name: str
  27. conf: float
  28. raw: str = ""
  29. hits: int = 1
  30. age: int = 0
  31. history: list[tuple[float, float]] = field(default_factory=list)
  32. meta: dict = field(default_factory=dict)
  33. # 连续满足自定义条件帧数
  34. streak: int = 0
  35. @property
  36. def center(self) -> tuple[float, float]:
  37. return centroid(self.box)
  38. @property
  39. def aspect(self) -> float:
  40. w = max(1.0, self.box[2] - self.box[0])
  41. h = max(1.0, self.box[3] - self.box[1])
  42. return w / h
  43. def displacement(self, n: int = 1) -> float:
  44. """相对 n 帧前质心的位移(像素)。"""
  45. if len(self.history) <= n:
  46. return 0.0
  47. cx, cy = self.history[-1]
  48. px, py = self.history[-1 - n]
  49. return ((cx - px) ** 2 + (cy - py) ** 2) ** 0.5
  50. class Tracker:
  51. """按类别分池跟踪,避免人与车辆互相抢 ID。"""
  52. def __init__(self, iou_threshold: float = 0.25, max_age: int = 30, history: int = 90):
  53. self.iou_threshold = iou_threshold
  54. self.max_age = max_age
  55. self.history = history
  56. self._ids = itertools.count(1)
  57. self.tracks: dict[int, Track] = {}
  58. def update(self, detections: list[dict]) -> list[Track]:
  59. """detections: [{cls,name,conf,xyxy}] -> 更新的活跃 track 列表。"""
  60. for t in self.tracks.values():
  61. t.age += 1
  62. t.streak = 0
  63. unmatched = list(detections)
  64. # 贪心匹配:优先高 IoU
  65. for tid, track in list(self.tracks.items()):
  66. if not unmatched:
  67. break
  68. best_i, best_iou = -1, self.iou_threshold
  69. for i, det in enumerate(unmatched):
  70. if det["cls"] != track.cls:
  71. continue
  72. v = iou(track.box, det["xyxy"])
  73. if v > best_iou:
  74. best_i, best_iou = i, v
  75. if best_i >= 0:
  76. det = unmatched.pop(best_i)
  77. track.box = det["xyxy"]
  78. track.conf = det["conf"]
  79. track.raw = det.get("raw_name", track.raw)
  80. track.hits += 1
  81. track.age = 0
  82. self._push(track)
  83. for det in unmatched:
  84. tid = next(self._ids)
  85. t = Track(
  86. track_id=tid,
  87. box=det["xyxy"],
  88. cls=det["cls"],
  89. name=det["name"],
  90. conf=det["conf"],
  91. raw=det.get("raw_name", det["name"]),
  92. )
  93. self._push(t)
  94. self.tracks[tid] = t
  95. for tid in [k for k, t in self.tracks.items() if t.age > self.max_age]:
  96. del self.tracks[tid]
  97. return list(self.tracks.values())
  98. def _push(self, t: Track) -> None:
  99. t.history.append(t.center)
  100. if len(t.history) > self.history:
  101. t.history.pop(0)
  102. def reset(self) -> None:
  103. self.tracks.clear()