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

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

2025-05-02 18:13:22作者:殷蕙予

概述

本文详细介绍了如何使用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模型,实现高效准确的旋转目标检测。

热门项目推荐
相关项目推荐

项目优选

收起
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
47
115
leetcodeleetcode
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
50
13
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
417
317
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
268
404
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
90
158
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TSX
310
28
carboncarbon
轻量级、语义化、对开发者友好的 golang 时间处理库
Go
7
2
ruoyi-airuoyi-ai
RuoYi AI 是一个全栈式 AI 开发平台,旨在帮助开发者快速构建和部署个性化的 AI 应用。
Java
90
25
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
87
239
CangjieMagicCangjieMagic
基于仓颉编程语言构建的 LLM Agent 开发框架,其主要特点包括:Agent DSL、支持 MCP 协议,支持模块化调用,支持任务智能规划。
Cangjie
554
39