scene.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. """场景规则判定:把 YOLO 检测框映射成 ``0 / 1 / 2`` 场景编码。
  2. 两种工作模式
  3. ------------
  4. ``composed``(默认,推荐)
  5. 模型检测 ``container / bed / flatbed`` 等目标,本模块用**几何关系**判断集装箱
  6. 是否落在某种车厢上:
  7. * 集装箱必须有足够面积落在 ROI 内(``roi_min_ratio``);
  8. * 车厢框与集装箱框在横向要有交叠(``support_overlap``);
  9. * 车厢顶边要贴近集装箱底边(``support_dy_ratio``,单位是箱高的比例);
  10. * 车厢置信度不能明显低于集装箱(``support_score_ratio``)。
  11. 这样做可解释、可现场调参,也便于以后新增 ``person`` 等安全类而不影响既有编码。
  12. ``direct``
  13. 模型直接输出 3 类场景(``not_on_train / bed / flatbed``),本模块只做 ROI 过滤
  14. 与 argmax。
  15. 输出始终是 :class:`~portcv.schema.Observation`,编码含义::
  16. 0 = 集装箱不在车上(没看到箱,或箱底下不是车斗/平板车)
  17. 1 = 车斗
  18. 2 = 平板车
  19. 255 = UNKNOWN(无任何观测 / 未就绪),由上层时序滤波决定是否下发给 PLC
  20. """
  21. from __future__ import annotations
  22. import math
  23. import time
  24. from typing import Dict, List, Optional, Sequence, Tuple
  25. from ..config import Config
  26. from ..schema import Box, Observation, SceneState
  27. from .geometry import box_in_polygon_ratio, normalized_to_pixel_polygon
  28. __all__ = ["SceneClassifier", "GROUP_CONTAINER", "GROUP_BED", "GROUP_FLATBED", "GROUP_IGNORE"]
  29. GROUP_CONTAINER = "container"
  30. GROUP_BED = "bed"
  31. GROUP_FLATBED = "flatbed"
  32. GROUP_IGNORE = "ignore"
  33. GROUP_UNKNOWN = "unknown"
  34. class SceneClassifier:
  35. """检测框 → 场景编码。线程内使用,非线程安全。"""
  36. def __init__(self, cfg: Config) -> None:
  37. self.cfg = cfg
  38. scene = cfg.section("scene")
  39. self.mode = str(scene.get("mode") or cfg.get_path("run.mode", "composed")).lower()
  40. classes = scene.get("classes") or {}
  41. self._groups: Dict[str, set] = {}
  42. for group in (GROUP_CONTAINER, GROUP_BED, GROUP_FLATBED, GROUP_IGNORE):
  43. self._groups[group] = {self.normalize(n) for n in (classes.get(group) or []) if n}
  44. # direct 模式:类别名 → 场景编码
  45. self._direct_map: Dict[str, int] = {}
  46. for name, code in (scene.get("direct_map") or {}).items():
  47. self._direct_map[self.normalize(name)] = int(code)
  48. for label, code in ((0, 0), (1, 1), (2, 2)):
  49. self._direct_map.setdefault(
  50. self.normalize(["not_on_train", "bed", "flatbed"][label]), code
  51. )
  52. self.require_container = bool(scene.get("require_container", True))
  53. self.min_class_conf = float(scene.get("min_class_conf", 0.30))
  54. self.roi_min_ratio = float(scene.get("roi_min_ratio", 0.30))
  55. self.support_overlap = float(scene.get("support_overlap", 0.30))
  56. self.support_dy_ratio = float(scene.get("support_dy_ratio", 0.45))
  57. self.support_score_ratio = float(scene.get("support_score_ratio", 0.60))
  58. self.unknown_on_no_detection = bool(scene.get("unknown_on_no_detection", True))
  59. self.no_container_conf = float(scene.get("no_container_conf", 0.60))
  60. self._roi_norm: List[Tuple[float, float]] = cfg.roi
  61. self._roi_cache: Dict[Tuple[int, int], List[Tuple[float, float]]] = {}
  62. # ---------------------------------------------------------------- 工具
  63. @staticmethod
  64. def normalize(name: str) -> str:
  65. return str(name or "").strip().lower().replace("-", "_").replace(" ", "_")
  66. def group_of(self, class_name: str) -> str:
  67. """类别名 → 语义分组。"""
  68. name = self.normalize(class_name)
  69. for group in (GROUP_CONTAINER, GROUP_BED, GROUP_FLATBED, GROUP_IGNORE):
  70. if name in self._groups[group]:
  71. return group
  72. return GROUP_UNKNOWN
  73. def roi_polygon(self, width: int, height: int) -> List[Tuple[float, float]]:
  74. key = (int(width), int(height))
  75. if key not in self._roi_cache:
  76. self._roi_cache[key] = normalized_to_pixel_polygon(self._roi_norm, width, height)
  77. return self._roi_cache[key]
  78. # ------------------------------------------------------------ 主入口
  79. def classify(
  80. self,
  81. detections: Sequence[Box],
  82. frame_size: Tuple[int, int],
  83. ts: Optional[float] = None,
  84. frame_id: int = 0,
  85. ) -> Observation:
  86. """``frame_size`` 为 ``(width, height)``。"""
  87. ts = float(ts if ts is not None else time.time())
  88. width, height = int(frame_size[0]), int(frame_size[1])
  89. boxes = [b for b in detections if float(b.score) >= self.min_class_conf]
  90. if self.mode == "direct":
  91. return self._classify_direct(boxes, width, height, ts, frame_id)
  92. return self._classify_composed(boxes, width, height, ts, frame_id)
  93. # --------------------------------------------------------- direct 模式
  94. def _classify_direct(
  95. self,
  96. boxes: List[Box],
  97. width: int,
  98. height: int,
  99. ts: float,
  100. frame_id: int,
  101. ) -> Observation:
  102. poly = self.roi_polygon(width, height)
  103. best: Optional[Tuple[Box, int, float]] = None # (box, state, score)
  104. for box in boxes:
  105. name = self.normalize(box.class_name)
  106. if name not in self._direct_map:
  107. continue
  108. ratio = box_in_polygon_ratio(box, poly)
  109. if ratio < self.roi_min_ratio:
  110. continue
  111. score = float(box.score) * (0.5 + 0.5 * ratio)
  112. if best is None or score > best[2]:
  113. best = (box, int(self._direct_map[name]), score)
  114. if best is None:
  115. if self.unknown_on_no_detection:
  116. return Observation(ts, int(SceneState.UNKNOWN), 0.0, list(boxes), "no_direct_hit", frame_id)
  117. return Observation(
  118. ts, int(SceneState.NOT_ON_TRAIN), self.no_container_conf, list(boxes), "no_direct_hit", frame_id
  119. )
  120. box, state, score = best
  121. return Observation(
  122. ts,
  123. state,
  124. min(1.0, float(box.score)),
  125. list(boxes),
  126. "direct:%s=%.2f" % (box.class_name, box.score),
  127. frame_id,
  128. )
  129. # ------------------------------------------------------- composed 模式
  130. @staticmethod
  131. def _overlap_x1d(a1: float, a2: float, b1: float, b2: float) -> float:
  132. """一维交叠长度占较短区间长度的比例(0..1)。"""
  133. inter = min(a2, b2) - max(a1, b1)
  134. if inter <= 0:
  135. return 0.0
  136. shorter = min(a2 - a1, b2 - b1)
  137. return float(inter / shorter) if shorter > 0 else 0.0
  138. def _support_quality(self, container: Box, wagon: Box) -> Optional[Tuple[float, float]]:
  139. """判断车厢是否"托着"集装箱,返回 ``(横向交叠, 匹配质量)``,不匹配则 None。"""
  140. if container.height <= 0:
  141. return None
  142. if wagon.score < self.support_score_ratio * container.score:
  143. return None
  144. # 车厢顶边不应明显高于集装箱顶边(否则多半是别的车厢/背景)
  145. if wagon.top < container.top - 0.05 * container.height:
  146. return None
  147. ov_x = self._overlap_x1d(container.x1, container.x2, wagon.x1, wagon.x2)
  148. if ov_x < self.support_overlap:
  149. return None
  150. dy_ratio = abs(wagon.top - container.bottom) / container.height
  151. if dy_ratio > self.support_dy_ratio:
  152. return None
  153. tol = max(self.support_dy_ratio, 1e-6)
  154. quality = ov_x * max(0.2, 1.0 - 0.5 * (dy_ratio / tol))
  155. return ov_x, quality
  156. def _best_support(
  157. self, container: Box, wagons: List[Tuple[Box, float]]
  158. ) -> Optional[Tuple[Box, float, float, float]]:
  159. """返回 ``(车厢框, 匹配分数, 横向交叠, 车厢ROI比例)``,取分数最高者。"""
  160. best: Optional[Tuple[Box, float, float, float]] = None
  161. for wagon, roi_ratio in wagons:
  162. matched = self._support_quality(container, wagon)
  163. if matched is None:
  164. continue
  165. ov_x, quality = matched
  166. score = float(wagon.score) * quality
  167. if best is None or score > best[1]:
  168. best = (wagon, score, ov_x, roi_ratio)
  169. return best
  170. def _classify_composed(
  171. self,
  172. boxes: List[Box],
  173. width: int,
  174. height: int,
  175. ts: float,
  176. frame_id: int,
  177. ) -> Observation:
  178. if not boxes:
  179. if self.unknown_on_no_detection:
  180. return Observation(
  181. ts, int(SceneState.UNKNOWN), 0.0, [], "no_detection", frame_id
  182. )
  183. return Observation(
  184. ts,
  185. int(SceneState.NOT_ON_TRAIN),
  186. self.no_container_conf,
  187. [],
  188. "no_detection",
  189. frame_id,
  190. )
  191. poly = self.roi_polygon(width, height)
  192. containers: List[Tuple[Box, float]] = []
  193. beds: List[Tuple[Box, float]] = []
  194. flats: List[Tuple[Box, float]] = []
  195. for box in boxes:
  196. group = self.group_of(box.class_name)
  197. if group == GROUP_IGNORE or group == GROUP_UNKNOWN:
  198. continue
  199. ratio = box_in_polygon_ratio(box, poly)
  200. if ratio < self.roi_min_ratio:
  201. continue
  202. if group == GROUP_CONTAINER:
  203. containers.append((box, ratio))
  204. elif group == GROUP_BED:
  205. beds.append((box, ratio))
  206. elif group == GROUP_FLATBED:
  207. flats.append((box, ratio))
  208. if not containers:
  209. # ROI 内没有集装箱 → "集装箱不在车上"
  210. wagon_score = max([b.score for b, _ in beds] + [b.score for b, _ in flats] + [0.0])
  211. conf = min(1.0, 0.55 + 0.35 * wagon_score)
  212. reason = "no_container" + ("_wagon_seen=%.2f" % wagon_score if wagon_score else "")
  213. return Observation(ts, int(SceneState.NOT_ON_TRAIN), conf, list(boxes), reason, frame_id)
  214. container = max(containers, key=lambda item: item[0].score * (0.5 + 0.5 * item[1]))[0]
  215. bed_hit = self._best_support(container, beds)
  216. flat_hit = self._best_support(container, flats)
  217. if bed_hit is None and flat_hit is None:
  218. # 有箱,但底下既不是车斗也不是平板车(吊起来/在卡车上/堆场)
  219. conf = min(0.75, 0.40 + 0.25 * container.score)
  220. reason = "container_without_wagon(c=%.2f)" % container.score
  221. return Observation(ts, int(SceneState.NOT_ON_TRAIN), conf, list(boxes), reason, frame_id)
  222. candidates = []
  223. if bed_hit is not None:
  224. candidates.append((int(SceneState.BED), bed_hit, "bed"))
  225. if flat_hit is not None:
  226. candidates.append((int(SceneState.FLATBED), flat_hit, "flatbed"))
  227. state, hit, tag = max(candidates, key=lambda item: item[1][1])
  228. wagon, sup_score, ov_x, _wagon_ratio = hit
  229. conf = (container.score * wagon.score) ** 0.5 * (0.55 + 0.45 * ov_x)
  230. ambiguous = len(candidates) > 1 and max(c[1][1] for c in candidates) < 1.10 * min(
  231. c[1][1] for c in candidates
  232. )
  233. if ambiguous:
  234. conf *= 0.85 # 两种车厢都像 → 降权,交给时序滤波去稳定
  235. reason = "c=%.2f %s=%.2f ov=%.2f%s" % (
  236. container.score,
  237. tag,
  238. wagon.score,
  239. ov_x,
  240. " ambiguous" if ambiguous else "",
  241. )
  242. return Observation(ts, int(state), min(1.0, conf), list(boxes), reason, frame_id)