Ubuntu环境下C++使用onnxruntime和Opencv进行YOLOv8模型部署

这篇具有很好参考价值的文章主要介绍了Ubuntu环境下C++使用onnxruntime和Opencv进行YOLOv8模型部署。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

环境配置

系统环境

项目文件路径 

文件环境

 config.txt

 CMakeLists.txt

type.names

 读取config.txt配置文件

修改图片尺寸格式

读取缺陷标志文件

生成缺陷随机颜色标识

模型推理

推理结果获取

缺陷信息还原并显示

总代码


环境配置

系统环境

Ubuntu18.04

onnxruntime-linux-x64 1.12.1:https://github.com/microsoft/onnxruntime/releases

opencv 3.4.3

cmake 3.10.2

项目文件路径 

1.  bin:存放可执行程序和识别结果
2.  data:存放数据集
3.  src:存放源程序
4.  include:存放头文件
5.  config.txt:配置文件,内容分别是模型相对路径、图片相对路径、缺陷标识文件相对路径、缺陷识别阈值、缺陷重叠阈值
6.  type.names:缺陷标识文件,内容和模型识别的缺陷标识顺序需要一致

ubuntu onnx,深度学习,YOLO,深度学习,c++,ubuntu

文件环境

 config.txt

分别表示模型相对路径、图片相对路径、缺陷标识文件相对路径、缺陷识别阈值、缺陷重叠阈值

../models/best.onnx
../data/2.bmp
../type.names
0.4
0.4

 CMakeLists.txt

需要更改的地方已经在里面标注好了

# 项目名称,随便写
PROJECT(image_onnx)
# cmake版本,根据自己的写
cmake_minimum_required(VERSION 3.10)

# 编译好的可执行文件放置的位置
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${image_onnx_SOURCE_DIR}/bin)

# find required opencv
find_package(OpenCV REQUIRED)
# directory of opencv headers
include_directories(${OpenCV_INCLUDE_DIRS})

# 根据自己的onnxruntime存放路径编写
set(ONNXRUNTIME_ROOT_PATH /home/ebaina/onnxruntime-linux-x64-1.12.1/)
set(ONNXRUNTIME_INCLUDE_DIRS ${ONNXRUNTIME_ROOT_PATH}/include/)
set(ONNXRUNTIME_LIB ${ONNXRUNTIME_ROOT_PATH}lib/libonnxruntime.so)

# 需要编译的cpp文件所在路径,前面是编译好的可执行文件名
add_executable(image_onnx src/main_image.cpp
src/change_image.cpp
src/adjust_result.cpp)
# directory of opencv library
link_directories(${OpenCV_LIBRARY_DIRS})
# opencv libraries
target_link_libraries(image_onnx ${OpenCV_LIBS})

include_directories(${ONNXRUNTIME_INCLUDE_DIRS})
target_link_libraries(image_onnx ${ONNXRUNTIME_LIB})

# include
target_include_directories(image_onnx
    PRIVATE 
        ${PROJECT_SOURCE_DIR}/include
)

type.names

缺陷标志文件,内容和模型识别的缺陷标识顺序需要一致,模型识别网站:Netron

ubuntu onnx,深度学习,YOLO,深度学习,c++,ubuntu

burr
cbreakage
inbreakage
bpulp
corrode文章来源地址https://www.toymoban.com/news/detail-796807.html

 读取config.txt配置文件

    // 自动读取模型路径,图片路径,缺陷阈值,重叠阈值
    std::string model_path_;
    std::string imgPath;
    std::string namesPath;
    float threshold;
    float nms_threshold;
        // 打开配置文件并读取配置
    std::ifstream configFile("../config.txt");
    if (configFile.is_open()) {
        configFile >> model_path_ >> imgPath >> namesPath >> threshold >> nms_threshold;
        configFile.close();

        std::cout << "Model Path: " << model_path_ << std::endl;
        std::cout << "Image Path: " << imgPath << std::endl;
        std::cout << "Names Path: " << namesPath << std::endl;
        std::cout << "Threshold: " << threshold << std::endl;
        std::cout << "NMS Threshold: " << nms_threshold << std::endl;
    } else
        std::cerr << "Failed to open config file." << std::endl;
    const char* model_path = model_path_.c_str();

