Ultralytics YOLOv11-OBB模型ONNX推理与后处理指南
概述
本文详细介绍了如何使用ONNX Runtime对Ultralytics YOLOv11-OBB(Oriented Bounding Box)模型进行推理和后处理。YOLOv11-OBB模型能够检测带有旋转角度的目标框,适用于遥感图像、文本检测等需要精确角度信息的场景。
模型导出与量化
在开始推理前,需要将训练好的PyTorch模型导出为ONNX格式:
- 使用Ultralytics库导出基础ONNX模型:
from ultralytics import YOLO
model = YOLO("custom_model-obb.pt")
model.export(format='onnx', simplify=True)
- 对ONNX模型进行预处理和量化:
python -m onnxruntime.quantization.preprocess --input custom_model-obb.onnx --output preprocessed_model.onnx
- 升级模型版本并进行量化:
upgraded_model_name = upgrade_model_version(preprocessed_model.onnx, opset_version=19)
onnxruntime.quantization.quantize_model(upgraded_model_name)
图像预处理
正确的图像预处理对模型性能至关重要。YOLOv11-OBB模型期望输入为640x640的RGB图像,数值范围在0-1之间:
def preprocess_image(image_path):
# 读取图像并转换为RGB格式
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 记录原始尺寸用于后处理
orig_shape = image.shape[:2]
# 调整大小并归一化
image = cv2.resize(image, (640, 640))
image = image.astype(np.float32) / 255.0
# 转换维度顺序为CHW
image = np.transpose(image, (2, 0, 1))
return image, orig_shape
模型推理
使用ONNX Runtime进行推理:
onnx_model = onnxruntime.InferenceSession(
path_or_bytes="quantized_model.onnx",
providers=['CPUExecutionProvider']
)
image_path = "image1.png"
processed_frame, orig_shape = preprocess_image(image_path)
predictions = onnx_model.run(
None,
{onnx_model.get_inputs()[0].name: np.expand_dims(processed_frame, axis=0)}
)
后处理详解
YOLOv11-OBB模型的输出形状为[1, 6, 8400],其中:
- 1: 批处理维度
- 6: 每个预测的特征维度(cx, cy, w, h, confidence, angle)
- 8400: 预测框数量
后处理步骤包括:
- 转置输出维度以便处理
- 根据置信度阈值过滤预测
- 提取旋转框参数和类别信息
- 将坐标从模型输入尺寸(640x640)缩放回原始图像尺寸
def postprocess_obb(output, orig_shape, conf_thresh=0.25):
# 转置输出维度 [1, 6, 8400] -> [8400, 6]
predictions = output[0].transpose((0, 2, 1))[0]
# 根据置信度过滤预测
mask = predictions[:, 4] > conf_thresh
predictions = predictions[mask]
if len(predictions) == 0:
return []
# 提取旋转框参数 [cx, cy, w, h, angle]
boxes = np.concatenate([predictions[:, :4], predictions[:, 5:6]], axis=1)
scores = predictions[:, 4]
class_ids = predictions[:, 5].astype(np.int32)
# 计算缩放比例
scale_x = orig_shape[1] / 640
scale_y = orig_shape[0] / 640
# 缩放坐标到原始图像尺寸
boxes[:, 0] *= scale_x # cx
boxes[:, 1] *= scale_y # cy
boxes[:, 2] *= scale_x # w
boxes[:, 3] *= scale_y # h
return boxes, scores, class_ids
旋转框可视化
得到旋转框参数后,可以使用OpenCV绘制结果:
def draw_rotated_boxes(image, boxes, scores, class_ids):
for box, score, cls_id in zip(boxes, scores, class_ids):
cx, cy, w, h, angle = box
# 计算旋转矩形
rect = ((cx, cy), (w, h), angle)
box_points = cv2.boxPoints(rect).astype(np.int32)
# 绘制旋转矩形
cv2.drawContours(image, [box_points], 0, (0, 255, 0), 2)
# 添加标签和置信度
label = f"Class {cls_id}: {score:.2f}"
cv2.putText(image, label, (int(cx), int(cy)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
return image
常见问题解决
-
坐标范围异常:确保预处理时没有错误地乘以255,输入图像应归一化到0-1范围。
-
角度表示:YOLOv11-OBB模型输出的角度通常以弧度表示,范围在[-π/2, π/2]之间。
-
长宽比失真:对于非方形图像,建议使用letterbox方法保持原始长宽比,避免目标变形。
-
量化后精度下降:如果量化后模型精度显著下降,可以尝试使用动态量化或混合精度量化。
性能优化建议
- 使用ONNX Runtime的CUDA执行提供者加速推理
- 对输入图像进行批处理以提高吞吐量
- 使用TensorRT进一步优化ONNX模型
- 对后处理代码进行向量化优化
通过以上步骤,您可以有效地在ONNX Runtime上部署和运行YOLOv11-OBB模型,实现高效准确的旋转目标检测。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



