"""推理预处理:letterbox 缩放 + NCHW/NHWC blob 组装。 ``letterbox`` 与 :mod:`portcv.detect.postproc` 中的还原逻辑严格配对: 训练/导出用的预处理必须与这里一致,否则框会整体偏移(尤其宽高比差异大的画面)。 """ from __future__ import annotations from typing import Tuple import numpy as np __all__ = ["letterbox", "to_blob", "unletterbox_box"] try: # pragma: no cover - 取决于环境 import cv2 except ImportError: # pragma: no cover cv2 = None # type: ignore def letterbox( image: np.ndarray, new_shape: Tuple[int, int] = (640, 640), color: Tuple[int, int, int] = (114, 114, 114), ) -> Tuple[np.ndarray, float, Tuple[float, float]]: """等比缩放到 ``new_shape`` 并居中填充。 返回 ``(图像, 缩放比例, (pad_x, pad_y))``。 """ if cv2 is None: raise RuntimeError("需要 opencv-python: pip install opencv-python") height, width = image.shape[:2] new_w, new_h = int(new_shape[0]), int(new_shape[1]) ratio = min(new_w / float(width), new_h / float(height)) unpad_w, unpad_h = int(round(width * ratio)), int(round(height * ratio)) resized = cv2.resize(image, (unpad_w, unpad_h), interpolation=cv2.INTER_LINEAR) dw = (new_w - unpad_w) / 2.0 dh = (new_h - unpad_h) / 2.0 top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) padded = cv2.copyMakeBorder( resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color ) return padded, float(ratio), (float(left), float(top)) def to_blob(image: np.ndarray, input_format: str = "rgb_float") -> np.ndarray: """按要求组装成模型输入 blob(batch=1)。 * ``rgb_float``:NCHW float32 / 255(ONNX、TensorRT 常用); * ``rgb_uint8`` / ``bgr_uint8``:NHWC uint8(RKNN 量化模型与部分 ONNX 常用)。 """ fmt = str(input_format).lower() if fmt == "rgb_float": rgb = image[:, :, ::-1] tensor = np.ascontiguousarray(rgb.transpose(2, 0, 1)[None].astype(np.float32) / 255.0) return tensor if fmt == "rgb_uint8": rgb = np.ascontiguousarray(image[:, :, ::-1]) return rgb[None] if fmt == "bgr_uint8": return np.ascontiguousarray(image)[None] raise ValueError("未知 input_format: %s(可选 rgb_float / rgb_uint8 / bgr_uint8)" % input_format) def unletterbox_box( x1: float, y1: float, x2: float, y2: float, ratio: float, pad: Tuple[float, float], image_size: Tuple[int, int], ) -> Tuple[float, float, float, float]: """把 letterbox 坐标系下的框还原到原图坐标,并裁剪到图像范围。""" pad_x, pad_y = float(pad[0]), float(pad[1]) ratio = float(ratio) if ratio > 0 else 1.0 x1 = (x1 - pad_x) / ratio x2 = (x2 - pad_x) / ratio y1 = (y1 - pad_y) / ratio y2 = (y2 - pad_y) / ratio width, height = float(image_size[0]), float(image_size[1]) x1 = min(max(x1, 0.0), width) x2 = min(max(x2, 0.0), width) y1 = min(max(y1, 0.0), height) y2 = min(max(y2, 0.0), height) return x1, y1, x2, y2