修改图片尺寸格式

    // 图片变换
    cv::Mat inputImage = cv::imread(imgPath);
    if (inputImage.empty()) {
        std::cerr << "Failed to load image." << std::endl;
        return 1;
    }
        // 获取图片尺寸
    int y = inputImage.rows;
    int x = inputImage.cols;
        // 图片尺寸变换
    cv::Mat image0 = resizeImage(inputImage, y, x);
        // 图像归一化
    std::vector<float> input_image_ = nchwImage(image0);

读取缺陷标志文件

    // 读取缺陷标志文件
    std::ifstream inputFile(namesPath);
    if (!inputFile.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }
    std::vector<std::string> typeNames;
    std::string line;
    while (std::getline(inputFile, line)) 
        typeNames.push_back(line);
    inputFile.close();

生成缺陷随机颜色标识

    // 缺陷颜色标识随机
    int numColors = typeNames.size();
    std::vector<std::vector<int>> colors;
    for (int i = 0; i < numColors; ++i) 
        colors.push_back(generateRandomColor());
    //     // 打印颜色种类
    // for (const auto &color : colors) 
    //     std::cout << "R: " << color[0] << ", G: " << color[1] << ", B: " << color[2] << std::endl;

模型推理

    // 模型设置和推理结果
    Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "Default");
        // CPU
    Ort::Session session_{env, model_path, Ort::SessionOptions{nullptr}}; 
        // 模型输入尺寸
    static constexpr const int height_ = 640; //model input height
    static constexpr const int width_ = 640; //model input width
    Ort::Value input_tensor_{nullptr};
    std::array<int64_t, 4> input_shape_{1, 3, height_, width_}; //mode input shape NCHW = 1x3xHxW
        // 模型输出尺寸
    Ort::Value output_tensor_{nullptr};
    std::array<int64_t, 3> output_shape_{1, 9, 8400}; //model output shape,
    std::array<_Float32, 9*8400> results_{};

        // 模型输入输出张量设置
    auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
    input_tensor_ = Ort::Value::CreateTensor<float>(memory_info, input_image_.data(), input_image_.size(), input_shape_.data(), input_shape_.size());
    output_tensor_ = Ort::Value::CreateTensor<float>(memory_info, results_.data(), results_.size(), output_shape_.data(), output_shape_.size());
        // 查看模型输入输出的名称
    const char* input_names[] = {"images"};
    const char* output_names[] = {"output0"};
        // 推理
    session_.Run(Ort::RunOptions{nullptr}, input_names, &input_tensor_, 1, output_names, &output_tensor_, 1);
    float* out = output_tensor_.GetTensorMutableData<float>();

推理结果获取

        // 推理结果获取
    int rows = 9;      // 第二维度大小,即行数
    int cols = 8400;   // 第三维度大小,即列数
    std::vector<std::vector<float>> matrix(rows, std::vector<float>(cols));
    for (int row = 0; row < rows; ++row) 
        for (int col = 0; col < cols; ++col) 
            matrix[row][col] = out[row * cols + col];
        // 9,8400数组转置为8400,9
    std::vector<std::vector<float>> tran_matrix = transpose(matrix);
    //     // 显示缺陷筛选结果
    // std::vector<std::vector<float>> num = tran_matrix;
    // for (size_t n = 0; n < num.size(); ++n) {
    //     bool aboveThreshold = false;
    //     for (size_t col = 4; col <= 8; ++col)
    //         if (num[n][col] > threshold) {
    //             aboveThreshold = true;
    //             break;
    //         }
        
    //     if (aboveThreshold) {
    //         std::cout << "Row " << n << ": ";
    //         for (const auto& val : num[n]) 
    //             std::cout << val << " ";
                
    //         std::cout << std::endl;
    //     }
    // }

