| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234 |
- """GB/T 45163.5 识别结果对象模型(P0-1)。
- 标准要求识别系统按**对象**给出结果,而不是只给一个场景码:被吊物、
- 抓取特征、装卸位置、装卸对象信息、环境。本模块提供与现有
- ``Observation`` / ``Decision`` 解耦的稳定数据契约:
- * 训练/推理侧新增对象时只扩展 :class:`ObjectType` 与字段,不动 PLC 的
- 0/1/2 语义;
- * ``bbox_px`` 使用原图像素坐标,``position_mm`` 使用设计文件规定的
- 坐标原点与单位;
- * ``evidence_id`` 把结果与日志/图片/视频证据关联,``reason`` 保留
- 分类器的可解释原因,便于按标准 6.x 做追溯;
- * :meth:`RecognitionResult.to_dict` 只输出 JSON 原生类型,可直接写
- JSONL,不依赖 numpy / OpenCV。
- 本模块**不改变**现有 ``Observation`` / ``Decision``,旧路径行为不变。
- """
- from __future__ import annotations
- import math
- from dataclasses import dataclass
- from enum import Enum
- from typing import Dict, List, Optional, Tuple
- from .schema import Box, Observation
- __all__ = [
- "ObjectType",
- "RecognitionResult",
- "results_from_observation",
- ]
- BBoxPx = Tuple[float, float, float, float]
- PositionMm = Tuple[float, float, float]
- class ObjectType(str, Enum):
- """标准 5.2 b) 的五类识别对象。"""
- LIFTED_OBJECT = "lifted_object" # 被吊物(集装箱/罐箱等)
- GRIP_FEATURE = "grip_feature" # 抓取特征(角件/旋锁等)
- LOAD_POSITION = "load_position" # 装卸位置(车斗/平板车/工位)
- LOAD_OBJECT_INFO = "load_object_info" # 装卸对象信息(车号/车牌/工位)
- ENVIRONMENT = "environment" # 环境(人/车/障碍物)
- @classmethod
- def parse(cls, value: object) -> "ObjectType":
- if isinstance(value, cls):
- return value
- text = str(value or "").strip().lower()
- for item in cls:
- if item.value == text:
- return item
- raise ValueError("未知识别对象类型: %r" % (value,))
- def _finite(value: float, name: str) -> float:
- number = float(value)
- if not math.isfinite(number):
- raise ValueError("%s 必须是有限数值,实际 %r" % (name, value))
- return number
- @dataclass(frozen=True)
- class RecognitionResult:
- """一条可追溯的识别结果。
- 字段顺序与标准 5.2 b) 对齐;``object_type`` / ``label`` 是最小语义,
- 其余字段为可选证据。对象类型与标签分开的原因:同一 ``lifted_object``
- 可以是 20ft/40ft 箱或罐箱,同一 ``load_position`` 可以是 1/2/0。
- """
- object_type: ObjectType
- label: str
- bbox_px: BBoxPx
- confidence: float
- ts: float
- frame_id: int
- sensor_id: str = ""
- position_mm: Optional[PositionMm] = None
- odd_id: str = ""
- evidence_id: str = ""
- reason: str = ""
- def __post_init__(self) -> None:
- object.__setattr__(self, "object_type", ObjectType.parse(self.object_type))
- label = str(self.label or "").strip()
- if not label:
- raise ValueError("RecognitionResult.label 不能为空")
- object.__setattr__(self, "label", label)
- if len(self.bbox_px) != 4:
- raise ValueError("bbox_px 需要 (x1, y1, x2, y2)")
- x1, y1, x2, y2 = (_finite(v, "bbox_px") for v in self.bbox_px)
- if x2 < x1 or y2 < y1:
- raise ValueError("bbox_px 必须满足 x2 >= x1 且 y2 >= y1")
- object.__setattr__(self, "bbox_px", (x1, y1, x2, y2))
- conf = _finite(self.confidence, "confidence")
- if not 0.0 <= conf <= 1.0:
- raise ValueError("confidence 必须在 0..1,实际 %r" % (self.confidence,))
- object.__setattr__(self, "confidence", conf)
- ts = _finite(self.ts, "ts")
- if ts < 0.0:
- raise ValueError("ts 不能为负")
- object.__setattr__(self, "ts", ts)
- object.__setattr__(self, "frame_id", int(self.frame_id))
- if self.position_mm is not None:
- if len(self.position_mm) != 3:
- raise ValueError("position_mm 需要 (x, y, z)")
- object.__setattr__(
- self, "position_mm", tuple(_finite(v, "position_mm") for v in self.position_mm)
- )
- object.__setattr__(self, "sensor_id", str(self.sensor_id or ""))
- object.__setattr__(self, "odd_id", str(self.odd_id or ""))
- object.__setattr__(self, "evidence_id", str(self.evidence_id or ""))
- def to_dict(self) -> Dict[str, object]:
- """JSON 原生字典(不包含 numpy/枚举实例)。"""
- return {
- "object_type": self.object_type.value,
- "label": self.label,
- "bbox_px": [round(float(v), 3) for v in self.bbox_px],
- "confidence": round(float(self.confidence), 6),
- "ts": round(float(self.ts), 6),
- "frame_id": int(self.frame_id),
- "sensor_id": self.sensor_id,
- "position_mm": (
- None if self.position_mm is None
- else [round(float(v), 3) for v in self.position_mm]
- ),
- "odd_id": self.odd_id,
- "evidence_id": self.evidence_id,
- "reason": self.reason,
- }
- @classmethod
- def from_dict(cls, data: Dict[str, object]) -> "RecognitionResult":
- position = data.get("position_mm")
- bbox = data.get("bbox_px") or (0.0, 0.0, 0.0, 0.0)
- return cls(
- object_type=ObjectType.parse(data.get("object_type")),
- label=str(data.get("label", "")),
- bbox_px=tuple(float(v) for v in bbox), # type: ignore[arg-type]
- confidence=float(data.get("confidence", 0.0)),
- ts=float(data.get("ts", 0.0)),
- frame_id=int(data.get("frame_id", 0) or 0),
- sensor_id=str(data.get("sensor_id", "")),
- position_mm=(
- None if position is None
- else tuple(float(v) for v in position) # type: ignore[arg-type]
- ),
- odd_id=str(data.get("odd_id", "")),
- evidence_id=str(data.get("evidence_id", "")),
- reason=str(data.get("reason", "")),
- )
- @classmethod
- def from_box(
- cls,
- box: Box,
- *,
- object_type: ObjectType = ObjectType.LIFTED_OBJECT,
- ts: float = 0.0,
- frame_id: int = 0,
- sensor_id: str = "",
- position_mm: Optional[PositionMm] = None,
- odd_id: str = "",
- evidence_id: str = "",
- reason: str = "",
- ) -> "RecognitionResult":
- return cls(
- object_type=object_type,
- label=box.class_name or "object",
- bbox_px=(box.x1, box.y1, box.x2, box.y2),
- confidence=float(box.score),
- ts=ts,
- frame_id=frame_id,
- sensor_id=sensor_id,
- position_mm=position_mm,
- odd_id=odd_id,
- evidence_id=evidence_id,
- reason=reason,
- )
- def results_from_observation(
- observation: Observation,
- *,
- sensor_id: str = "",
- odd_id: str = "",
- include_environment: bool = False,
- ) -> List[RecognitionResult]:
- """把旧 ``Observation.detections`` 映射成标准对象结果。
- 这是**兼容层**:旧分类器只输出检测框,没有抓取特征/位置 mm 等
- 字段;本函数只做可解释的粗映射,不伪造毫米级位置。新模型应直接
- 构造 :class:`RecognitionResult`。
- """
- loading_labels = {
- "bed", "wagon_bed", "hopper_wagon", "gondola",
- "flatbed", "flat_wagon", "platform_wagon",
- }
- env_labels = {"person", "people", "crane", "spreader", "truck", "wheel", "rail"}
- results: List[RecognitionResult] = []
- for index, box in enumerate(observation.detections):
- name = str(box.class_name or "").strip().lower()
- if name in loading_labels:
- object_type = ObjectType.LOAD_POSITION
- elif name in env_labels:
- if not include_environment:
- continue
- object_type = ObjectType.ENVIRONMENT
- else:
- object_type = ObjectType.LIFTED_OBJECT
- results.append(
- RecognitionResult.from_box(
- box,
- object_type=object_type,
- ts=observation.ts,
- frame_id=observation.frame_id,
- sensor_id=sensor_id,
- odd_id=odd_id,
- evidence_id="%d:%d" % (int(observation.frame_id), int(index)),
- reason=observation.reason,
- )
- )
- return results
|