| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459 |
- """公共数据结构:检测框、单帧观测、时序判决、PLC 快照。
- 约定
- ----
- * 检测框一律使用 **像素坐标**,原点在图像左上角,``y`` 向下增大。
- * :class:`SceneState` 的枚举值就是最终反馈给西门子 PLC 的编码,改动前先确认 PLC 侧。
- * :class:`VisionSnapshot` 是"视觉 → PLC"的唯一数据载体,Modbus/TCP 服务端与 S7 推送端
- 都必须通过它来编码,保证两条链路语义一致。
- """
- from __future__ import annotations
- from dataclasses import dataclass, field
- from enum import Enum, IntEnum
- from typing import TYPE_CHECKING, Dict, List, Sequence, Tuple
- if TYPE_CHECKING: # pragma: no cover - 仅类型检查,避免 schema ↔ recognition 循环导入
- from .recognition import RecognitionResult
- __all__ = [
- "Box",
- "CommitPhase",
- "Decision",
- "Observation",
- "PlcCommand",
- "SceneState",
- "STATE_LABELS",
- "STATE_NAME_TO_CODE",
- "StatusBits",
- "ViewMode",
- "VisionSnapshot",
- "crc16_modbus",
- "recognition_results",
- ]
- class SceneState(IntEnum):
- """反馈给 PLC 的场景编码。
- ``3``(空车)是 v2 P0-Q9 新增的**独立车型结论**,不是 ``0`` 的子类:
- ``0`` = 不是目标车(地面/堆场/卡车/其他车型),``3`` = 确认是敞车、但车斗
- 里没有箱(可以装车)。二者对 PLC 的动作含义完全不同,不能合并。
- """
- NOT_ON_TRAIN = 0 # 集装箱不在车上 / 不是目标车
- BED = 1 # 车斗(敞车,车上有箱)
- FLATBED = 2 # 平板车(平车,车上有箱)
- EMPTY = 3 # 空车(敞车,车斗内无箱)
- UNKNOWN = 255 # 视觉未就绪 / 结果不可信
- @property
- def label(self) -> str:
- return STATE_LABELS.get(int(self), "unknown")
- STATE_LABELS: Dict[int, str] = {
- 0: "not_on_train",
- 1: "bed",
- 2: "flatbed",
- 3: "empty",
- 255: "unknown",
- }
- STATE_NAME_TO_CODE: Dict[str, int] = {v: k for k, v in STATE_LABELS.items()}
- class ViewMode(str, Enum):
- """P1 双视角模式(``docs/route_v2.md`` §3)。"""
- FRONT = "front"
- HIGH = "high"
- UNKNOWN = "unknown"
- @classmethod
- def parse(cls, value: object) -> "ViewMode":
- text = str(value or "").strip().lower()
- for item in cls:
- if item.value == text:
- return item
- return cls.UNKNOWN
- class CommitPhase(str, Enum):
- """落位相位:T1 可判窗口、T2 已落位、T3 吊装中。"""
- T1 = "T1"
- T2 = "T2"
- T3 = "T3"
- class StatusBits(IntEnum):
- """``VisionSnapshot.flags`` 的位定义(同时写入 Modbus 寄存器与 S7 DB)。"""
- READY = 1 << 0 # 模型已加载且完成预热
- FRAME_OK = 1 << 1 # 最近一帧是新的(未超过 stale 时限)
- STABLE = 1 << 2 # 状态稳定,可用于联锁/自动落箱
- LOW_FPS = 1 << 3 # 帧率低于下限
- FRAME_TIMEOUT = 1 << 4 # 长时间拿不到帧(相机/网络异常)
- ON_DEMAND = 1 << 5 # 当前处于 PLC 请求触发的按需识别
- RESULT_VALID = 1 << 6 # 置信度达到阈值,结果有效
- PUBLISH_OK = 1 << 7 # 最近一次向 PLC 发布成功(服务端模式恒为 1)
- # P0-2:GB/T 45163.5 5.1.3/5.1.4 的感知健康位(bit8~12)。
- # 约束:PERCEPTION_UNCERTAIN=1 时 RESULT_VALID 必须为 0。
- PERCEPTION_UNCERTAIN = 1 << 8 # 感知不确定(低置信度/证据不足/模糊等)
- MRC_REQUEST = 1 << 9 # 请求 PLC 进入最小风险状态(MRC)
- SENSOR_DEGRADED = 1 << 10 # 图像质量/传感器退化(模糊、过曝、遮挡)
- CALIB_STALE = 1 << 11 # 标定过期或漂移
- DATA_LOSS = 1 << 12 # 数据链中断(取帧超时/丢流)
- def crc16_modbus(data: bytes) -> int:
- """CRC-16/MODBUS,用于快照校验,便于 PLC 侧判断数据是否完整/刷新。"""
- crc = 0xFFFF
- for byte in data:
- crc ^= byte
- for _ in range(8):
- if crc & 0x0001:
- crc = (crc >> 1) ^ 0xA001
- else:
- crc >>= 1
- return crc & 0xFFFF
- @dataclass
- class Box:
- """一个检测框。``class_id`` 为模型输出索引,``class_name`` 为标签名。"""
- x1: float
- y1: float
- x2: float
- y2: float
- score: float = 0.0
- class_id: int = -1
- class_name: str = ""
- def __post_init__(self) -> None:
- if self.x2 < self.x1:
- self.x1, self.x2 = self.x2, self.x1
- if self.y2 < self.y1:
- self.y1, self.y2 = self.y2, self.y1
- # -- 几何属性 ---------------------------------------------------------
- @property
- def width(self) -> float:
- return max(0.0, self.x2 - self.x1)
- @property
- def height(self) -> float:
- return max(0.0, self.y2 - self.y1)
- @property
- def area(self) -> float:
- return self.width * self.height
- @property
- def cx(self) -> float:
- return (self.x1 + self.x2) / 2.0
- @property
- def cy(self) -> float:
- return (self.y1 + self.y2) / 2.0
- @property
- def top(self) -> float:
- return min(self.y1, self.y2)
- @property
- def bottom(self) -> float:
- return max(self.y1, self.y2)
- def as_xyxy(self) -> Tuple[float, float, float, float]:
- return (self.x1, self.y1, self.x2, self.y2)
- def as_list(self) -> List[float]:
- return [float(self.x1), float(self.y1), float(self.x2), float(self.y2)]
- def to_dict(self) -> Dict[str, object]:
- return {
- "box": [round(v, 1) for v in self.as_list()],
- "score": round(float(self.score), 4),
- "class_id": int(self.class_id),
- "class_name": self.class_name,
- }
- # -- 构造 / 变换 ------------------------------------------------------
- @classmethod
- def from_xywh(
- cls,
- cx: float,
- cy: float,
- w: float,
- h: float,
- score: float = 0.0,
- class_id: int = -1,
- class_name: str = "",
- ) -> "Box":
- return cls(
- cx - w / 2.0,
- cy - h / 2.0,
- cx + w / 2.0,
- cy + h / 2.0,
- score=score,
- class_id=class_id,
- class_name=class_name,
- )
- def clip(self, width: float, height: float) -> "Box":
- """裁剪到图像范围内。"""
- return Box(
- min(max(self.x1, 0.0), width),
- min(max(self.y1, 0.0), height),
- min(max(self.x2, 0.0), width),
- min(max(self.y2, 0.0), height),
- score=self.score,
- class_id=self.class_id,
- class_name=self.class_name,
- )
- # -- 关系运算 ---------------------------------------------------------
- def intersection(self, other: "Box") -> float:
- ix1 = max(self.x1, other.x1)
- iy1 = max(self.y1, other.y1)
- ix2 = min(self.x2, other.x2)
- iy2 = min(self.y2, other.y2)
- if ix2 <= ix1 or iy2 <= iy1:
- return 0.0
- return float((ix2 - ix1) * (iy2 - iy1))
- def iou(self, other: "Box") -> float:
- inter = self.intersection(other)
- if inter <= 0.0:
- return 0.0
- union = self.area + other.area - inter
- return float(inter / union) if union > 0 else 0.0
- def overlap_ratio(self, other: "Box") -> float:
- """交叠面积占两者**较小**面积的比例(小框被大框包含时为 1)。"""
- inter = self.intersection(other)
- if inter <= 0.0:
- return 0.0
- denom = min(self.area, other.area)
- return float(inter / denom) if denom > 0 else 0.0
- def contains_point(self, x: float, y: float) -> bool:
- return self.x1 <= x <= self.x2 and self.y1 <= y <= self.y2
- @dataclass
- class Observation:
- """单帧的场景判定结果(未经时序滤波)。"""
- ts: float = 0.0
- state: int = int(SceneState.UNKNOWN)
- confidence: float = 0.0
- detections: List[Box] = field(default_factory=list)
- reason: str = ""
- frame_id: int = 0
- @property
- def is_valid(self) -> bool:
- return int(self.state) != int(SceneState.UNKNOWN)
- @dataclass
- class Decision:
- """时序滤波后的判决,可直接发布给 PLC。"""
- state: int = int(SceneState.UNKNOWN)
- confidence: float = 0.0
- stable: bool = False
- seq: int = 0 # 状态每提交一次变化 +1,PLC 用它判断"有新结果"
- since_ts: float = 0.0 # 当前状态起始时间(秒,time.time())
- reason: str = "init"
- changed: bool = False # 本次 update 是否发生了状态变化
- @property
- def label(self) -> str:
- return STATE_LABELS.get(int(self.state), "unknown")
- def to_dict(self) -> Dict[str, object]:
- return {
- "state": int(self.state),
- "label": self.label,
- "confidence": round(float(self.confidence), 4),
- "stable": bool(self.stable),
- "seq": int(self.seq),
- "reason": self.reason,
- }
- @dataclass
- class VisionSnapshot:
- """视觉侧写入 PLC 的一张"结果快照"。
- Modbus/TCP 服务端把它铺到输入寄存器(FC4 只读),S7 推送端把它打成 DB 字节数组。
- 字段宽度之和 = 11 个 16bit 字,第 12 个字是 CRC-16/MODBUS。
- """
- state: int = int(SceneState.UNKNOWN)
- confidence: int = 0 # 千分比 0..1000
- flags: int = 0
- seq: int = 0 # 32bit,状态变化计数
- ts_s: int = 0 # unix 秒(32bit)
- heartbeat: int = 0 # 0..65535,每个心跳周期 +1
- fps_x10: int = 0 # 帧率 x10
- latency_ms: int = 0 # 单帧端到端耗时
- reserved: int = 0
- #: 寄存器布局:字段 → 16bit 字宽度
- REGISTER_LAYOUT: Tuple[Tuple[str, int], ...] = (
- ("state", 1),
- ("confidence", 1),
- ("flags", 1),
- ("seq", 2),
- ("ts_s", 2),
- ("heartbeat", 1),
- ("fps_x10", 1),
- ("latency_ms", 1),
- ("reserved", 1),
- )
- @staticmethod
- def register_count() -> int:
- return int(sum(width for _, width in VisionSnapshot.REGISTER_LAYOUT)) + 1 # +1 = CRC
- def to_registers(self) -> List[int]:
- """铺成 16bit 寄存器数组(大端),最后一个字为 CRC-16/MODBUS 校验。"""
- words = [
- int(self.state) & 0xFFFF,
- int(self.confidence) & 0xFFFF,
- int(self.flags) & 0xFFFF,
- (int(self.seq) >> 16) & 0xFFFF,
- int(self.seq) & 0xFFFF,
- (int(self.ts_s) >> 16) & 0xFFFF,
- int(self.ts_s) & 0xFFFF,
- int(self.heartbeat) & 0xFFFF,
- int(self.fps_x10) & 0xFFFF,
- int(self.latency_ms) & 0xFFFF,
- int(self.reserved) & 0xFFFF,
- ]
- payload = b"".join(int(w).to_bytes(2, "big") for w in words)
- words.append(crc16_modbus(payload))
- return words
- @classmethod
- def from_registers(cls, words: Sequence[int], verify: bool = False) -> "VisionSnapshot":
- values = [int(w) & 0xFFFF for w in words]
- if len(values) < cls.register_count():
- raise ValueError(
- "寄存器数量不足: 需要 %d,实际 %d" % (cls.register_count(), len(values))
- )
- if verify:
- payload = b"".join(int(w).to_bytes(2, "big") for w in values[:-1])
- if crc16_modbus(payload) != values[-1]:
- raise ValueError("CRC 校验失败,数据可能不完整")
- return cls(
- state=values[0],
- confidence=values[1],
- flags=values[2],
- seq=(values[3] << 16) | values[4],
- ts_s=(values[5] << 16) | values[6],
- heartbeat=values[7],
- fps_x10=values[8],
- latency_ms=values[9],
- reserved=values[10],
- )
- def to_db_bytes(self) -> bytes:
- """S7 DB 字节块(每字大端),布局与 :meth:`to_registers` 一致。"""
- return b"".join(int(w).to_bytes(2, "big") for w in self.to_registers())
- def has_flag(self, bit: StatusBits) -> bool:
- return bool(int(self.flags) & int(bit))
- def to_dict(self) -> Dict[str, object]:
- return {
- "state": int(self.state),
- "state_label": STATE_LABELS.get(int(self.state), "unknown"),
- "confidence": int(self.confidence),
- "flags": int(self.flags),
- "seq": int(self.seq),
- "ts_s": int(self.ts_s),
- "heartbeat": int(self.heartbeat),
- "fps_x10": int(self.fps_x10),
- "latency_ms": int(self.latency_ms),
- }
- @dataclass
- class PlcCommand:
- """PLC → 视觉的指令块(保持寄存器 FC3/FC6/FC16)。"""
- cmd: int = 0 # 0=空闲, 1=请求识别(按需), 2=复位, 3=清统计
- preset: int = 0 # ROI / 相机预设编号
- min_conf: int = 0 # 覆盖最小置信度(千分比,0=用配置值)
- reserved: int = 0
- #: 保持寄存器布局:字段 → 16bit 字宽度
- REGISTER_LAYOUT: Tuple[Tuple[str, int], ...] = (
- ("cmd", 1),
- ("preset", 1),
- ("min_conf", 1),
- ("reserved", 1),
- )
- @staticmethod
- def register_count() -> int:
- return int(sum(width for _, width in PlcCommand.REGISTER_LAYOUT))
- def to_registers(self) -> List[int]:
- return [
- int(self.cmd) & 0xFFFF,
- int(self.preset) & 0xFFFF,
- int(self.min_conf) & 0xFFFF,
- int(self.reserved) & 0xFFFF,
- ]
- @classmethod
- def from_registers(cls, words: Sequence[int]) -> "PlcCommand":
- values = [int(w) & 0xFFFF for w in words]
- while len(values) < cls.register_count():
- values.append(0)
- return cls(cmd=values[0], preset=values[1], min_conf=values[2], reserved=values[3])
- def is_request(self) -> bool:
- return int(self.cmd) == 1
- def is_reset(self) -> bool:
- return int(self.cmd) == 2
- def recognition_results(
- observation: Observation,
- *,
- sensor_id: str = "",
- odd_id: str = "",
- include_environment: bool = False,
- ) -> List["RecognitionResult"]:
- """兼容入口:旧 ``Observation`` → 标准识别对象结果(P0-1)。
- 实现放在 :mod:`portcv.recognition`;这里只做延迟导入,保持
- ``Observation`` / ``Decision`` 字段与旧行为完全不变。
- """
- from .recognition import results_from_observation
- return results_from_observation(
- observation,
- sensor_id=sensor_id,
- odd_id=odd_id,
- include_environment=include_environment,
- )
|