缺陷信息还原并显示

    // 缺陷还原
    std::vector<std::vector<double>> select_matrix;
    select_matrix = select(tran_matrix, threshold, cols,rows);
        // 缺陷位置信息还原
    select_matrix = return_(select_matrix, y, x);
        // 缺陷位置信息筛选
    select_matrix = nms_(select_matrix, nms_threshold);
    //     // 打印数组的内容
    // for (const auto& row : select_matrix){
    //     for (const auto& value : row) {
    //         std::cout << value << " ";
    //     }
    //     std::cout << std::endl;
    // }
        // 绘制识别框
    cv::Mat outputImage = draw_image(select_matrix, inputImage, typeNames, colors);
    
    // 自定义窗口大小
    int windowWidth = 1200;
    int windowHeight = 900;

    // 调整窗口大小
    cv::namedWindow("Image with Bounding Boxes", cv::WINDOW_NORMAL);
    cv::resizeWindow("Image with Bounding Boxes", windowWidth, windowHeight);
    cv::imshow("Image with Bounding Boxes", outputImage);
    cv::imwrite("marked_image.jpg", outputImage);
    cv::waitKey(0);

main代码(关注取源码!)

#include <assert.h>
#include <random>
#include <onnxruntime_cxx_api.h>
#include "cpu_provider_factory.h"
#include <adjust_result.h>

// 随机生成颜色
std::vector<int> generateRandomColor() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<double> dis(0.0, 1.0);

    std::vector<int> color(3);
    for (int i = 0; i < 3; ++i) {
        color[i] = static_cast<int>(dis(gen) * 255);
    }

    return color;
}

