"""推理后处理:解析 YOLO 输出 → :class:`~portcv.schema.Box` 列表。 兼容三种常见导出形态 -------------------- * ``(1, 4+nc, N)`` / ``(1, N, 4+nc)``:YOLOv8/v11 系列 xywh + 类别分数; * ``(1, 5+nc, N)`` / ``(1, N, 5+nc)``:YOLOv5 系列 xywh + obj + 类别分数; * ``(1, N, 6)``(``nms_free=True``):``x1,y1,x2,y2,score,class_id`` 端到端输出。 坐标系约定:输入张量坐标是 **letterbox 后的输入尺寸**,本模块负责还原到原图。 """ from __future__ import annotations from typing import List, Optional, Sequence, Tuple import numpy as np from ..schema import Box __all__ = ["decode_yolo_output", "draw_boxes"] try: # pragma: no cover import cv2 except ImportError: # pragma: no cover cv2 = None # type: ignore def _as_2d(raw: np.ndarray, nc: int, nms_free: bool) -> np.ndarray: """把输出统一成 ``(N, C)``(C = 4+nc / 5+nc / 6)。""" arr = np.asarray(raw, dtype=np.float32) while arr.ndim > 2: arr = arr[0] if arr.ndim == 1: arr = arr[None] cols = int(arr.shape[1]) expected = 6 if nms_free else (4 + nc) expected_obj = 5 + nc if cols not in (expected, expected_obj, 6) and arr.shape[0] in (expected, expected_obj, 6): arr = arr.T return np.ascontiguousarray(arr) def _label_at(index: int, labels: Sequence[str]) -> str: if 0 <= int(index) < len(labels): return str(labels[int(index)]) return "cls_%d" % index def _unletterbox_arrays( x1: np.ndarray, y1: np.ndarray, x2: np.ndarray, y2: np.ndarray, ratio: float, pad: Tuple[float, float], image_size: Tuple[int, int], ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """向量化版 :func:`~portcv.detect.preproc.unletterbox_box`(逐元素结果一致)。 8400 个候选框逐个调 Python 标量函数是后处理的主要热点,这里一次算完。 用 float64 与标量版 ``float(x) - pad`` 的精度一致;裁剪后可能留下 NaN, 由调用方按「``< 1`` 才丢弃」的老语义处理(NaN 的 ``< 1`` 为 False,即保留)。 """ pad_x, pad_y = float(pad[0]), float(pad[1]) scale = float(ratio) if float(ratio) > 0 else 1.0 width, height = float(image_size[0]), float(image_size[1]) x1 = (x1.astype(np.float64) - pad_x) / scale x2 = (x2.astype(np.float64) - pad_x) / scale y1 = (y1.astype(np.float64) - pad_y) / scale y2 = (y2.astype(np.float64) - pad_y) / scale np.clip(x1, 0.0, width, out=x1) np.clip(x2, 0.0, width, out=x2) np.clip(y1, 0.0, height, out=y1) np.clip(y2, 0.0, height, out=y2) return x1, y1, x2, y2 def decode_yolo_output( raw: np.ndarray, labels: Sequence[str], conf_thres: float = 0.35, iou_thres: float = 0.5, max_det: int = 60, nms_free: bool = False, ratio: float = 1.0, pad: Tuple[float, float] = (0.0, 0.0), image_size: Tuple[int, int] = (640, 640), apply_nms: bool = True, ) -> List[Box]: """解析模型输出。``image_size`` 为原图 ``(width, height)``。""" nc = len(labels) arr = _as_2d(raw, nc, nms_free) if arr.size == 0: return [] cols = int(arr.shape[1]) if cols == 6 and nms_free: boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size) elif cols in (4 + nc, 5 + nc): boxes = _decode_xywh( arr, labels, conf_thres, ratio, pad, image_size, use_obj=(cols == 5 + nc) ) elif cols == 6: boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size) else: return [] if len(boxes) > max_det: boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det] if apply_nms and len(boxes) > 1 and not nms_free: from ..logic.geometry import nms as _nms boxes = _nms(boxes, iou_thres, per_class=True) if len(boxes) > max_det: boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det] return boxes def _decode_nms_free( arr: np.ndarray, labels: Sequence[str], conf_thres: float, ratio: float, pad: Tuple[float, float], image_size: Tuple[int, int], ) -> List[Box]: """``N x 6``:``x1, y1, x2, y2, score, class_id``(向量化)。""" keep = arr[:, 4] >= conf_thres if not np.any(keep): return [] rows = arr[keep] rx1, ry1, rx2, ry2 = _unletterbox_arrays( rows[:, 0], rows[:, 1], rows[:, 2], rows[:, 3], ratio, pad, image_size ) # 与标量版等价:只有 ``< 1`` 才丢弃(NaN 会被保留) valid = ~((rx2 - rx1) < 1.0) & ~((ry2 - ry1) < 1.0) boxes: List[Box] = [] for i in np.nonzero(valid)[0]: score = float(rows[i, 4]) cls_id = int(round(float(rows[i, 5]))) boxes.append( Box( float(rx1[i]), float(ry1[i]), float(rx2[i]), float(ry2[i]), score=score, class_id=cls_id, class_name=_label_at(cls_id, labels), ) ) return boxes def _decode_xywh( arr: np.ndarray, labels: Sequence[str], conf_thres: float, ratio: float, pad: Tuple[float, float], image_size: Tuple[int, int], use_obj: bool, ) -> List[Box]: """``N x (4+nc)`` 或 ``N x (5+nc)``:cxcywh(+obj)+类别分数(向量化裁剪,只为保留框建对象)。""" nc = len(labels) cx, cy, w, h = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3] if use_obj: obj = arr[:, 4] cls_scores = arr[:, 5 : 5 + nc] cls_ids = np.argmax(cls_scores, axis=1) scores = obj * cls_scores[np.arange(len(obj)), cls_ids] else: cls_scores = arr[:, 4 : 4 + nc] cls_ids = np.argmax(cls_scores, axis=1) scores = cls_scores[np.arange(len(cls_ids)), cls_ids] keep = scores >= conf_thres if not np.any(keep): return [] x1 = cx[keep] - w[keep] / 2.0 y1 = cy[keep] - h[keep] / 2.0 x2 = cx[keep] + w[keep] / 2.0 y2 = cy[keep] + h[keep] / 2.0 rx1, ry1, rx2, ry2 = _unletterbox_arrays(x1, y1, x2, y2, ratio, pad, image_size) valid = ~((rx2 - rx1) < 1.0) & ~((ry2 - ry1) < 1.0) scores = scores[keep] cls_ids = cls_ids[keep] boxes: List[Box] = [] for i in np.nonzero(valid)[0]: cls_id = int(cls_ids[i]) boxes.append( Box( float(rx1[i]), float(ry1[i]), float(rx2[i]), float(ry2[i]), score=float(scores[i]), class_id=cls_id, class_name=_label_at(cls_id, labels), ) ) return boxes def draw_boxes( image: np.ndarray, boxes: Sequence[Box], roi: Optional[Sequence[Tuple[float, float]]] = None, texts: Optional[Sequence[str]] = None, ) -> np.ndarray: """画框 + ROI + 文本,用于联调预览与难例复盘(原地绘制并返回同一张图)。""" if cv2 is None: return image colors = { "container": (0, 215, 255), "bed": (0, 255, 0), "flatbed": (255, 128, 0), } for box in boxes: color = colors.get(box.class_name, (0, 0, 255)) x1, y1, x2, y2 = [int(v) for v in box.as_xyxy()] cv2.rectangle(image, (x1, y1), (x2, y2), color, 2) tag = "%s %.2f" % (box.class_name, box.score) cv2.putText(image, tag, (x1, max(12, y1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1) if roi: pts = np.array([[int(x), int(y)] for x, y in roi], dtype=np.int32) cv2.polylines(image, [pts], True, (0, 255, 255), 2) if texts: for i, line in enumerate(texts): cv2.putText( image, str(line), (10, 24 + i * 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2 ) return image