opencv C++ onnx 模型如何得到多个输出
.
·
有时候咱的模型会输出多个值,怎么拿到呢?
如果只输出一个值,我看很多博客都写了,这篇水文给个例子来看怎么拿到多个返回值
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
如果你暂时还没搞定 opencv 的 C++ 环境问题,可以看一下介篇水文:
https://blog.csdn.net/HaoZiHuang/article/details/127288350
只针对 Linux/mac 哈,windows 自己搜搜吧hhhh
下边是 onnx 模型前向传播的一个demo
// 读入 onnx 模型
std::string model = "onnx_model/xxxxx.onnx";
cv::dnn::Net net = cv::dnn::readNetFromONNX(model);
// 读图
std::string image_path = 图片路径;
cv::Mat frame = cv::imread(image_path);
// OpenCV预处理图片
const float scalefactor = 1.0;
const bool swapRB = true;
const bool crop = false;
const int ddepth = CV_32F;
cv::Size new_size(960, 540);
cv::Mat input_blob = cv::dnn::blobFromImage(frame, scalefactor, new_size, cv::Scalar(), swapRB, crop, ddepth);
// 设置模型输入
net.setInput(input_blob);
std::vector<cv::Mat> output_probs;
net.forward(output_probs, std::vector<cv::String>{"xx", "keps", "offset", "instance", "mhu"});
单输入与多输入不同的是,要用一个 std::vector<cv::Mat> 来接收一下
同时,forward 的第二个参数要传入一个 std::vector<cv::String> 来拿需要的输出值
但是有时候不知道 onnx 模型的输出怎么办,可以用 Python API 搞一下, 看看输入输出名字:
https://blog.csdn.net/HaoZiHuang/article/details/126168132
from pprint import pprint
import onnxruntime
onnx_path = "xxxx.onnx"
provider = "CPUExecutionProvider"
onnx_session = onnxruntime.InferenceSession(onnx_path, providers=[provider])
print("----------------- 输入部分 -----------------")
input_tensors = onnx_session.get_inputs() # 该 API 会返回列表
for input_tensor in input_tensors: # 因为可能有多个输入,所以为列表
input_info = {
"name" : input_tensor.name,
"type" : input_tensor.type,
"shape": input_tensor.shape,
}
pprint(input_info)
print("----------------- 输出部分 -----------------")
output_tensors = onnx_session.get_outputs() # 该 API 会返回列表
for output_tensor in output_tensors: # 因为可能有多个输出,所以为列表
output_info = {
"name" : output_tensor.name,
"type" : output_tensor.type,
"shape": output_tensor.shape,
}
pprint(output_info)
----------------- 输入部分 -----------------
{'name': 'input', 'shape': [1, 3, 540, 960], 'type': 'tensor(float)'}
----------------- 输出部分 -----------------
{'name': 'xx', 'shape': [1, 1, 168, 120], 'type': 'tensor(float)'}
{'name': 'keps', 'shape': [1, 1, 168, 120], 'type': 'tensor(float)'}
{'name': 'offset', 'shape': [1, 2, 168, 120], 'type': 'tensor(float)'}
{'name': 'instance', 'shape': [1, 16, 168, 120], 'type': 'tensor(float)'}
{'name': 'mhu', 'shape': [1, 9, 168, 120], 'type': 'tensor(float)'}
把那几个输出的名字传入就行
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)