MacOS C++环境 onnxruntime1.10.0(brew安装)
使用pytorch导出的 .onnx模型文件,其动态轴设定如下:
input = torch.randn(1, 3, 736, 736)
dynamic_axes = {'images': {2: 'height', 3: 'width'},
'output': {2: 'height', 3: 'width'}}
他的维度应该是(1,3,H,W),H和W是可变的。
在C++环境定义了input_node_dims获取onnx输入节点的维度,这里我只有一个输入节点,即为Input 0
auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
ONNXTensorElementDataType type = tensor_info.GetElementType();
printf("Input %d : type=%d\n", i, type);
// print shapes/dims
input_node_dims = tensor_info.GetShape();
printf("Input %d : num_dims=%zu\n", i, input_node_dims.size());
如果规定了动态轴,那么调用的时候那个动态轴的位置默认就是-1,需要手动去覆盖,不然就会报错。
手动覆盖是指用输入图像的维度去覆盖-1,如下:
Ort::TypeInfo type_info = session.GetInputTypeInfo(i);
auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
input_node_dims = tensor_info.GetShape();
// ...读取图像 cv::Mat img
int64_t H = img.rows;
int64_t W = img.cols;
cv::Mat blob;
cv::dnn::blobFromImage(img, blob, 1.0 / 255.0, cv::Size(H, W), mean, true, false); // swap RB
// 创建tensor
size_t input_tensor_size = blob.total();
vector<float> input_tensor_values(input_tensor_size);
//overwrite input dims
input_node_dims[2] = H;
input_node_dims[3] = W;
for (size_t i = 0; i < input_tensor_size; ++i)
{
input_tensor_values[i] = blob.at<float>(i);
}
就OK了