[C++][cmake]基于C++在windows上onnxruntime+opencv部署yolo26的图像分类onnx模型源码

作品简介

如果只需要opencv去部署yolov11分类模型可以参考我其他博文,本文和 opencv去部署yolov11分类模型区别是:opencv部署推理核心使用opencv自带api,而本文推理核心用的onnxruntime,opencv只是辅助作用即读取处理图片

【算法介绍】

ONNXRuntime是微软推出的一款高性能的机器学习推理引擎框架,专注于加速机器学习模型的预测阶段。它支持多种运行后端,包括CPU、GPU等,使得开发者可以灵活选择最适合其应用场景的硬件平台。使用C++和ONNX Runtime部署YOLOv11-CLS图像分类ONNX模型,涉及到以下几个关键步骤:

  1. 环境配置 :首先,需要安装ONNX Runtime库,可以通过从ONNX Runtime的GitHub存储库中下载预编译的二进制文件来安装,或者通过源代码进行构建。同时,还需要安装OpenCV等图像处理库,以便对输入图像进行预处理。
  2. 模型加载 :加载YOLOv11-CLS的ONNX模型文件,通常涉及到指定模型的路径,并创建一个InferenceSession对象,该对象将用于后续的推理。
  3. 数据预处理 :使用OpenCV等库对输入图像进行预处理,包括调整图像大小、归一化像素值等,以满足模型输入的要求。
  4. 模型推理 :将预处理后的数据传递给InferenceSession对象,并调用其Run方法来执行推理。这将返回模型的输出,通常是一个包含分类结果的张量。
  5. 结果处理 :解析模型的输出,提取有用的信息(如分类标签和置信度),并根据需要进行进一步的处理或可视化。

通过以上步骤,可以在C++中使用ONNXRuntime成功部署YOLO26CLS图像分类模型,实现高效的图像分类任务。

【效果展示】

【调用代码】

#pragma once
#include 
#include 
#include 
#include "inference.h"
#include 
 
 
using namespace std;
 
int main(int argc, char *argv[])
{
 
    if (argc == 1)
    {
        std::cout << "Usage: main.exe " << std::endl;
        return 0;
    }
    DL_INIT_PARAM params;
    params.labelPath = "class_names.txt";
    params.modelPath = "yolo26n-cls.onnx";
    params.modelType = YOLO_CLS_26;
    params.imgSize = {224, 224};
    params.rectConfidenceThreshold = 0.4;
    params.iouThreshold = 0.0001;
    params.cudaEnable = false;
 
    auto starttime_1 = std::chrono::high_resolution_clock::now();
    std::unique_ptr yolo(new YOLO_26);
    yolo->CreateSession(params);
    auto starttime_3 = std::chrono::high_resolution_clock::now();
    auto duration_ms4 = std::chrono::duration_cast(starttime_3 - starttime_1).count();
    std::cout << "[YOLO_26]: warm up: " << duration_ms4 << "ms" << std::endl;
    std::string imagepath = argv[1];
    cv::Mat image = cv::imread(imagepath);
    auto starttime_2 = std::chrono::high_resolution_clock::now();
    auto results = yolo->Inference(image);
    auto starttime_4 = std::chrono::high_resolution_clock::now();
    auto duration_ms3 = std::chrono::duration_cast(starttime_4 - starttime_2).count();
    std::cout << "[YOLO_26]: inference time: " << duration_ms3 << " ms" << std::endl;
    for (const auto &result : results)
    {
        std::cout << "[YOLO_26]: label is: " << result.className << ", confidence is: " << result.confidence << std::endl;
        std::string text = result.className + " " + std::to_string(result.confidence).substr(0, 4);
        cv::putText(image, text, cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 255, 0), 2);
    }
 
    return 0;
}

【测试环境】

vs2019

cmake==3.30.1

opencv==4.8.0

onnxruntime==1.16.3

【运行步骤】

通过cmake编译出exe后,执行

yolo26-cls.exe 【图片路径】即可

创作时间: