postproc.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. """推理后处理:解析 YOLO 输出 → :class:`~portcv.schema.Box` 列表。
  2. 兼容三种常见导出形态
  3. --------------------
  4. * ``(1, 4+nc, N)`` / ``(1, N, 4+nc)``:YOLOv8/v11 系列 xywh + 类别分数;
  5. * ``(1, 5+nc, N)`` / ``(1, N, 5+nc)``:YOLOv5 系列 xywh + obj + 类别分数;
  6. * ``(1, N, 6)``(``nms_free=True``):``x1,y1,x2,y2,score,class_id`` 端到端输出。
  7. 坐标系约定:输入张量坐标是 **letterbox 后的输入尺寸**,本模块负责还原到原图。
  8. """
  9. from __future__ import annotations
  10. from typing import List, Optional, Sequence, Tuple
  11. import numpy as np
  12. from ..schema import Box
  13. from .preproc import unletterbox_box
  14. __all__ = ["decode_yolo_output", "draw_boxes"]
  15. try: # pragma: no cover
  16. import cv2
  17. except ImportError: # pragma: no cover
  18. cv2 = None # type: ignore
  19. def _as_2d(raw: np.ndarray, nc: int, nms_free: bool) -> np.ndarray:
  20. """把输出统一成 ``(N, C)``(C = 4+nc / 5+nc / 6)。"""
  21. arr = np.asarray(raw, dtype=np.float32)
  22. while arr.ndim > 2:
  23. arr = arr[0]
  24. if arr.ndim == 1:
  25. arr = arr[None]
  26. cols = int(arr.shape[1])
  27. expected = 6 if nms_free else (4 + nc)
  28. expected_obj = 5 + nc
  29. if cols not in (expected, expected_obj, 6) and arr.shape[0] in (expected, expected_obj, 6):
  30. arr = arr.T
  31. return np.ascontiguousarray(arr)
  32. def _label_at(index: int, labels: Sequence[str]) -> str:
  33. if 0 <= int(index) < len(labels):
  34. return str(labels[int(index)])
  35. return "cls_%d" % index
  36. def decode_yolo_output(
  37. raw: np.ndarray,
  38. labels: Sequence[str],
  39. conf_thres: float = 0.35,
  40. iou_thres: float = 0.5,
  41. max_det: int = 60,
  42. nms_free: bool = False,
  43. ratio: float = 1.0,
  44. pad: Tuple[float, float] = (0.0, 0.0),
  45. image_size: Tuple[int, int] = (640, 640),
  46. apply_nms: bool = True,
  47. ) -> List[Box]:
  48. """解析模型输出。``image_size`` 为原图 ``(width, height)``。"""
  49. nc = len(labels)
  50. arr = _as_2d(raw, nc, nms_free)
  51. if arr.size == 0:
  52. return []
  53. cols = int(arr.shape[1])
  54. if cols == 6 and nms_free:
  55. boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size)
  56. elif cols in (4 + nc, 5 + nc):
  57. boxes = _decode_xywh(
  58. arr, labels, conf_thres, ratio, pad, image_size, use_obj=(cols == 5 + nc)
  59. )
  60. elif cols == 6:
  61. boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size)
  62. else:
  63. return []
  64. if len(boxes) > max_det:
  65. boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det]
  66. if apply_nms and boxes and not nms_free:
  67. from ..logic.geometry import nms as _nms
  68. boxes = _nms(boxes, iou_thres, per_class=True)
  69. if len(boxes) > max_det:
  70. boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det]
  71. return boxes
  72. def _decode_nms_free(
  73. arr: np.ndarray,
  74. labels: Sequence[str],
  75. conf_thres: float,
  76. ratio: float,
  77. pad: Tuple[float, float],
  78. image_size: Tuple[int, int],
  79. ) -> List[Box]:
  80. """``N x 6``:``x1, y1, x2, y2, score, class_id``。"""
  81. boxes: List[Box] = []
  82. for row in arr:
  83. score = float(row[4])
  84. if score < conf_thres:
  85. continue
  86. cls_id = int(round(float(row[5])))
  87. x1, y1, x2, y2 = unletterbox_box(
  88. float(row[0]), float(row[1]), float(row[2]), float(row[3]), ratio, pad, image_size
  89. )
  90. if x2 - x1 < 1 or y2 - y1 < 1:
  91. continue
  92. boxes.append(
  93. Box(x1, y1, x2, y2, score=score, class_id=cls_id, class_name=_label_at(cls_id, labels))
  94. )
  95. return boxes
  96. def _decode_xywh(
  97. arr: np.ndarray,
  98. labels: Sequence[str],
  99. conf_thres: float,
  100. ratio: float,
  101. pad: Tuple[float, float],
  102. image_size: Tuple[int, int],
  103. use_obj: bool,
  104. ) -> List[Box]:
  105. """``N x (4+nc)`` 或 ``N x (5+nc)``:cxcywh(+obj)+类别分数。"""
  106. nc = len(labels)
  107. cx, cy, w, h = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3]
  108. if use_obj:
  109. obj = arr[:, 4]
  110. cls_scores = arr[:, 5 : 5 + nc]
  111. cls_ids = np.argmax(cls_scores, axis=1)
  112. scores = obj * cls_scores[np.arange(len(obj)), cls_ids]
  113. else:
  114. cls_scores = arr[:, 4 : 4 + nc]
  115. cls_ids = np.argmax(cls_scores, axis=1)
  116. scores = cls_scores[np.arange(len(cls_ids)), cls_ids]
  117. keep = scores >= conf_thres
  118. if not np.any(keep):
  119. return []
  120. x1 = cx[keep] - w[keep] / 2.0
  121. y1 = cy[keep] - h[keep] / 2.0
  122. x2 = cx[keep] + w[keep] / 2.0
  123. y2 = cy[keep] + h[keep] / 2.0
  124. scores = scores[keep]
  125. cls_ids = cls_ids[keep]
  126. boxes: List[Box] = []
  127. for i in range(len(scores)):
  128. rx1, ry1, rx2, ry2 = unletterbox_box(
  129. float(x1[i]), float(y1[i]), float(x2[i]), float(y2[i]), ratio, pad, image_size
  130. )
  131. if rx2 - rx1 < 1 or ry2 - ry1 < 1:
  132. continue
  133. boxes.append(
  134. Box(
  135. rx1,
  136. ry1,
  137. rx2,
  138. ry2,
  139. score=float(scores[i]),
  140. class_id=int(cls_ids[i]),
  141. class_name=_label_at(int(cls_ids[i]), labels),
  142. )
  143. )
  144. return boxes
  145. def draw_boxes(
  146. image: np.ndarray,
  147. boxes: Sequence[Box],
  148. roi: Optional[Sequence[Tuple[float, float]]] = None,
  149. texts: Optional[Sequence[str]] = None,
  150. ) -> np.ndarray:
  151. """画框 + ROI + 文本,用于联调预览与难例复盘(原地绘制并返回同一张图)。"""
  152. if cv2 is None:
  153. return image
  154. colors = {
  155. "container": (0, 215, 255),
  156. "bed": (0, 255, 0),
  157. "flatbed": (255, 128, 0),
  158. }
  159. for box in boxes:
  160. color = colors.get(box.class_name, (0, 0, 255))
  161. x1, y1, x2, y2 = [int(v) for v in box.as_xyxy()]
  162. cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
  163. tag = "%s %.2f" % (box.class_name, box.score)
  164. cv2.putText(image, tag, (x1, max(12, y1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
  165. if roi:
  166. pts = np.array([[int(x), int(y)] for x, y in roi], dtype=np.int32)
  167. cv2.polylines(image, [pts], True, (0, 255, 255), 2)
  168. if texts:
  169. for i, line in enumerate(texts):
  170. cv2.putText(
  171. image, str(line), (10, 24 + i * 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
  172. )
  173. return image