postproc.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. __all__ = ["decode_yolo_output", "draw_boxes"]
  14. try: # pragma: no cover
  15. import cv2
  16. except ImportError: # pragma: no cover
  17. cv2 = None # type: ignore
  18. def _as_2d(raw: np.ndarray, nc: int, nms_free: bool) -> np.ndarray:
  19. """把输出统一成 ``(N, C)``(C = 4+nc / 5+nc / 6)。"""
  20. arr = np.asarray(raw, dtype=np.float32)
  21. while arr.ndim > 2:
  22. arr = arr[0]
  23. if arr.ndim == 1:
  24. arr = arr[None]
  25. cols = int(arr.shape[1])
  26. expected = 6 if nms_free else (4 + nc)
  27. expected_obj = 5 + nc
  28. if cols not in (expected, expected_obj, 6) and arr.shape[0] in (expected, expected_obj, 6):
  29. arr = arr.T
  30. return np.ascontiguousarray(arr)
  31. def _label_at(index: int, labels: Sequence[str]) -> str:
  32. if 0 <= int(index) < len(labels):
  33. return str(labels[int(index)])
  34. return "cls_%d" % index
  35. def _unletterbox_arrays(
  36. x1: np.ndarray,
  37. y1: np.ndarray,
  38. x2: np.ndarray,
  39. y2: np.ndarray,
  40. ratio: float,
  41. pad: Tuple[float, float],
  42. image_size: Tuple[int, int],
  43. ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
  44. """向量化版 :func:`~portcv.detect.preproc.unletterbox_box`(逐元素结果一致)。
  45. 8400 个候选框逐个调 Python 标量函数是后处理的主要热点,这里一次算完。
  46. 用 float64 与标量版 ``float(x) - pad`` 的精度一致;裁剪后可能留下 NaN,
  47. 由调用方按「``< 1`` 才丢弃」的老语义处理(NaN 的 ``< 1`` 为 False,即保留)。
  48. """
  49. pad_x, pad_y = float(pad[0]), float(pad[1])
  50. scale = float(ratio) if float(ratio) > 0 else 1.0
  51. width, height = float(image_size[0]), float(image_size[1])
  52. x1 = (x1.astype(np.float64) - pad_x) / scale
  53. x2 = (x2.astype(np.float64) - pad_x) / scale
  54. y1 = (y1.astype(np.float64) - pad_y) / scale
  55. y2 = (y2.astype(np.float64) - pad_y) / scale
  56. np.clip(x1, 0.0, width, out=x1)
  57. np.clip(x2, 0.0, width, out=x2)
  58. np.clip(y1, 0.0, height, out=y1)
  59. np.clip(y2, 0.0, height, out=y2)
  60. return x1, y1, x2, y2
  61. def decode_yolo_output(
  62. raw: np.ndarray,
  63. labels: Sequence[str],
  64. conf_thres: float = 0.35,
  65. iou_thres: float = 0.5,
  66. max_det: int = 60,
  67. nms_free: bool = False,
  68. ratio: float = 1.0,
  69. pad: Tuple[float, float] = (0.0, 0.0),
  70. image_size: Tuple[int, int] = (640, 640),
  71. apply_nms: bool = True,
  72. ) -> List[Box]:
  73. """解析模型输出。``image_size`` 为原图 ``(width, height)``。"""
  74. nc = len(labels)
  75. arr = _as_2d(raw, nc, nms_free)
  76. if arr.size == 0:
  77. return []
  78. cols = int(arr.shape[1])
  79. if cols == 6 and nms_free:
  80. boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size)
  81. elif cols in (4 + nc, 5 + nc):
  82. boxes = _decode_xywh(
  83. arr, labels, conf_thres, ratio, pad, image_size, use_obj=(cols == 5 + nc)
  84. )
  85. elif cols == 6:
  86. boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size)
  87. else:
  88. return []
  89. if len(boxes) > max_det:
  90. boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det]
  91. if apply_nms and len(boxes) > 1 and not nms_free:
  92. from ..logic.geometry import nms as _nms
  93. boxes = _nms(boxes, iou_thres, per_class=True)
  94. if len(boxes) > max_det:
  95. boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det]
  96. return boxes
  97. def _decode_nms_free(
  98. arr: np.ndarray,
  99. labels: Sequence[str],
  100. conf_thres: float,
  101. ratio: float,
  102. pad: Tuple[float, float],
  103. image_size: Tuple[int, int],
  104. ) -> List[Box]:
  105. """``N x 6``:``x1, y1, x2, y2, score, class_id``(向量化)。"""
  106. keep = arr[:, 4] >= conf_thres
  107. if not np.any(keep):
  108. return []
  109. rows = arr[keep]
  110. rx1, ry1, rx2, ry2 = _unletterbox_arrays(
  111. rows[:, 0], rows[:, 1], rows[:, 2], rows[:, 3], ratio, pad, image_size
  112. )
  113. # 与标量版等价:只有 ``< 1`` 才丢弃(NaN 会被保留)
  114. valid = ~((rx2 - rx1) < 1.0) & ~((ry2 - ry1) < 1.0)
  115. boxes: List[Box] = []
  116. for i in np.nonzero(valid)[0]:
  117. score = float(rows[i, 4])
  118. cls_id = int(round(float(rows[i, 5])))
  119. boxes.append(
  120. Box(
  121. float(rx1[i]),
  122. float(ry1[i]),
  123. float(rx2[i]),
  124. float(ry2[i]),
  125. score=score,
  126. class_id=cls_id,
  127. class_name=_label_at(cls_id, labels),
  128. )
  129. )
  130. return boxes
  131. def _decode_xywh(
  132. arr: np.ndarray,
  133. labels: Sequence[str],
  134. conf_thres: float,
  135. ratio: float,
  136. pad: Tuple[float, float],
  137. image_size: Tuple[int, int],
  138. use_obj: bool,
  139. ) -> List[Box]:
  140. """``N x (4+nc)`` 或 ``N x (5+nc)``:cxcywh(+obj)+类别分数(向量化裁剪,只为保留框建对象)。"""
  141. nc = len(labels)
  142. cx, cy, w, h = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3]
  143. if use_obj:
  144. obj = arr[:, 4]
  145. cls_scores = arr[:, 5 : 5 + nc]
  146. cls_ids = np.argmax(cls_scores, axis=1)
  147. scores = obj * cls_scores[np.arange(len(obj)), cls_ids]
  148. else:
  149. cls_scores = arr[:, 4 : 4 + nc]
  150. cls_ids = np.argmax(cls_scores, axis=1)
  151. scores = cls_scores[np.arange(len(cls_ids)), cls_ids]
  152. keep = scores >= conf_thres
  153. if not np.any(keep):
  154. return []
  155. x1 = cx[keep] - w[keep] / 2.0
  156. y1 = cy[keep] - h[keep] / 2.0
  157. x2 = cx[keep] + w[keep] / 2.0
  158. y2 = cy[keep] + h[keep] / 2.0
  159. rx1, ry1, rx2, ry2 = _unletterbox_arrays(x1, y1, x2, y2, ratio, pad, image_size)
  160. valid = ~((rx2 - rx1) < 1.0) & ~((ry2 - ry1) < 1.0)
  161. scores = scores[keep]
  162. cls_ids = cls_ids[keep]
  163. boxes: List[Box] = []
  164. for i in np.nonzero(valid)[0]:
  165. cls_id = int(cls_ids[i])
  166. boxes.append(
  167. Box(
  168. float(rx1[i]),
  169. float(ry1[i]),
  170. float(rx2[i]),
  171. float(ry2[i]),
  172. score=float(scores[i]),
  173. class_id=cls_id,
  174. class_name=_label_at(cls_id, labels),
  175. )
  176. )
  177. return boxes
  178. def draw_boxes(
  179. image: np.ndarray,
  180. boxes: Sequence[Box],
  181. roi: Optional[Sequence[Tuple[float, float]]] = None,
  182. texts: Optional[Sequence[str]] = None,
  183. ) -> np.ndarray:
  184. """画框 + ROI + 文本,用于联调预览与难例复盘(原地绘制并返回同一张图)。"""
  185. if cv2 is None:
  186. return image
  187. colors = {
  188. "container": (0, 215, 255),
  189. "bed": (0, 255, 0),
  190. "flatbed": (255, 128, 0),
  191. }
  192. for box in boxes:
  193. color = colors.get(box.class_name, (0, 0, 255))
  194. x1, y1, x2, y2 = [int(v) for v in box.as_xyxy()]
  195. cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
  196. tag = "%s %.2f" % (box.class_name, box.score)
  197. cv2.putText(image, tag, (x1, max(12, y1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
  198. if roi:
  199. pts = np.array([[int(x), int(y)] for x, y in roi], dtype=np.int32)
  200. cv2.polylines(image, [pts], True, (0, 255, 255), 2)
  201. if texts:
  202. for i, line in enumerate(texts):
  203. cv2.putText(
  204. image, str(line), (10, 24 + i * 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
  205. )
  206. return image