"""场景规则判定:把 YOLO 检测框映射成 ``0 / 1 / 2`` 场景编码。 两种工作模式 ------------ ``composed``(默认,推荐) 模型检测 ``container / bed / flatbed`` 等目标,本模块用**几何关系**判断集装箱 是否落在某种车厢上: * 集装箱必须有足够面积落在 ROI 内(``roi_min_ratio``); * 车厢框与集装箱框在横向要有交叠(``support_overlap``); * 车厢顶边要贴近集装箱底边(``support_dy_ratio``,单位是箱高的比例); * 车厢置信度不能明显低于集装箱(``support_score_ratio``)。 这样做可解释、可现场调参,也便于以后新增 ``person`` 等安全类而不影响既有编码。 ``direct`` 模型直接输出 3 类场景(``not_on_train / bed / flatbed``),本模块只做 ROI 过滤 与 argmax。 输出始终是 :class:`~portcv.schema.Observation`,编码含义:: 0 = 集装箱不在车上(没看到箱,或箱底下不是车斗/平板车) 1 = 车斗 2 = 平板车 255 = UNKNOWN(无任何观测 / 未就绪),由上层时序滤波决定是否下发给 PLC """ from __future__ import annotations import math import time from typing import Dict, List, Optional, Sequence, Tuple from ..config import Config from ..schema import Box, Observation, SceneState from .geometry import box_in_polygon_ratio, normalized_to_pixel_polygon __all__ = ["SceneClassifier", "GROUP_CONTAINER", "GROUP_BED", "GROUP_FLATBED", "GROUP_IGNORE"] GROUP_CONTAINER = "container" GROUP_BED = "bed" GROUP_FLATBED = "flatbed" GROUP_IGNORE = "ignore" GROUP_UNKNOWN = "unknown" class SceneClassifier: """检测框 → 场景编码。线程内使用,非线程安全。""" def __init__(self, cfg: Config) -> None: self.cfg = cfg scene = cfg.section("scene") self.mode = str(scene.get("mode") or cfg.get_path("run.mode", "composed")).lower() classes = scene.get("classes") or {} self._groups: Dict[str, set] = {} for group in (GROUP_CONTAINER, GROUP_BED, GROUP_FLATBED, GROUP_IGNORE): self._groups[group] = {self.normalize(n) for n in (classes.get(group) or []) if n} # direct 模式:类别名 → 场景编码 self._direct_map: Dict[str, int] = {} for name, code in (scene.get("direct_map") or {}).items(): self._direct_map[self.normalize(name)] = int(code) for label, code in ((0, 0), (1, 1), (2, 2)): self._direct_map.setdefault( self.normalize(["not_on_train", "bed", "flatbed"][label]), code ) self.require_container = bool(scene.get("require_container", True)) self.min_class_conf = float(scene.get("min_class_conf", 0.30)) self.roi_min_ratio = float(scene.get("roi_min_ratio", 0.30)) self.support_overlap = float(scene.get("support_overlap", 0.30)) self.support_dy_ratio = float(scene.get("support_dy_ratio", 0.45)) self.support_score_ratio = float(scene.get("support_score_ratio", 0.60)) self.unknown_on_no_detection = bool(scene.get("unknown_on_no_detection", True)) self.no_container_conf = float(scene.get("no_container_conf", 0.60)) self._roi_norm: List[Tuple[float, float]] = cfg.roi self._roi_cache: Dict[Tuple[int, int], List[Tuple[float, float]]] = {} # ---------------------------------------------------------------- 工具 @staticmethod def normalize(name: str) -> str: return str(name or "").strip().lower().replace("-", "_").replace(" ", "_") def group_of(self, class_name: str) -> str: """类别名 → 语义分组。""" name = self.normalize(class_name) for group in (GROUP_CONTAINER, GROUP_BED, GROUP_FLATBED, GROUP_IGNORE): if name in self._groups[group]: return group return GROUP_UNKNOWN def roi_polygon(self, width: int, height: int) -> List[Tuple[float, float]]: key = (int(width), int(height)) if key not in self._roi_cache: self._roi_cache[key] = normalized_to_pixel_polygon(self._roi_norm, width, height) return self._roi_cache[key] # ------------------------------------------------------------ 主入口 def classify( self, detections: Sequence[Box], frame_size: Tuple[int, int], ts: Optional[float] = None, frame_id: int = 0, ) -> Observation: """``frame_size`` 为 ``(width, height)``。""" ts = float(ts if ts is not None else time.time()) width, height = int(frame_size[0]), int(frame_size[1]) boxes = [b for b in detections if float(b.score) >= self.min_class_conf] if self.mode == "direct": return self._classify_direct(boxes, width, height, ts, frame_id) return self._classify_composed(boxes, width, height, ts, frame_id) # --------------------------------------------------------- direct 模式 def _classify_direct( self, boxes: List[Box], width: int, height: int, ts: float, frame_id: int, ) -> Observation: poly = self.roi_polygon(width, height) best: Optional[Tuple[Box, int, float]] = None # (box, state, score) for box in boxes: name = self.normalize(box.class_name) if name not in self._direct_map: continue ratio = box_in_polygon_ratio(box, poly) if ratio < self.roi_min_ratio: continue score = float(box.score) * (0.5 + 0.5 * ratio) if best is None or score > best[2]: best = (box, int(self._direct_map[name]), score) if best is None: if self.unknown_on_no_detection: return Observation(ts, int(SceneState.UNKNOWN), 0.0, list(boxes), "no_direct_hit", frame_id) return Observation( ts, int(SceneState.NOT_ON_TRAIN), self.no_container_conf, list(boxes), "no_direct_hit", frame_id ) box, state, score = best return Observation( ts, state, min(1.0, float(box.score)), list(boxes), "direct:%s=%.2f" % (box.class_name, box.score), frame_id, ) # ------------------------------------------------------- composed 模式 @staticmethod def _overlap_x1d(a1: float, a2: float, b1: float, b2: float) -> float: """一维交叠长度占较短区间长度的比例(0..1)。""" inter = min(a2, b2) - max(a1, b1) if inter <= 0: return 0.0 shorter = min(a2 - a1, b2 - b1) return float(inter / shorter) if shorter > 0 else 0.0 def _support_quality(self, container: Box, wagon: Box) -> Optional[Tuple[float, float]]: """判断车厢是否"托着"集装箱,返回 ``(横向交叠, 匹配质量)``,不匹配则 None。""" if container.height <= 0: return None if wagon.score < self.support_score_ratio * container.score: return None # 车厢顶边不应明显高于集装箱顶边(否则多半是别的车厢/背景) if wagon.top < container.top - 0.05 * container.height: return None ov_x = self._overlap_x1d(container.x1, container.x2, wagon.x1, wagon.x2) if ov_x < self.support_overlap: return None dy_ratio = abs(wagon.top - container.bottom) / container.height if dy_ratio > self.support_dy_ratio: return None tol = max(self.support_dy_ratio, 1e-6) quality = ov_x * max(0.2, 1.0 - 0.5 * (dy_ratio / tol)) return ov_x, quality def _best_support( self, container: Box, wagons: List[Tuple[Box, float]] ) -> Optional[Tuple[Box, float, float, float]]: """返回 ``(车厢框, 匹配分数, 横向交叠, 车厢ROI比例)``,取分数最高者。""" best: Optional[Tuple[Box, float, float, float]] = None for wagon, roi_ratio in wagons: matched = self._support_quality(container, wagon) if matched is None: continue ov_x, quality = matched score = float(wagon.score) * quality if best is None or score > best[1]: best = (wagon, score, ov_x, roi_ratio) return best def _classify_composed( self, boxes: List[Box], width: int, height: int, ts: float, frame_id: int, ) -> Observation: if not boxes: if self.unknown_on_no_detection: return Observation( ts, int(SceneState.UNKNOWN), 0.0, [], "no_detection", frame_id ) return Observation( ts, int(SceneState.NOT_ON_TRAIN), self.no_container_conf, [], "no_detection", frame_id, ) poly = self.roi_polygon(width, height) containers: List[Tuple[Box, float]] = [] beds: List[Tuple[Box, float]] = [] flats: List[Tuple[Box, float]] = [] for box in boxes: group = self.group_of(box.class_name) if group == GROUP_IGNORE or group == GROUP_UNKNOWN: continue ratio = box_in_polygon_ratio(box, poly) if ratio < self.roi_min_ratio: continue if group == GROUP_CONTAINER: containers.append((box, ratio)) elif group == GROUP_BED: beds.append((box, ratio)) elif group == GROUP_FLATBED: flats.append((box, ratio)) if not containers: # ROI 内没有集装箱 → "集装箱不在车上" wagon_score = max([b.score for b, _ in beds] + [b.score for b, _ in flats] + [0.0]) conf = min(1.0, 0.55 + 0.35 * wagon_score) reason = "no_container" + ("_wagon_seen=%.2f" % wagon_score if wagon_score else "") return Observation(ts, int(SceneState.NOT_ON_TRAIN), conf, list(boxes), reason, frame_id) container = max(containers, key=lambda item: item[0].score * (0.5 + 0.5 * item[1]))[0] bed_hit = self._best_support(container, beds) flat_hit = self._best_support(container, flats) if bed_hit is None and flat_hit is None: # 有箱,但底下既不是车斗也不是平板车(吊起来/在卡车上/堆场) conf = min(0.75, 0.40 + 0.25 * container.score) reason = "container_without_wagon(c=%.2f)" % container.score return Observation(ts, int(SceneState.NOT_ON_TRAIN), conf, list(boxes), reason, frame_id) candidates = [] if bed_hit is not None: candidates.append((int(SceneState.BED), bed_hit, "bed")) if flat_hit is not None: candidates.append((int(SceneState.FLATBED), flat_hit, "flatbed")) state, hit, tag = max(candidates, key=lambda item: item[1][1]) wagon, sup_score, ov_x, _wagon_ratio = hit conf = (container.score * wagon.score) ** 0.5 * (0.55 + 0.45 * ov_x) ambiguous = len(candidates) > 1 and max(c[1][1] for c in candidates) < 1.10 * min( c[1][1] for c in candidates ) if ambiguous: conf *= 0.85 # 两种车厢都像 → 降权,交给时序滤波去稳定 reason = "c=%.2f %s=%.2f ov=%.2f%s" % ( container.score, tag, wagon.score, ov_x, " ambiguous" if ambiguous else "", ) return Observation(ts, int(state), min(1.0, conf), list(boxes), reason, frame_id)