概述

将得到的模型转化为onnx模型,加载到c++中运行,来完成模型的部署,下载并安装onnxruntime;

CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)
project(test)#使用clang++编译器
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_BUILD_TYPE "Release")
set(CMAKE_INCLUDE_CURRENT_DIR ON)#find the opencv and the qt5
find_package(OpenCV 4.5.1  REQUIRED)
#onnxruntime
set(ONNXRUNTIME_ROOT_PATH /home/zyl/ubuntu/tensorRT/onnxruntime-master)
set(ONNXRUNTIME_INCLUDE_DIRS ${ONNXRUNTIME_ROOT_PATH}/include/onnxruntime${ONNXRUNTIME_ROOT_PATH}/onnxruntime${ONNXRUNTIME_ROOT_PATH}/include/onnxruntime/core/session/)
set(ONNXRUNTIME_LIB ${ONNXRUNTIME_ROOT_PATH}/build/Linux/Release/libonnxruntime.so)
include_directories(${ONNXRUNTIME_INCLUDE_DIRS})add_executable(${PROJECT_NAME} "main.cpp")
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS} ${ONNXRUNTIME_LIB})

C++源码:

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <chrono>
#include <string>//onnxruntime
#include <core/session/onnxruntime_cxx_api.h>
#include <core/providers/cuda/cuda_provider_factory.h>
#include <core/session/onnxruntime_c_api.h>
#include <core/providers/tensorrt/tensorrt_provider_factory.h>using namespace std;int main(int argc,char ** argv)
{//输入网络的维度static constexpr const int width = 600;static constexpr const int height = 600;static constexpr const int channel = 3;std::array<int64_t, 4> input_shape_{ 1,height, width,channel};//-------------------------------------------------------------onnxruntime-------------------------------------------------//图片和模型位置string img_path = argv[1];string model_path = "model.onnx";cv::Mat imgSource = cv::imread(img_path);Ort::Env env(OrtLoggingLevel::ORT_LOGGING_LEVEL_WARNING, "Detection");Ort::SessionOptions session_options;//CUDA加速开启//OrtSessionOptionsAppendExecutionProvider_Tensorrt(session_options, 0); //tensorRTOrtSessionOptionsAppendExecutionProvider_CUDA(session_options, 0);session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);Ort::AllocatorWithDefaultOptions allocator;//加载ONNX模型Ort::Session session(env, model_path.c_str(), session_options);//获取输入输出的维度std::vector<int64_t> input_dims = session.GetInputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape();std::vector<int64_t> output_dims = session.GetOutputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape();/*session.GetOutputName(1, allocator);session.GetInputName(1, allocator);//输出模型输入节点的数量size_t num_input_nodes = session.GetInputCount();size_t num_output_nodes = session.GetOutputCount();*/std::vector<const char*> input_node_names = {"image_tensor:0"};std::vector<const char*> output_node_names = {"detection_boxes:0","detection_scores:0","detection_classes:0","num_detections:0" };input_dims[0] = output_dims[0] = 1;//batch size = 1std::vector<Ort::Value> input_tensors;auto memory_info = Ort::MemoryInfo::CreateCpu(OrtAllocatorType::OrtArenaAllocator, OrtMemType::OrtMemTypeDefault);//将图像存储到uchar数组中,BGR--->RGBstd::array<uchar, width * height *channel> input_image_{};uchar* input =  input_image_.data();for (int i = 0; i < imgSource.rows; i++) {for (int j = 0; j < imgSource.cols; j++) {for (int c = 0; c < 3; c++){//NHWC 格式if(c==0)input[i*imgSource.cols*3+j*3+c] = imgSource.ptr<uchar>(i)[j*3+2];if(c==1)input[i*imgSource.cols*3+j*3+c] = imgSource.ptr<uchar>(i)[j*3+1];if(c==2)input[i*imgSource.cols*3+j*3+c] = imgSource.ptr<uchar>(i)[j*3+0];//NCHW 格式
//                if (c == 0)
//                     input[c*imgSource.rows*imgSource.cols + i * imgSource.cols + j] = imgSource.ptr<uchar>(i)[j * 3 + 2];
//                if (c == 1)
//                     input[c*imgSource.rows*imgSource.cols + i * imgSource.cols + j] = imgSource.ptr<uchar>(i)[j * 3 + 1];
//                if (c == 2)
//                     input[c*imgSource.rows*imgSource.cols + i * imgSource.cols + j] = imgSource.ptr<uchar>(i)[j * 3 + 0];}}}input_tensors.push_back(Ort::Value::CreateTensor<uchar>(memory_info, input, input_image_.size(), input_shape_.data(), input_shape_.size()));//不知道输入维度时//input_tensors.push_back(Ort::Value::CreateTensor<uchar>(//        memory_info, input, input_image_.size(), input_dims.data(), input_dims.size()));chrono::steady_clock::time_point t1 = chrono::steady_clock::now();std::vector<Ort::Value> output_tensors;for(int i=0; i<100;i++)output_tensors = session.Run(Ort::RunOptions { nullptr },input_node_names.data(), //输入节点名input_tensors.data(),     //input tensorsinput_tensors.size(),     //1output_node_names.data(), //输出节点名output_node_names.size()); //4chrono::steady_clock::time_point t2 = chrono::steady_clock::now();chrono::duration<double> delay_time = chrono::duration_cast<chrono::duration<double>>(t2 - t1); //milliseconds 毫秒cout<<"前向传播平均耗时:"<<delay_time.count()*1000/100.0<<"ms"<<endl;float* boxes_ = output_tensors[0].GetTensorMutableData<float>();float* scores_ = output_tensors[1].GetTensorMutableData<float>();float* class_ = output_tensors[2].GetTensorMutableData<float>();float* num_detection = output_tensors[3].GetTensorMutableData<float>();//-------------------------------------------------------------onnxruntime-------------------------------------------------//------------------循环遍历显示检测框--------------------------cv::Mat frame(imgSource.clone());for (int i = 0; i < num_detection[0]; i++){float confidence = scores_[i];size_t objectClass = (size_t)class_[i];if (confidence >= 0.8){int xLeftBottom = static_cast<int>(boxes_[i*4 + 1] * frame.cols);int yLeftBottom = static_cast<int>(boxes_[i*4 + 0] * frame.rows);int xRightTop = static_cast<int>(boxes_[i*4 + 3] * frame.cols);int yRightTop = static_cast<int>(boxes_[i*4 + 2]* frame.rows);//显示检测框cv::Rect object((int)xLeftBottom, (int)yLeftBottom,(int)(xRightTop - xLeftBottom),(int)(yRightTop - yLeftBottom));cv::rectangle(frame, object, cv::Scalar(0,0,255), 2);cv::String label = cv::String("confidence :") +to_string(confidence);int baseLine = 0;cv::Size labelSize = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.3, 1, &baseLine);cv::rectangle(frame, cv::Rect(cv::Point(xLeftBottom, yLeftBottom - labelSize.height),cv::Size(labelSize.width, labelSize.height + baseLine)),cv::Scalar(255, 255, 0), cv::FILLED);cv::putText(frame, label, cv::Point(xLeftBottom, yLeftBottom),cv::FONT_HERSHEY_SIMPLEX, 0.3, cv::Scalar(0, 0, 0));}}cv::imshow("frame",frame);cv::waitKey(0);return 0;}

参考链接:

  1. https://codechina.csdn.net/mirrors/tenglike1997/onnxruntime-projects/-/blob/master/Ubuntu/onnx_mobilenet
  2. https://blog.csdn.net/mightbxg/article/details/119237326

在C++上利用onnxruntime (CUDA)和 opencv 部署模型onnx相关推荐

  1. android代码查找图像,Android平台上利用opencv进行图像的边沿检测

    原标题:Android平台上利用opencv进行图像的边沿检测 近开始接触opencv for Android,从网上down了图像的边沿检测的代码. 测试图片: 在Android2.3.1模拟器上跑 ...

  2. 在NVIDIA A100 GPU上利用硬件JPEG解码器和NVIDIA nvJPEG库

    在NVIDIA A100 GPU上利用硬件JPEG解码器和NVIDIA nvJPEG库 根据调查,普通人产生的1.2万亿张图像可以通过电话或数码相机捕获.这样的图像的存储,尤其是以高分辨率的原始格式, ...

  3. 在机械狗上利用AstraPro3D深度摄像头简单实现目标跟踪和人体姿态识别

    本次任务是将AstraPro3D摄像头和机械狗运用起来,AstraPro为奥比中光开发的3D传感摄像头,机械狗是云深处绝影mini,过程中主要运用到了AstraSDK做骨架提取,ros系统控制机械狗和 ...

  4. Github上利用win10使用TensorFlow(GPU)上如何去训练一个目标多分类检测的例子

    Github上利用win10使用TensorFlow(GPU)上如何去训练一个目标多分类检测的例子 我们从github找到一个用fast-rcnn训练模型用于目标物体检测的例子,文中是实现检测扑克牌的 ...

  5. opencv在电脑屏幕上画_用Python+OpenCV让电脑帮你玩微信跳一跳

    前言 最近微信小游戏跳一跳大热,自己也是中毒颇久,无奈手残最高分只拿到200分.无意间看到教你用Python来玩微信跳一跳一文,在电脑上利用adb驱动工具操作手机,详细的介绍以及如何安装adb驱动可以 ...

  6. 在服务器上利用mmdetection来训练自己的voc数据集

    在服务器上利用mmdetection来训练自己的voc数据集 服务器上配置mmdetection环境 在服务器上用anaconda配置自己的环境 进入自己的虚拟环境,开始配置mmdetection 跑 ...

  7. 在Ubuntu 16.04.5 LTS上利用python中的PIL模块压缩一百多兆的单张图片实操

    在前面的博文中,我将300多张电影海报拼接为了一张103MB的巨幅图片,我想拿它做电脑桌面(1080P),但是这么多的图片,存储和加载是个麻烦事儿,需要将它压缩到几MB大小. 在Ubuntu 16.0 ...

  8. 在Linux上利用python获取本机ip

    下面介绍在Linux上利用python获取本机ip的方法. 经过网上调查, 发现大致有两种方法, 一种是调用shell脚本,另一种是利用python中的socket等模块来得到,下面是这两种方法的源码 ...

  9. linux nmcli源码,Linux上利用nmcli命令创建网络组(示例代码)

    网络组:是将多个网卡聚合在一起方法,从而实现冗错和提高吞吐量 网络组不同于旧版中bonding技术,提供更好的性能和扩展性 网络组由内核驱动和teamd守护进程实现. 下面我们以CentOS7系统为环 ...

  10. Windows学习总结(23)——在 Windows 10 子系统 ubuntu 上利用 WSL2 安装 docker 的 2 种方式

    前言 windows10 目前推出了WSL2,相对于WSL采用API转换的方式, WSL2 则完全不同,win10 开始内置了一个轻量级虚拟机,经过不断的优化,这个虚拟机实现了与 windows 的高 ...

最新文章

  1. 基于BCH的SLP代币超过1000种,探秘SLP的内部生态
  2. git更改已提交作者用户名
  3. 干货|用配电安全基础知识及隐患排查重点PPT
  4. 【LeetCode】- Search Insert Position(查找插入的位置)
  5. mysql 备库 hang住_mysql主键的缺少导致备库hang住
  6. 坚定不移地加速,并且不断解决新问题
  7. 因为我们还很穷,所以世界杯氛围差
  8. 2021年高考成绩什么时候查询辽宁,2021年辽宁高考成绩什么时候几点可以查
  9. 学校如何把表格里的成绩,让学生以二维码的方式去扫描查询呢?
  10. python发QQ邮件
  11. 用计算机写试卷反思,计算机试卷
  12. python自动化测试流程_接口自动化基本流程(python)
  13. sql语句where的执行顺序
  14. GenBank数据格式
  15. lvds输入悬空_LVDS布线的一般原则
  16. NDT-MCL定位算法论文解读
  17. adb devices 无法识别手机设备
  18. 15000 字的 MySQL 速查手册
  19. JS事件对象 (event)
  20. grasshopper python可以做什么_Grasshopper 有哪些奇技淫巧?

热门文章

  1. dom4j解析xml_JAVADom、Sax解析XML详解
  2. linux 内核usb,Linux 内核示例程序 usb_skeleton.c 详解
  3. lisp封装成vla函数_牛逼,自动将函数或者命令行工具转换成 Web 服务
  4. 通过 docker 搭建自用的 gitlab 服务
  5. centos7 yum安装zabbix监控
  6. linux 查看系统内存及系统负载
  7. vuex - 学习日记
  8. django1.2中将ManyToManyField呈现为checkbox
  9. HDU 4421 Bit Magic(2-sat)
  10. http长轮询短轮询