ONNXRUNTUIME c++使用与相关资料(暂记)

news2024/10/1 1:20:40

        下面的教程是在linux系统上运行的,如果想在windows系统上运行,可以看官方链接或中文教程https://bbs.huaweicloud.com/blogs/335706,官方链接中有完整的VS的带.sln的项目。

ONNXRUNTUIME

  • OPENCV不支持某些算子(挤压层在opencv 中不支持)

安装 github.com/microsoft/onnxruntime

配置

cmake_minimum_required(VERSION 3.15)
project(aaa)
set(CMAKE_CXX_STANDARD 14)

option(ONNXRUNTIME_ROOTDIR "/home/dell/CLionProjects/onnxruntime-linux-x64-1.12.1")
find_package(OpenCV REQUIRED)
set(SOURCE_FILES main.cpp)
include_directories(${OpenCV_INCLUDE_DIRS})
include_directories("/home/dell/下载/onnxruntime-1.12.1/include/onnxruntime/core/session/")


add_executable(aaa main.cpp)
target_link_libraries(aaa ${OpenCV_LIBS})
target_link_libraries(aaa "/home/dell/CLionProjects/onnxruntime-linux-x64-1.12.1/lib/libonnxruntime.so")

安装ONNXRUNTIME

  • https://github.com/microsoft/onnxruntime/releases/

新版本(1.13)弃用函数GetInputName 到 GetInputNameAllocator,所以可以使用1.12版本

session->GetInputName(i, allocator));

自己build

  • https://github.com/microsoft/onnxruntime/archive/refs/tags/v1.12.1.zip
    在这里插入图片描述在这里插入图片描述- cd onnxruntime-1.12.1/

  • git init # 如果报错 git submodule sync --recursive fatal: 不是 git 仓库(或者任何父目录):.git

  • ./build.sh --config RelWithDebInfo --build_wheel --update --build

运行一个实力

在这里插入图片描述在这里插入图片描述

//PP-HumanSeg-opencv-onnxrun-main
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <onnxruntime_cxx_api.h>
//#include <cuda_provider_factory.h>  ///如果使用cuda加速,需要取消注释
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
//#include <cuda_provider_factory.h>  ///如果使用cuda加速,需要取消注释
#include <onnxruntime_cxx_api.h>

using namespace cv;
using namespace std;
using namespace Ort;

class pphuman_seg
{
public:
    pphuman_seg();
    Mat inference(Mat cv_image);
private:

    void preprocess(Mat srcimg);
    int inpWidth;
    int inpHeight;
    vector<float> input_image_;
    const float conf_threshold = 0.5;

    Env env = Env(ORT_LOGGING_LEVEL_ERROR, "pphuman-seg");
    Ort::Session *ort_session = nullptr;
    SessionOptions sessionOptions = SessionOptions();
    vector<char*> input_names;
    vector<char*> output_names;
    vector<vector<int64_t>> input_node_dims; // >=1 outputs
    vector<vector<int64_t>> output_node_dims; // >=1 outputs
};

pphuman_seg::pphuman_seg()
{
    string model_path = "/home/dell/CLionProjects/aaa/model_float32.onnx";
    //std::wstring widestr = std::wstring(model_path.begin(), model_path.end());  windows写法
    ///OrtStatus* status = OrtSessionOptionsAppendExecutionProvider_CUDA(sessionOptions, 0);   ///如果使用cuda加速,需要取消注释

    sessionOptions.SetGraphOptimizationLevel(ORT_ENABLE_BASIC);
    //ort_session = new Session(env, widestr.c_str(), sessionOptions); windows写法
    ort_session = new Session(env, model_path.c_str(), sessionOptions); linux写法

    size_t numInputNodes = ort_session->GetInputCount();
    size_t numOutputNodes = ort_session->GetOutputCount();
    AllocatorWithDefaultOptions allocator;
    for (int i = 0; i < numInputNodes; i++)
    {
        input_names.push_back(ort_session->GetInputName(i, allocator));
        Ort::TypeInfo input_type_info = ort_session->GetInputTypeInfo(i);
        auto input_tensor_info = input_type_info.GetTensorTypeAndShapeInfo();
        auto input_dims = input_tensor_info.GetShape();
        input_node_dims.push_back(input_dims);
    }
    for (int i = 0; i < numOutputNodes; i++)
    {
        output_names.push_back(ort_session->GetOutputName(i, allocator));
        Ort::TypeInfo output_type_info = ort_session->GetOutputTypeInfo(i);
        auto output_tensor_info = output_type_info.GetTensorTypeAndShapeInfo();
        auto output_dims = output_tensor_info.GetShape();
        output_node_dims.push_back(output_dims);
    }
    this->inpHeight = input_node_dims[0][2];
    this->inpWidth = input_node_dims[0][3];
}

