终于进入正题了,首先我们先默认已经装好了onnx并且能正常运行,具体步骤跳到第一篇文章去看。
注意,我输入的是特征而不是图片,即输入是二维的不是三维的,三维的情况下篇文章再说。
下方是总体代码,我数据处理部分太长就不贴出来了,最后输入的特征是vector< float >的格式,具体一点就是8046 ,输出是20183,我的label类别有83,特征804卷出来后是201。python的onnx是可以任意长度的输入,不过c++的好像必须是固定长度,这些数字在之前python输出onnx模型的时候就设定好。
详细看代码内部的解析。
#include <assert.h>
#include<onnxruntime_cxx_api.h>
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
string feature2result(vector<float> feature_list)
{
Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "test");
Ort::SessionOptions session_options;
session_options.SetIntraOpNumThreads(1);
session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);
//const char* model_path = "F://c++//test.onnx";
const wchar_t* model_path = L"test.onnx"; //改为模型路径,我一般是最后把路径复制到这个文件旁边,免得绝对路径换环境就完蛋
printf("Using Onnxruntime C++ API\n");
Ort::Session session(env, model_path, session_options);
// print model input layer (node names, types, shape etc.)
Ort::AllocatorWithDefaultOptions allocator;
// print number of model input nodes
size_t num_input_nodes = session.GetInputCount();
std::vector<const char*> input_node_names = {
"input" };
std::vector<const char*> output_node_names = {
"output" };
//后面的数据类型全是float,换成double的报错,我也不知道怎么改,先将就吧
//输入的维度,我是804*6维的特征,这两行依次写1,804,6
std::vector<int64_t> input_node_dims = {
1, 804, 6 }