"""推理后处理:解析 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 from .preproc import unletterbox_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 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 boxes 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``。""" boxes: List[Box] = [] for row in arr: score = float(row[4]) if score < conf_thres: continue cls_id = int(round(float(row[5]))) x1, y1, x2, y2 = unletterbox_box( float(row[0]), float(row[1]), float(row[2]), float(row[3]), ratio, pad, image_size ) if x2 - x1 < 1 or y2 - y1 < 1: continue boxes.append( Box(x1, y1, x2, y2, 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 scores = scores[keep] cls_ids = cls_ids[keep] boxes: List[Box] = [] for i in range(len(scores)): rx1, ry1, rx2, ry2 = unletterbox_box( float(x1[i]), float(y1[i]), float(x2[i]), float(y2[i]), ratio, pad, image_size ) if rx2 - rx1 < 1 or ry2 - ry1 < 1: continue boxes.append( Box( rx1, ry1, rx2, ry2, score=float(scores[i]), class_id=int(cls_ids[i]), class_name=_label_at(int(cls_ids[i]), 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