void pphuman_seg::preprocess(Mat srcimg)
{
    Mat dstimg;
    resize(srcimg, dstimg, Size(this->inpWidth, this->inpHeight), INTER_LINEAR);

    int row = dstimg.rows;
    int col = dstimg.cols;
    this->input_image_.resize(row * col * dstimg.channels());
    for (int c = 0; c < 3; c++)
    {
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                float pix = dstimg.ptr<uchar>(i)[j * 3 + c];
                this->input_image_[c * row * col + i * col + j] = (pix / 255.0 - 0.5) / 0.5;
            }
        }
    }
}

Mat pphuman_seg::inference(Mat srcimg)
{
    this->preprocess(srcimg);
    array<int64_t, 4> input_shape_{1, 3, this->inpHeight, this->inpWidth};

    auto allocator_info = MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
    Value input_tensor_ = Value::CreateTensor<float>(allocator_info, input_image_.data(), input_image_.size(), input_shape_.data(), input_shape_.size());
    vector<Value> ort_outputs = ort_session->Run(RunOptions{ nullptr }, input_names.data(), &input_tensor_, 1, output_names.data(), output_names.size());   // 开始推理
    // post process.
    Value &mask_pred = ort_outputs.at(0);
    const int out_h = this->output_node_dims[0][1];
    const int out_w = this->output_node_dims[0][2];
    float *mask_ptr = mask_pred.GetTensorMutableData<float>();

    Mat segmentation_map;
    Mat mask_out(out_h, out_w, CV_32FC2, mask_ptr);
    resize(mask_out, segmentation_map, Size(srcimg.cols, srcimg.rows));
    Mat dstimg = srcimg.clone();

    for (int h = 0; h < srcimg.rows; h++)
    {
        for (int w = 0; w < srcimg.cols; w++)
        {
            float pix = segmentation_map.ptr<float>(h)[w * 2];
            if (pix > this->conf_threshold)
            {
                float b = (float)srcimg.at<Vec3b>(h, w)[0];
                dstimg.at<Vec3b>(h, w)[0] = uchar(b * 0.5 + 1);
                float g = (float)srcimg.at<Vec3b>(h, w)[1];
                dstimg.at<Vec3b>(h, w)[1] = uchar(g * 0.5 + 1);
                float r = (float)srcimg.at<Vec3b>(h, w)[2];
                dstimg.at<Vec3b>(h, w)[2] = uchar(r * 0.5 + 1);
            }
        }
    }

    for (int h = 0; h < srcimg.rows; h++)
    {
        for (int w = 0; w < srcimg.cols; w++)
        {
            float pix = segmentation_map.ptr<float>(h)[w * 2 + 1];
            if (pix > this->conf_threshold)
            {
                float b = (float)dstimg.at<Vec3b>(h, w)[0];
                dstimg.at<Vec3b>(h, w)[0] = uchar(b * 0.5 + 1);
                float g = (float)dstimg.at<Vec3b>(h, w)[1] + 255.0;
                dstimg.at<Vec3b>(h, w)[1] = uchar(g * 0.5 + 1);
                float r = (float)dstimg.at<Vec3b>(h, w)[2];
                dstimg.at<Vec3b>(h, w)[2] = uchar(r * 0.5 + 1);
            }
        }
    }
    return dstimg;
}

int main()
{
    //return 0;
    const int use_video = 1;
    pphuman_seg mynet;
    if (use_video)
    {
        cv::VideoCapture video_capture("/home/dell/CLionProjects/a.mp4");  ///也可以是视频文件
        if (!video_capture.isOpened())
        {
            std::cout << "Can not open video " << endl;
            return -1;
        }

        cv::Mat frame;
        while (video_capture.read(frame))
        {
            Mat dstimg = mynet.inference(frame);
            string kWinName = "Deep learning ONNXRuntime with pphuman seg";
            namedWindow(kWinName, WINDOW_NORMAL);
            imshow(kWinName, dstimg);
            waitKey(1);
        }
        destroyAllWindows();
    }
    else
    {
        string imgpath = "testimgs/1.jpg";
        Mat srcimg = imread(imgpath);
        Mat dstimg = mynet.inference(srcimg);

        namedWindow("srcimg", WINDOW_NORMAL);
        imshow("srcimg", srcimg);
        static const string kWinName = "Deep learning ONNXRuntime with pphuman seg";
        namedWindow(kWinName, WINDOW_NORMAL);
        imshow(kWinName, dstimg);
        waitKey(0);
        destroyAllWindows();
    }
}

CG

  • https://stackoverflow.com/questions/69633595/load-onnx-model-in-opencv-dnn

  • 如果您使用的是 tf2 并且您的权重为 .h5 形式,我有一个更好的解决方案。 您可以从 .h5 生成 .pb,然后在 C++ 程序中轻松使用

  • Opencv loads models of dynamic input typesOpencv 加载动态输入类型的模型 https://github.com/opencv/opencv/issues/19347

  • https://blog.csdn.net/Fenplan/article/details/116742180

  • https://github.com/hpc203/yolov5-v6.1-opencv-onnxrun

  • https://github.com/leimao/ONNX-Runtime-Inference/tree/main/src

  • https://leimao.github.io/blog/ONNX-Runtime-CPP-Inference/

  • https://onnxruntime.ai/docs/get-started/with-cpp.html

  • https://github.com/microsoft/onnxruntime-inference-examples/tree/main/c_cxx

  • https://blog.csdn.net/Fenplan/article/details/116742180

  • https://github.com/itsnine/yolov5-onnxruntime/blob/master/CMakeLists.txt

  • https://github.com/hpc203/bytetrack-opencv-onnxruntime/blob/main/onnxruntime/cpp/CMakeLists.txt

  • https://github.com/fei176/smoke_monitoring/blob/main/CMakeLists.txt

  • https://github.com/qianqing13579/DetectorSamples/blob/master/CMakeLists.txt
    https://github.com/hpc203/u2net-onnxruntime/blob/main/main.cpp
    https://github.com/lcskrishna/onnx-parser

  • git clone --recursive https://github.com/Microsoft/onnxruntime

  • cd onnxruntime

  • https://www.zhihu.com/answer/2877937918

  • https://github.com/hpc203/yolov5-v6.1-opencv-onnxrun

  • https://github.com/hpc203/yolov7-opencv-onnxrun-cpp-py

  • 1.1 https://github.com/hpc203/PP-HumanSeg-opencv-onnxrun

  • 1.2https://github.com/WoodsGao/opencv_onnx_deploy

  • 1.5https://github.com/EdVince/PSGAN-NCNN

  • 3.0 https://github.com/qianqing13579/DetectorSamples

  • 2.2 https://github.com/xun-xh/yolov5-onnx-pyqt-exe

  • 5.5https://github.com/iwatake2222/InferenceHelper

  • 5.9采用TensorRT的C++接口进行ONNX模型转TRT,并进行Inference推理。https://github.com/MAhaitao999/ONNX_TRT_CPP

  • 6/0Deploy an ONNX model to TensorRT usingOpenCV for I/O https://github.com/FauxShow/trt_cpp_opencv

  • 9 YOLOv7 right in your browser with onnxruntime-web https://github.com/Hyuto/yolov7-onnxruntime-web

  • Detect text in an image with OpenCV https://github.com/Qengineering/OpenCV_OCR_Detect_Text

  • 添加链接描述

  • https://blog.csdn.net/juebai123/article/details/86545556/

  • 推理部署资料整理
    https://zhuanlan.zhihu.com/p/414317269

  • http://onnx.ai/sklearn-onnx/tutorial_1_simple.html

  • https://blog.csdn.net/wsp_1138886114/article/details/123271871

  • 格灵深瞳
    中文简体:本项目将不再频繁更新,更优的部署体验请尝试zapPaddlePaddle/FastDeploy : zap一款简单易用的推理部署工具箱。覆盖业界主流优质预训练模型并提供开箱即用的开发体验,包括图像分类、目标检测、图像分割、人脸检测、人体关键点识别、文字识别等多任务,满足开发者多场景,多硬件、多平台的快速部署需求,并同时支持 C++ 和 Python 两种语言。lite.ai.toolkit 中的核心模型未来将会以contrib的方式集成到zapPaddlePaddle/FastDeploy 中。欢迎同学们使用 handpoint_rightzapPaddlePaddle/FastDeploy.

