preproc.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """推理预处理:letterbox 缩放 + NCHW/NHWC blob 组装。
  2. ``letterbox`` 与 :mod:`portcv.detect.postproc` 中的还原逻辑严格配对:
  3. 训练/导出用的预处理必须与这里一致,否则框会整体偏移(尤其宽高比差异大的画面)。
  4. """
  5. from __future__ import annotations
  6. from typing import Tuple
  7. import numpy as np
  8. __all__ = ["letterbox", "to_blob", "unletterbox_box"]
  9. try: # pragma: no cover - 取决于环境
  10. import cv2
  11. except ImportError: # pragma: no cover
  12. cv2 = None # type: ignore
  13. def letterbox(
  14. image: np.ndarray,
  15. new_shape: Tuple[int, int] = (640, 640),
  16. color: Tuple[int, int, int] = (114, 114, 114),
  17. ) -> Tuple[np.ndarray, float, Tuple[float, float]]:
  18. """等比缩放到 ``new_shape`` 并居中填充。
  19. 返回 ``(图像, 缩放比例, (pad_x, pad_y))``。
  20. """
  21. if cv2 is None:
  22. raise RuntimeError("需要 opencv-python: pip install opencv-python")
  23. height, width = image.shape[:2]
  24. new_w, new_h = int(new_shape[0]), int(new_shape[1])
  25. ratio = min(new_w / float(width), new_h / float(height))
  26. unpad_w, unpad_h = int(round(width * ratio)), int(round(height * ratio))
  27. resized = cv2.resize(image, (unpad_w, unpad_h), interpolation=cv2.INTER_LINEAR)
  28. dw = (new_w - unpad_w) / 2.0
  29. dh = (new_h - unpad_h) / 2.0
  30. top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
  31. left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
  32. padded = cv2.copyMakeBorder(
  33. resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
  34. )
  35. return padded, float(ratio), (float(left), float(top))
  36. def to_blob(image: np.ndarray, input_format: str = "rgb_float") -> np.ndarray:
  37. """按要求组装成模型输入 blob(batch=1)。
  38. * ``rgb_float``:NCHW float32 / 255(ONNX、TensorRT 常用);
  39. * ``rgb_uint8`` / ``bgr_uint8``:NHWC uint8(RKNN 量化模型与部分 ONNX 常用)。
  40. """
  41. fmt = str(input_format).lower()
  42. if fmt == "rgb_float":
  43. rgb = image[:, :, ::-1]
  44. tensor = np.ascontiguousarray(rgb.transpose(2, 0, 1)[None].astype(np.float32) / 255.0)
  45. return tensor
  46. if fmt == "rgb_uint8":
  47. rgb = np.ascontiguousarray(image[:, :, ::-1])
  48. return rgb[None]
  49. if fmt == "bgr_uint8":
  50. return np.ascontiguousarray(image)[None]
  51. raise ValueError("未知 input_format: %s(可选 rgb_float / rgb_uint8 / bgr_uint8)" % input_format)
  52. def unletterbox_box(
  53. x1: float,
  54. y1: float,
  55. x2: float,
  56. y2: float,
  57. ratio: float,
  58. pad: Tuple[float, float],
  59. image_size: Tuple[int, int],
  60. ) -> Tuple[float, float, float, float]:
  61. """把 letterbox 坐标系下的框还原到原图坐标,并裁剪到图像范围。"""
  62. pad_x, pad_y = float(pad[0]), float(pad[1])
  63. ratio = float(ratio) if ratio > 0 else 1.0
  64. x1 = (x1 - pad_x) / ratio
  65. x2 = (x2 - pad_x) / ratio
  66. y1 = (y1 - pad_y) / ratio
  67. y2 = (y2 - pad_y) / ratio
  68. width, height = float(image_size[0]), float(image_size[1])
  69. x1 = min(max(x1, 0.0), width)
  70. x2 = min(max(x2, 0.0), width)
  71. y1 = min(max(y1, 0.0), height)
  72. y2 = min(max(y2, 0.0), height)
  73. return x1, y1, x2, y2