recognition.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. """GB/T 45163.5 识别结果对象模型(P0-1)。
  2. 标准要求识别系统按**对象**给出结果,而不是只给一个场景码:被吊物、
  3. 抓取特征、装卸位置、装卸对象信息、环境。本模块提供与现有
  4. ``Observation`` / ``Decision`` 解耦的稳定数据契约:
  5. * 训练/推理侧新增对象时只扩展 :class:`ObjectType` 与字段,不动 PLC 的
  6. 0/1/2 语义;
  7. * ``bbox_px`` 使用原图像素坐标,``position_mm`` 使用设计文件规定的
  8. 坐标原点与单位;
  9. * ``evidence_id`` 把结果与日志/图片/视频证据关联,``reason`` 保留
  10. 分类器的可解释原因,便于按标准 6.x 做追溯;
  11. * :meth:`RecognitionResult.to_dict` 只输出 JSON 原生类型,可直接写
  12. JSONL,不依赖 numpy / OpenCV。
  13. 本模块**不改变**现有 ``Observation`` / ``Decision``,旧路径行为不变。
  14. """
  15. from __future__ import annotations
  16. import math
  17. from dataclasses import dataclass
  18. from enum import Enum
  19. from typing import Dict, List, Optional, Tuple
  20. from .schema import Box, Observation
  21. __all__ = [
  22. "ObjectType",
  23. "RecognitionResult",
  24. "results_from_observation",
  25. ]
  26. BBoxPx = Tuple[float, float, float, float]
  27. PositionMm = Tuple[float, float, float]
  28. class ObjectType(str, Enum):
  29. """标准 5.2 b) 的五类识别对象。"""
  30. LIFTED_OBJECT = "lifted_object" # 被吊物(集装箱/罐箱等)
  31. GRIP_FEATURE = "grip_feature" # 抓取特征(角件/旋锁等)
  32. LOAD_POSITION = "load_position" # 装卸位置(车斗/平板车/工位)
  33. LOAD_OBJECT_INFO = "load_object_info" # 装卸对象信息(车号/车牌/工位)
  34. ENVIRONMENT = "environment" # 环境(人/车/障碍物)
  35. @classmethod
  36. def parse(cls, value: object) -> "ObjectType":
  37. if isinstance(value, cls):
  38. return value
  39. text = str(value or "").strip().lower()
  40. for item in cls:
  41. if item.value == text:
  42. return item
  43. raise ValueError("未知识别对象类型: %r" % (value,))
  44. def _finite(value: float, name: str) -> float:
  45. number = float(value)
  46. if not math.isfinite(number):
  47. raise ValueError("%s 必须是有限数值,实际 %r" % (name, value))
  48. return number
  49. @dataclass(frozen=True)
  50. class RecognitionResult:
  51. """一条可追溯的识别结果。
  52. 字段顺序与标准 5.2 b) 对齐;``object_type`` / ``label`` 是最小语义,
  53. 其余字段为可选证据。对象类型与标签分开的原因:同一 ``lifted_object``
  54. 可以是 20ft/40ft 箱或罐箱,同一 ``load_position`` 可以是 1/2/0。
  55. """
  56. object_type: ObjectType
  57. label: str
  58. bbox_px: BBoxPx
  59. confidence: float
  60. ts: float
  61. frame_id: int
  62. sensor_id: str = ""
  63. position_mm: Optional[PositionMm] = None
  64. odd_id: str = ""
  65. evidence_id: str = ""
  66. reason: str = ""
  67. def __post_init__(self) -> None:
  68. object.__setattr__(self, "object_type", ObjectType.parse(self.object_type))
  69. label = str(self.label or "").strip()
  70. if not label:
  71. raise ValueError("RecognitionResult.label 不能为空")
  72. object.__setattr__(self, "label", label)
  73. if len(self.bbox_px) != 4:
  74. raise ValueError("bbox_px 需要 (x1, y1, x2, y2)")
  75. x1, y1, x2, y2 = (_finite(v, "bbox_px") for v in self.bbox_px)
  76. if x2 < x1 or y2 < y1:
  77. raise ValueError("bbox_px 必须满足 x2 >= x1 且 y2 >= y1")
  78. object.__setattr__(self, "bbox_px", (x1, y1, x2, y2))
  79. conf = _finite(self.confidence, "confidence")
  80. if not 0.0 <= conf <= 1.0:
  81. raise ValueError("confidence 必须在 0..1,实际 %r" % (self.confidence,))
  82. object.__setattr__(self, "confidence", conf)
  83. ts = _finite(self.ts, "ts")
  84. if ts < 0.0:
  85. raise ValueError("ts 不能为负")
  86. object.__setattr__(self, "ts", ts)
  87. object.__setattr__(self, "frame_id", int(self.frame_id))
  88. if self.position_mm is not None:
  89. if len(self.position_mm) != 3:
  90. raise ValueError("position_mm 需要 (x, y, z)")
  91. object.__setattr__(
  92. self, "position_mm", tuple(_finite(v, "position_mm") for v in self.position_mm)
  93. )
  94. object.__setattr__(self, "sensor_id", str(self.sensor_id or ""))
  95. object.__setattr__(self, "odd_id", str(self.odd_id or ""))
  96. object.__setattr__(self, "evidence_id", str(self.evidence_id or ""))
  97. def to_dict(self) -> Dict[str, object]:
  98. """JSON 原生字典(不包含 numpy/枚举实例)。"""
  99. return {
  100. "object_type": self.object_type.value,
  101. "label": self.label,
  102. "bbox_px": [round(float(v), 3) for v in self.bbox_px],
  103. "confidence": round(float(self.confidence), 6),
  104. "ts": round(float(self.ts), 6),
  105. "frame_id": int(self.frame_id),
  106. "sensor_id": self.sensor_id,
  107. "position_mm": (
  108. None if self.position_mm is None
  109. else [round(float(v), 3) for v in self.position_mm]
  110. ),
  111. "odd_id": self.odd_id,
  112. "evidence_id": self.evidence_id,
  113. "reason": self.reason,
  114. }
  115. @classmethod
  116. def from_dict(cls, data: Dict[str, object]) -> "RecognitionResult":
  117. position = data.get("position_mm")
  118. bbox = data.get("bbox_px") or (0.0, 0.0, 0.0, 0.0)
  119. return cls(
  120. object_type=ObjectType.parse(data.get("object_type")),
  121. label=str(data.get("label", "")),
  122. bbox_px=tuple(float(v) for v in bbox), # type: ignore[arg-type]
  123. confidence=float(data.get("confidence", 0.0)),
  124. ts=float(data.get("ts", 0.0)),
  125. frame_id=int(data.get("frame_id", 0) or 0),
  126. sensor_id=str(data.get("sensor_id", "")),
  127. position_mm=(
  128. None if position is None
  129. else tuple(float(v) for v in position) # type: ignore[arg-type]
  130. ),
  131. odd_id=str(data.get("odd_id", "")),
  132. evidence_id=str(data.get("evidence_id", "")),
  133. reason=str(data.get("reason", "")),
  134. )
  135. @classmethod
  136. def from_box(
  137. cls,
  138. box: Box,
  139. *,
  140. object_type: ObjectType = ObjectType.LIFTED_OBJECT,
  141. ts: float = 0.0,
  142. frame_id: int = 0,
  143. sensor_id: str = "",
  144. position_mm: Optional[PositionMm] = None,
  145. odd_id: str = "",
  146. evidence_id: str = "",
  147. reason: str = "",
  148. ) -> "RecognitionResult":
  149. return cls(
  150. object_type=object_type,
  151. label=box.class_name or "object",
  152. bbox_px=(box.x1, box.y1, box.x2, box.y2),
  153. confidence=float(box.score),
  154. ts=ts,
  155. frame_id=frame_id,
  156. sensor_id=sensor_id,
  157. position_mm=position_mm,
  158. odd_id=odd_id,
  159. evidence_id=evidence_id,
  160. reason=reason,
  161. )
  162. def results_from_observation(
  163. observation: Observation,
  164. *,
  165. sensor_id: str = "",
  166. odd_id: str = "",
  167. include_environment: bool = False,
  168. ) -> List[RecognitionResult]:
  169. """把旧 ``Observation.detections`` 映射成标准对象结果。
  170. 这是**兼容层**:旧分类器只输出检测框,没有抓取特征/位置 mm 等
  171. 字段;本函数只做可解释的粗映射,不伪造毫米级位置。新模型应直接
  172. 构造 :class:`RecognitionResult`。
  173. """
  174. loading_labels = {
  175. "bed", "wagon_bed", "hopper_wagon", "gondola",
  176. "flatbed", "flat_wagon", "platform_wagon",
  177. }
  178. env_labels = {"person", "people", "crane", "spreader", "truck", "wheel", "rail"}
  179. results: List[RecognitionResult] = []
  180. for index, box in enumerate(observation.detections):
  181. name = str(box.class_name or "").strip().lower()
  182. if name in loading_labels:
  183. object_type = ObjectType.LOAD_POSITION
  184. elif name in env_labels:
  185. if not include_environment:
  186. continue
  187. object_type = ObjectType.ENVIRONMENT
  188. else:
  189. object_type = ObjectType.LIFTED_OBJECT
  190. results.append(
  191. RecognitionResult.from_box(
  192. box,
  193. object_type=object_type,
  194. ts=observation.ts,
  195. frame_id=observation.frame_id,
  196. sensor_id=sensor_id,
  197. odd_id=odd_id,
  198. evidence_id="%d:%d" % (int(observation.frame_id), int(index)),
  199. reason=observation.reason,
  200. )
  201. )
  202. return results