似乎 opencv 不支持具有动态输入形状的 onnx 模型,请查看此链接。尝试构建最新版本的 opencv。另外,请检查此链接 .已经提到对Yunet使用固定的输入形状。如果以前的建议不起作用,请使用以下方法。
如果您使用的是 tf2 并且您的权重是 .h5 形式,您将能够处理 onnx 麻烦 .您可以从 .h5 生成 .pb,然后在 C++ 中轻松使用 program.to 目标生成 .pb,使用以下代码:
之后,通过使用OpenCV,您将能够导入您的模型,然后享受!

在这里插入图片描述

opencv_sample-master

  • https://github.com/iwatake2222/opencv_sample/blob/master/dnn_face/face_detection.cpp

  • 【全网最小的Yolov5实现,364Kb纯C-哔哩哔哩】 https://b23.tv/2IvAN8J

  • https://www.zhihu.com/answer/2880316516

  • https://github.com/blueloveth/pocketpy

  • https://www.zhihu.com/answer/2788934753搞台淘汰安卓手机安装 Linux Deploy 就能平替

  • C++调用Python,C++调用Python视觉算法模型,C++传递Mat格式的图片数据到

  • https://github.com/Qihoo360/safe-rules

  • GPU-Puzzles: 玩游戏学CUDA https://zhuanlan.zhihu.com/p/597684060

  • 全球最好用的3D打印免费测试网站详细讲解

https://github.com/dlunion/tensorRTIntegrate

  • https://github.com/ttanzhiqiang/onnx_tensorrt_project
cmake_minimum_required(VERSION 3.15)
project(onnx)
set(CMAKE_CXX_STANDARD 14)

MESSAGE(STATUS "Project: onnx")              
find_package(OpenCV REQUIRED)
set(SOURCE_FILES main.cpp)
include_directories(${OpenCV_INCLUDE_DIRS})
include_directories("/home/dell/CLionProjects/onnxruntime-linux-x64-1.12.1/include")# https://blog.csdn.net/sinat_31608641/article/details/121736503

add_executable(onnx main.cpp)
target_link_libraries(onnx ${OpenCV_LIBS})
link_directories("/home/dell/CLionProjects/onnxruntime-linux-x64-1.12.1/lib")
- https://www.w3cschool.cn/doc_cmake_3_6/cmake_3_6-command-target_link_libraries.html
- https://www.cnblogs.com/stonemjl/articles/12668208.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/338404.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

