首页
/ Ultralytics YOLOv11-OBB模型ONNX推理与后处理指南

Ultralytics YOLOv11-OBB模型ONNX推理与后处理指南

2025-05-02 11:45:11作者:殷蕙予

概述

本文详细介绍了如何使用ONNX Runtime对Ultralytics YOLOv11-OBB(Oriented Bounding Box)模型进行推理和后处理。YOLOv11-OBB模型能够检测带有旋转角度的目标框,适用于遥感图像、文本检测等需要精确角度信息的场景。

模型导出与量化

在开始推理前,需要将训练好的PyTorch模型导出为ONNX格式:

  1. 使用Ultralytics库导出基础ONNX模型:
from ultralytics import YOLO
model = YOLO("custom_model-obb.pt")
model.export(format='onnx', simplify=True)
  1. 对ONNX模型进行预处理和量化:
python -m onnxruntime.quantization.preprocess --input custom_model-obb.onnx --output preprocessed_model.onnx
  1. 升级模型版本并进行量化:
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: 预测框数量

后处理步骤包括:

  1. 转置输出维度以便处理
  2. 根据置信度阈值过滤预测
  3. 提取旋转框参数和类别信息
  4. 将坐标从模型输入尺寸(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

常见问题解决

  1. 坐标范围异常:确保预处理时没有错误地乘以255,输入图像应归一化到0-1范围。

  2. 角度表示:YOLOv11-OBB模型输出的角度通常以弧度表示,范围在[-π/2, π/2]之间。

  3. 长宽比失真:对于非方形图像,建议使用letterbox方法保持原始长宽比,避免目标变形。

  4. 量化后精度下降:如果量化后模型精度显著下降,可以尝试使用动态量化或混合精度量化。

性能优化建议

  1. 使用ONNX Runtime的CUDA执行提供者加速推理
  2. 对输入图像进行批处理以提高吞吐量
  3. 使用TensorRT进一步优化ONNX模型
  4. 对后处理代码进行向量化优化

通过以上步骤,您可以有效地在ONNX Runtime上部署和运行YOLOv11-OBB模型,实现高效准确的旋转目标检测。

登录后查看全文
热门项目推荐

热门内容推荐

最新内容推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
260
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
854
505
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
254
295
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
331
1.08 K
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
397
370
note-gennote-gen
一款跨平台的 Markdown AI 笔记软件,致力于使用 AI 建立记录和写作的桥梁。
TSX
83
4
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
kernelkernel
deepin linux kernel
C
21
5