int main(int argc, char* argv[]) {
    // // 模型路径,图片路径,缺陷阈值,重叠阈值
    // const char* model_path = "../models/best.onnx";
    // std::string imgPath = "../data/3.bmp";
    // std::string namesPath = "../type.names";
    // float threshold = 0.4;
    // float nms_threshold = 0.4;
    // 自动读取模型路径,图片路径,缺陷阈值,重叠阈值
    std::string model_path_;
    std::string imgPath;
    std::string namesPath;
    float threshold;
    float nms_threshold;
        // 打开配置文件并读取配置
    std::ifstream configFile("../config.txt");
    if (configFile.is_open()) {
        configFile >> model_path_ >> imgPath >> namesPath >> threshold >> nms_threshold;
        configFile.close();

        std::cout << "Model Path: " << model_path_ << std::endl;
        std::cout << "Image Path: " << imgPath << std::endl;
        std::cout << "Names Path: " << namesPath << std::endl;
        std::cout << "Threshold: " << threshold << std::endl;
        std::cout << "NMS Threshold: " << nms_threshold << std::endl;
    } else
        std::cerr << "Failed to open config file." << std::endl;
    const char* model_path = model_path_.c_str();

    // 图片变换
    cv::Mat inputImage = cv::imread(imgPath);
    if (inputImage.empty()) {
        std::cerr << "Failed to load image." << std::endl;
        return 1;
    }
        // 获取图片尺寸
    int y = inputImage.rows;
    int x = inputImage.cols;
        // 图片尺寸变换
    cv::Mat image0 = resizeImage(inputImage, y, x);
        // 图像归一化
    std::vector<float> input_image_ = nchwImage(image0);
    
    // 读取缺陷标志文件
    std::ifstream inputFile(namesPath);
    if (!inputFile.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }
    std::vector<std::string> typeNames;
    std::string line;
    while (std::getline(inputFile, line)) 
        typeNames.push_back(line);
    inputFile.close();
    //     // 打印缺陷标志文件内容
    // std::cout << "Number of elements: " << typeNames.size() << std::endl;
    // for (const std::string &typeName : typeNames) 
    //     std::cout << typeName << std::endl;

    // 缺陷颜色标识随机
    int numColors = typeNames.size();
    std::vector<std::vector<int>> colors;
    for (int i = 0; i < numColors; ++i) 
        colors.push_back(generateRandomColor());
    //     // 打印颜色种类
    // for (const auto &color : colors) 
    //     std::cout << "R: " << color[0] << ", G: " << color[1] << ", B: " << color[2] << std::endl;

    // 模型设置和推理结果
    Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "Default");
        // CPU
    Ort::Session session_{env, model_path, Ort::SessionOptions{nullptr}}; 
        // 模型输入尺寸
    static constexpr const int height_ = 640; //model input height
    static constexpr const int width_ = 640; //model input width
    Ort::Value input_tensor_{nullptr};
    std::array<int64_t, 4> input_shape_{1, 3, height_, width_}; //mode input shape NCHW = 1x3xHxW
        // 模型输出尺寸
    Ort::Value output_tensor_{nullptr};
    std::array<int64_t, 3> output_shape_{1, 9, 8400}; //model output shape,
    std::array<_Float32, 9*8400> results_{};

        // 模型输入输出张量设置
    auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault);
    input_tensor_ = Ort::Value::CreateTensor<float>(memory_info, input_image_.data(), input_image_.size(), input_shape_.data(), input_shape_.size());
    output_tensor_ = Ort::Value::CreateTensor<float>(memory_info, results_.data(), results_.size(), output_shape_.data(), output_shape_.size());
        // 查看模型输入输出的名称
    const char* input_names[] = {"images"};
    const char* output_names[] = {"output0"};
        // 推理
    session_.Run(Ort::RunOptions{nullptr}, input_names, &input_tensor_, 1, output_names, &output_tensor_, 1);
    float* out = output_tensor_.GetTensorMutableData<float>();

        // 推理结果获取
    int rows = 9;      // 第二维度大小,即行数
    int cols = 8400;   // 第三维度大小,即列数
    std::vector<std::vector<float>> matrix(rows, std::vector<float>(cols));
    for (int row = 0; row < rows; ++row) 
        for (int col = 0; col < cols; ++col) 
            matrix[row][col] = out[row * cols + col];
        // 9,8400数组转置为8400,9
    std::vector<std::vector<float>> tran_matrix = transpose(matrix);
    //     // 显示缺陷筛选结果
    // std::vector<std::vector<float>> num = tran_matrix;
    // for (size_t n = 0; n < num.size(); ++n) {
    //     bool aboveThreshold = false;
    //     for (size_t col = 4; col <= 8; ++col)
    //         if (num[n][col] > threshold) {
    //             aboveThreshold = true;
    //             break;
    //         }
        
    //     if (aboveThreshold) {
    //         std::cout << "Row " << n << ": ";
    //         for (const auto& val : num[n]) 
    //             std::cout << val << " ";
                
    //         std::cout << std::endl;
    //     }
    // }

    // 缺陷还原
    std::vector<std::vector<double>> select_matrix;
    select_matrix = select(tran_matrix, threshold, cols,rows);
        // 缺陷位置信息还原
    select_matrix = return_(select_matrix, y, x);
        // 缺陷位置信息筛选
    select_matrix = nms_(select_matrix, nms_threshold);
    //     // 打印数组的内容
    // for (const auto& row : select_matrix){
    //     for (const auto& value : row) {
    //         std::cout << value << " ";
    //     }
    //     std::cout << std::endl;
    // }
        // 绘制识别框
    cv::Mat outputImage = draw_image(select_matrix, inputImage, typeNames, colors);
    
    // 自定义窗口大小
    int windowWidth = 1200;
    int windowHeight = 900;

    // 调整窗口大小
    cv::namedWindow("Image with Bounding Boxes", cv::WINDOW_NORMAL);
    cv::resizeWindow("Image with Bounding Boxes", windowWidth, windowHeight);
    cv::imshow("Image with Bounding Boxes", outputImage);
    cv::imwrite("marked_image.jpg", outputImage);
    cv::waitKey(0);

    return 0;
}