开关电源环路稳定性分析(10)——OPA和OTA型补偿器传递函数

大家好&#xff0c;这里是大话硬件。 在前面9讲的内容中将开关电源环路分析进行了梳理&#xff0c;我相信很多人即使都看完了&#xff0c;应该还是不会设计&#xff0c;而且还存在几个疑问。比如我随便举几个&#xff1a; 开关电源的带宽怎么设定&#xff1f;开关电源精度和什…

IDEA下java程序的调试(简易实例图示版)

在线排版不太好看&#xff0c;介意的读者可下载word下来看&#xff1a;https://download.csdn.net/download/xijinno1/87441301IDEA下java程序的简单调试-System.out.println首先本次进行调试的一个程序是实现从1累加到100的功能&#xff0c;是在IDEA下进行编写的。如图所示&am…

1626_MIT 6.828 lab1课程大纲学习过程整理

全部学习汇总&#xff1a; GreyZhang/g_unix: some basic learning about unix operating system. (github.com) 现在lab1的内容全都学习完了&#xff0c;该做的练习也都做了。接下来&#xff0c;整理一下自己看这一部分课程讲义的一些笔记。 整理之前&#xff0c;先把自己完成…

c# 跑马灯显示

//本文演示跑马灯//用到了线程、同步委托using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;using System.IO;nam…

鲜花数据集实验结果总结

从read_split_data中得到&#xff1a;训练数据集&#xff0c;验证数据集&#xff0c;训练标签&#xff0c;验证标签。的所有的具体详细路径 数据集位置&#xff1a;https://download.csdn.net/download/guoguozgw/87437634 import os #一种轻量级的数据交换格式&#xff0c; …

常见漏洞之 struts2+ jboss

数据来源 本文仅用于信息安全的学习&#xff0c;请遵守相关法律法规&#xff0c;严禁用于非法途径。若观众因此作出任何危害网络安全的行为&#xff0c;后果自负&#xff0c;与本人无关。 01 Struts2相关介绍 》Struts2概述 》Struts2历史漏洞&#xff08;1&#xff09; 》…

【Linux】Linux多线程(下)

前言 大家好呀,欢迎来到我的Linux学习笔记~ 本篇承上Linux多线程创建,线程互斥(互斥锁),线程同步(条件变量),继下接着学习线程同步的另一个信号量,以及后序的线程池&#xff0c;线程的懒汉单例模式和其他锁相关知识。&#xff08;注意本篇博客代码居多&#xff09; Linux多线程…

C++005-C++选择与分支2

文章目录C005-C选择与分支2条件语句C实现else if 语句题目描述 根据成绩输出成绩等级ABCDEif嵌套语句题目描述 输出三个数中的最大值题目描述 模拟游戏登录switch语句三元运算符题目描述 输出三个数中的最大值-基于3元运算符题目描述 根据1-7输出星期1-星期日案例练习题目描述 …

php的api系统,php api 框架

本文目录一览&#xff1a; 1、php如何开发API接口2、什么是API&#xff1f;PHP的API怎么写&#xff1f;3、API和PHP是什么关系4、php中的API接口怎么写 ?5、如何使用PHP搭建一个restFul风格的API系统6、PHP 的API接口 php如何开发API接口 比如一个自定义函数&#xff1a;fun…

【遇见青山】项目难点:缓存击穿问题解决方案

【遇见青山】项目难点&#xff1a;缓存击穿问题解决方案1.缓存击穿互斥锁&#x1f512;方案逻辑过期方案2.基于互斥锁方案的具体实现3.基于逻辑过期方案的具体实现1.缓存击穿 缓存击穿问题也叫热点Key问题&#xff0c;就是一个被高并发访问并且缓存重建业务较复杂的key突然失效…

RuoYi-Cloud 部署

