一、完整预处理流程
mermaid
graph TD
A[原始图像] --> B[LetterBox缩放]
B --> C[通道转换]
C --> D[归一化]
D --> E[张量转换]
二、LetterBox核心实现
1. 标准LetterBox类
python
import cv2
import numpy as np
class LetterBox:
"""保持原始比例的缩放填充"""
def __init__(self, new_shape=(640, 640), auto=False, stride=32):
self.new_shape = new_shape
self.auto = auto # 是否自动计算padding
self.stride = stride # 模型步长
def __call__(self, image):
# 原始尺寸
shape = image.shape[:2] # [height, width]
# 计算缩放比例
r = min(self.new_shape[0] / shape[0],
self.new_shape[1] / shape[1])
# 新尺寸(保持