到了这里,关于Ubuntu环境下C++使用onnxruntime和Opencv进行YOLOv8模型部署的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用yolov8的dockerfile在ubuntu上部署环境

    首先进入doceker文件夹 cd yolov8/ultralytics-main/docker 执行命令 docker build -t yolov8:v1 . yolov8:v1(镜像名称:镜像标签,可以自己定义) 注意点: (1)原docekerfile中 ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/ 下载很慢,可以在外部下载好

    2024年02月10日
    浏览(32)
  • [C++]使用纯opencv部署yolov8旋转框目标检测

    【官方框架地址】 https://github.com/ultralytics/ultralytics 【算法介绍】 YOLOv8是一种先进的对象检测算法,它通过单个神经网络实现了快速的物体检测。其中,旋转框检测是YOLOv8的一项重要特性,它可以有效地检测出不同方向和角度的物体。 旋转框检测的原理是通过预测物体的边界

    2024年04月26日
    浏览(25)
  • pytorch 42 C#使用onnxruntime部署内置nms的yolov8模型

    在进行目标检测部署时,通常需要自行编码实现对模型预测结果的解码及与预测结果的nms操作。所幸现在的各种部署框架对算子的支持更为灵活,可以在模型内实现预测结果的解码,但仍然需要自行编码实现对预测结果的nms操作。其实在onnx opset===11版本以后,其已支持将nms操

    2024年02月12日
    浏览(26)
  • C++模型部署:qt+yolov5/6+onnxruntime+opencv

    作者平时主要是写 c++ 库的,界面方面了解不多,也没有发现“美”的眼镜,界面有点丑,大家多包涵。 本次介绍的项目主要是通过 cmake 构建一个 基于 c++ 语言的,以 qt 为框架的,包含 opencv 第三方库在内的,跨平台的,使用 ONNX RUNTIME 进行前向推理的 yolov5/6 演示平台。文章

    2024年02月05日
    浏览(37)
  • [C++]使用yolov8的onnx模型仅用opencv和bytetrack实现目标追踪

    【官方框架地址】 yolov8: https://github.com/ultralytics/ultralytics bytetrack: https://github.com/ifzhang/ByteTrack 【算法介绍】 随着人工智能技术的不断发展,目标追踪已成为计算机视觉领域的重要研究方向。Yolov8和ByTetrack作为当前先进的算法,当它们结合使用时,能够显著提升目标追踪的准

    2024年01月24日
    浏览(31)
  • 如何加载模型YOLOv8 ONNXRuntime

    YOLOv8 是 YOLO(You Only Look Once)目标检测系统的最新版本(v8)。YOLO 是一种实时、一次性目标检测系统,旨在在网络的单次前向传递中执行目标检测,使其快速高效。YOLOv8是之前YOLO模型的改进版本,具有更高的精度和更快的推理速度。 ONNX(开放神经网络交换)是一种表示深度

    2024年02月14日
    浏览(23)
  • YOLOV8 进行docker环境配置

    原docekerfile中ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/下载很慢,可以在外部下载好,放入docker文件夹中,再将源代码改为ADD Arial.ttf Arial.Unicode.ttf /root/.config/Ultralytics/(其它下载内容类似修改包括yolo8.pt,) 可在RUN pip install -

    2024年02月04日
    浏览(23)
  • yolov8 opencv模型部署(C++版)

    TensorRT系列之 Windows10下yolov8 tensorrt模型加速部署 TensorRT系列之 Linux下 yolov8 tensorrt模型加速部署 TensorRT系列之 Linux下 yolov7 tensorrt模型加速部署 TensorRT系列之 Linux下 yolov6 tensorrt模型加速部署 TensorRT系列之 Linux下 yolov5 tensorrt模型加速部署 TensorRT系列之 Linux下 yolox tensorrt模型加速部

    2024年02月08日
    浏览(24)
  • YOLOv8-Openvino和ONNXRuntime推理【CPU】

    CPU:i5-12500 2.1 Openvino简介 Openvino是由Intel开发的专门用于优化和部署人工智能推理的半开源的工具包,主要用于对深度推理做优化。 Openvino内部集成了Opencv、TensorFlow模块,除此之外它还具有强大的Plugin开发框架,允许开发者在Openvino之上对推理过程做优化。 Openvino整体框架为

    2024年02月20日
    浏览(32)
  • AI模型部署 | onnxruntime部署YOLOv8分割模型详细教程

    本文首发于公众号【DeepDriving】,欢迎关注。 0. 引言 我之前写的文章《基于YOLOv8分割模型实现垃圾识别》介绍了如何使用 YOLOv8 分割模型来实现垃圾识别,主要是介绍如何用自定义的数据集来训练 YOLOv8 分割模型。那么训练好的模型该如何部署呢? YOLOv8 分割模型相比检测模型

    2024年04月24日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包