这个代码 "ORTInfer::ORTInfer(const std::string &modelpath, const std::vector<int64t>…
- User
这个代码 "ORTInfer::ORTInfer(const std::string &model_path, const std::vector<int64_t> &input_shape, bool use_gpu, bool onnx_decrypt) { //读取模型 if (!utils::fs::exists(model_path)) { LOG__(LOGID_E, "模型路径不存在! %s", model_path.c_str()); utils::g_bExitSystem = true; return; } std::cout<<model_path<<std::endl;
code//创建ORT环境,设置日志级别 this->ort_env = Ort::Env(); auto session_opts = Ort::SessionOptions(); //尝试使用GPU推理 if (use_gpu) { try { OrtCUDAProviderOptions cuda_options; // cuda_options.gpu_mem_limit = 1024*1024*1024; session_opts.AppendExecutionProvider_CUDA(cuda_options); LOG__(LOGID_I, "使用GPU推理."); } catch (...) { LOG__(LOGID_I, "当前设备GPU不可用, 使用CPU推理."); } } else { LOG__(LOGID_I, "使用CPU推理."); } //读取模型 if (onnx_decrypt) { //解密模型 std::vector<char> onnx_data; FileDecrypt(model_path, onnx_data); //创建会话 this->ort_session = Ort::Session(this->ort_env, onnx_data.data(), onnx_data.size(), session_opts); } else { this->ort_session = Ort::Session(this->ort_env, model_path.c_str(), session_opts); } this->memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault); //校验输入尺寸 auto onnx_inshape = this->ort_session.GetInputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape(); if (onnx_inshape != input_shape) { LOG__(LOGID_E, "ONNX模型尺寸与输入尺寸不一致! 模型尺寸:[%d %d %d %d], 输入尺寸:[%d %d %d %d]", (int)onnx_inshape[0], (int)onnx_inshape[1], (int)onnx_inshape[2], (int)onnx_inshape[3], (int)input_shape[0], (int)input_shape[1], (int)input_shape[2], (int)input_shape[3]); utils::g_bExitSystem = true; return; } //判断模型是否为FP16 auto onnx_type = this->ort_session.GetInputTypeInfo(0).GetTensorTypeAndShapeInfo().GetElementType(); if (onnx_type == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) { this->is_half = true; } LOG__(LOGID_I, "推理精度: %s", this->is_half ? "FP16" : "FP32"); //解析输入输出名称 Ort::AllocatorWithDefaultOptions allocator; this->input_names[0] = strdup(this->ort_session.GetInputNameAllocated(0, allocator).get()); this->output_names[0] = strdup(this->ort_session.GetOutputNameAllocated(0, allocator).get()); //输入输出尺寸 this->input_shape = input_shape; auto onnx_outshape = this->ort_session.GetOutputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape(); this->output_shape = std::vector<int>(onnx_outshape.data(), onnx_outshape.data() + onnx_outshape.size()); for (size_t tmp : this->input_shape) { this->input_size *= tmp; } for (size_t tmp : this->output_shape) { this->output_size *= tmp; } //预推理 LOG__(LOGID_I, "正在对模型进行预推理......"); std::vector<int> img_shape(input_shape.data(), input_shape.data() + input_shape.size()); cv::Mat blob(img_shape, CV_32F), outs; try { this->runOnce(blob, outs); LOG__(LOGID_I, "模型预推理成功."); } catch (...) { LOG__(LOGID_E, "模型预推理失败!"); utils::g_bExitSystem = true; return; } - Assistant