RuoYi-Cloud部署 1. 下载 点击右侧链接可以进入gitee的源码下载地址&#xff1a; 偌依微服务源码gitee下载地址 2. 数据库部署 依据如下步骤创建系统所需数据环境&#xff0c;脚本执行没有先后次序要求&#xff1a; 在Mysql 中创建 ry-cloud 主数据库&#xff0c;并执行 …

初学者必读:讲解 VC 下如何正确的创建、管理及发布项目

Visual C 的项目文件组成&#xff0c;以及如何正确的创建及管理项目。 本内容是初学者必须要掌握的。不能正确的管理项目&#xff0c;就不能进一步写有规模的程序。 一、项目下各种常见文件类型的功能 1. 代码文件 扩展名为 .cpp、.c、.h 等。 通常情况下&#xff0c;项目…

【Java】Help notes about JAVA

JAVA语言帮助笔记Java的安装与JDKJava命名规范JAVA的数据类型自动类型转换强制类型转换JAVA的运算符取余运算结果的符号逻辑运算的短路运算三元运算符运算符优先级JAVA的流程控制分支结构Java的安装与JDK JDK安装网站&#xff1a;https://www.oracle.com/java/technologies/do…

[项目设计]高并发内存池

目录 1、项目介绍 2、高并发内存池整体框架设计 3、thread cache <1>thread cache 哈希桶对齐规则 <2>Thread Cache类设计 4、Central Cache <1>Central Cache类设计 5、page cache <1>Page Cache类设计 6、性能分析 <1>定长内存池实现…

更换主板开机logo

更换主板开机logo前言详细操作步骤可能遇到的问题素材链接前言 在使用刀锋钛主板后发现&#xff0c;开机logo有些不符合个人喜好&#xff0c;如下图&#xff1a; 于是就有了更换主板logo的想法&#xff0c;确定用刷bios这一方法&#xff0c;注&#xff1a;刷BIOS之前一定要做…

MS14-064(OLE远程代码执行漏洞复现)

✅作者简介&#xff1a;CSDN内容合伙人、信息安全专业在校大学生&#x1f3c6; &#x1f525;系列专栏 &#xff1a;内网安全-漏洞复现 &#x1f4c3;新人博主 &#xff1a;欢迎点赞收藏关注&#xff0c;会回访&#xff01; &#x1f4ac;舞台再大&#xff0c;你不上台&#xf…

Java测试——selenium常见操作(2)

这篇博客继续讲解一些selenium的常见操作 selenium的下载与准备工作请看之前的博客&#xff1a;Java测试——selenium的安装与使用教程 先创建驱动 ChromeDriver driver new ChromeDriver();等待操作 我们上一篇博客讲到&#xff0c;有些时候代码执行过快&#xff0c;页面…

Axios异步请求 json格式

Axios是Ajax的一个框架,简化Ajax操作。需要axios.min.js 和vue.js的jar。发送普通参数异步请求以及相应异常情况客户端向服务器端异步发送普通参数值&#xff1a;- 基本格式&#xff1a; axios().then().catch()- 示例&#xff1a;axios({ // axios表示要发送一个异步请求metho…

12月无情被辞:想给还不会自动化测试的技术人提个醒

公司前段时间缺人&#xff0c;也面了不少测试&#xff0c;结果竟没有一个合适的。一开始瞄准的就是中级的水准&#xff0c;也没指望来大牛&#xff0c;提供的薪资在10-20k&#xff0c;面试的人很多&#xff0c;但是平均水平很让人失望。基本能用一句话概括就是&#xff1a;3年测…

火遍全网的ChatGPT,可免费使用啦

啰嗦几句最近最最最火爆的莫过于ChatGPT了&#xff0c;感觉你不知道ChatGPT是什么做什么&#xff0c;你都没法跟人交流了&#xff01;ChatGPT是美国OpenAI研发的聊天机器人程序&#xff0c;跟小冰、小爱、小度一样&#xff0c;但是不一样的是它拥有强大的信息整合能力&#xff…