文章目录
0. onnx模型准备以及测试图
参考:https://blog.csdn.net/qq_44747572/article/details/120820964?spm=1001.2014.3001.5501
1. c++使用onnxruntime进行推理
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/dnn.hpp>
#include <iostream>
#include <onnxruntime_cxx_api.h>
#include <assert.h>
#include <vector>
#include <fstream>
using namespace cv; //当定义这一行后,cv::imread可以直接写成imread
using namespace std;
using namespace Ort;
using namespace cv::dnn;
String labels_txt_file = "F:\Pycharm\PyCharm_Study\Others\c++_learning\C++_Master\Onnx\classification\classification_classes_ILSVRC2012.txt";
vector<String> readClassNames(); // string对象作为vector对象
// 图像处理 标准化处理
void PreProcess(const Mat& image, Mat& image_blob)
{
Mat input;
image.copyTo(input);
//数据处理 标准化
std::vector<Mat> channels, channel_p;
split(input, channels);
Mat R, G, B;
B = channels.at(0);
G = channels.at(1);
R = channels.at(2);
B = (B / 255. - 0.406) / 0.225;
G = (G / 255. - 0.456) / 0.224;
R = (R / 255. - 0.485) / 0.229;
channel_p.push_back(R);
channel_p.push_back(G);
channel_p.push_back(B);
Mat outt;
merge(channel_p, outt);
image_blob = outt;
}
// 读取txt文件
std::vector<String> readClassNames()
{
std::vector<String> classNames;
std::ifstream fp(labels_txt_file);
if (!fp.is_open())
{
printf("could not open file...
");
exit(-1);
}
std::string name;
while (!fp.eof())
{
std::getline(fp, name);
if (name.length())
classNames.push_back(name);
}
fp.close();
return classNames;
}
int main() // 返回值为整型带参的main函数. 函数体内使用或不使用argc和argv都可
{
//environment (设置为VERBOSE(ORT_LOGGING_LEVEL_VERBOSE)时,方便控制台输出时看到是使用了cpu还是gpu执行)
Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "