Python 成功将Midas模型转换为ONNX后出现ONNX运行时测试错误

Python 成功将Midas模型转换为ONNX后出现ONNX运行时测试错误,python,pytorch,onnx,onnxruntime,Python,Pytorch,Onnx,Onnxruntime,最后,我问我的第一个问题。在过去的几天里,我一直在努力解决这个问题,但在这里找不到同样的问题 我使用以下代码转换为ONNX: import torch from midas import midas_net import onnx model_path = "model-f46da743.pt" model = midas_net.MidasNet(model_path, non_negative=True) sample = torch.randn(1,3,384,672

最后,我问我的第一个问题。在过去的几天里,我一直在努力解决这个问题,但在这里找不到同样的问题

我使用以下代码转换为ONNX:

import torch
from midas import midas_net
import onnx

model_path = "model-f46da743.pt"
model = midas_net.MidasNet(model_path, non_negative=True)
sample = torch.randn(1,3,384,672) # input_shape
torch.onnx.export(model,
                  sample,
                  "midas.onnx",
                  opset_version=11)

onnx_model = onnx.load("midas.onnx")
# Print a human readable representation of the graph
graph_output = onnx.helper.printable_graph(onnx_model.graph)
with open("graph.txt", mode="w") as fout:
    fout.write(graph_output)
我用Netron打开了midas.onnx,看起来不错。然后我尝试用onnxruntime测试它:

import torch
import utils
import cv2
from torchvision.transforms import Compose
from midas import transforms
import onnxruntime # Tool for scoring ONNX models
import onnx

# select device
device = torch.device("cpu")
# print("device: %s" % device)

model = "/home/ipu/libraries/MiDaS/midas.onnx"
sess = onnxruntime.InferenceSession(model) # Load a ONNX model
# print(sess) # <onnxruntime.capi.session.InferenceSession object at 0x7f07d5e10f10>

input_name = sess.get_inputs()[0].name
# print(input_name) # input.1

input_shape = sess.get_inputs()[0].shape
# print("input shape", input_shape) # [1, 3, 384, 672]

output_name = sess.get_outputs()[0].name
# print(output_name) # 1176

output_shape = sess.get_outputs()[0].shape
# print("output shape", output_shape) # [1, 384, 672]

# Check that the Intermediate Representation (IR) is well formed
# print("check onnx model ", onnx.checker.check_model(onnx.load(model))) # None

transform = Compose(
    [
        transforms.Resize(
            384,
            384,
            resize_target=None,
            keep_aspect_ratio=True,
            ensure_multiple_of=32,
            resize_method="lower_bound",
            image_interpolation_method=cv2.INTER_CUBIC,
        ),
        transforms.NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
        transforms.PrepareForNet(),
    ]
)

# get input
img = utils.read_image("input/20200629_123103.jpg")
img_input = transform({"image": img})["image"]

sample = torch.from_numpy(img_input).to(device).unsqueeze(0)
# print("sample", sample)
# print("sample shape", sample.shape) # torch.Size([1, 3, 384, 672])
# print(type(sample)) # <class 'torch.Tensor'>

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

# print("to numpy sample", to_numpy(sample))
# print("to numpy sample shape", to_numpy(sample).shape) # (1, 3, 384, 672)
# print(type(to_numpy(sample))) # <class 'numpy.ndarray'>

# Input must be a list of dictionaries or a single numpy array
ort_outs = sess.run([output_name], {input_name: to_numpy(sample)})
print(ort_outs)
导入火炬
导入UTIL
进口cv2
来自torchvision.com
从midas导入转换
导入ONNX运行时#用于对ONNX模型评分的工具
导入onnx
#选择设备
设备=火炬。设备(“cpu”)
#打印(“设备:%s”%device)
model=“/home/ipu/libraries/MiDaS/MiDaS.onnx”
sess=onnxruntime.推断会话(模型)#加载ONNX模型
#印刷品(sess)#
input_name=sess.get_inputs()[0].name
#打印(输入名称)#输入。1
input_shape=sess.get_inputs()[0]。shape
#打印(“输入形状”,输入U形)#[1,3,384,672]
output\u name=sess.get\u outputs()[0].name
#打印(输出名称)#1176
output\u shape=sess.get\u outputs()[0]。shape
#打印(“输出形状”,输出U形)#[1384672]
#检查中间表示(IR)是否格式正确
#打印(“检查onnx模型”,onnx.checker.check_模型(onnx.load(model)))#无
变换=合成(
[
变换。调整大小(
384,
384,
resize_target=None,
保持纵横比=真,
确保倍数=32,
resize_method=“lower_bound”,
图像插值法=cv2.INTER\u立方,
),
归一化年龄(平均值=[0.485,0.456,0.406],标准值=[0.229,0.224,0.225]),
transforms.PrepareForNet(),
]
)
#获取输入
img=utils.read\u image(“input/20200629\u 123103.jpg”)
img_输入=变换({“图像”:img})[“图像”]
样本=火炬。从(img输入)。到(设备)。取消查询(0)
#打印(“样本”,样本)
#打印(“样本形状”,样本形状)#火炬大小([1,3384672])
#打印(类型(样本))#
def to_numpy(张量):
如果tensor.requires_grad else tensor.cpu().numpy(),则返回tensor.detach().cpu().numpy()
#打印(“至numpy样本”,至_numpy(样本))
#打印(“到numpy样本形状”,到_numpy(样本).shape)#(1,3,384,672)
#打印(打印(打印到numpy(样本)))#
#输入必须是字典列表或单个numpy数组
ort\u outs=sess.run([output\u name],{input\u name:to\u numpy(sample)})
打印(输出)
但是,我有一个错误:

2020-07-15 10:55:23.402764485 [E:onnxruntime:, sequential_executor.cc:281 Execute] Non-zero status code returned while running Resize node. Name:'' Status Message: /onnxruntime_src/onnxruntime/core/providers/cpu/tensor/upsample.h:283 void onnxruntime::UpsampleBase::ScalesValidation(const std::vector<float>&, onnxruntime::UpsampleMode) const scales.size() == 2 || (scales.size() == 4 && scales[0] == 1 && scales[1] == 1) was false. 'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the Resize operator

Traceback (most recent call last):
  File "simple_test.py", line 73, in <module>
    ort_outs = sess.run([output_name], {input_name: to_numpy(sample)})
  File "/home/ipu/anaconda3/envs/midas/lib/python3.7/site-packages/onnxruntime/capi/session.py", line 111, in run
    return self._sess.run(output_names, input_feed, run_options)
onnxruntime.capi.onnxruntime_pybind11_state.RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Resize node. Name:'' Status Message: /onnxruntime_src/onnxruntime/core/providers/cpu/tensor/upsample.h:283 void onnxruntime::UpsampleBase::ScalesValidation(const std::vector<float>&, onnxruntime::UpsampleMode) const scales.size() == 2 || (scales.size() == 4 && scales[0] == 1 && scales[1] == 1) was false. 'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the Resize operator
2020-07-15 10:55:23.402764485[E:onnxruntime:,sequential_executor.cc:281 Execute]运行Resize节点时返回的非零状态代码。名称:''状态消息:/onnxruntime\u src/onnxruntime/core/providers/cpu/tensor/upsample.h:283 void onnxruntime::UpsampleBase::ScalesValidation(const std::vector&,onnxruntime::UpsampleMode)const scales.size()==2 | |(scales.size()=4&&scales[0]==1&&scales[1]=1)为false。'“线性”模式和“立方”模式仅支持二维输入(“双线性”、“双三次”)或四维输入,在“调整大小”操作符中,对应的最外层2个刻度值为1
回溯(最近一次呼叫最后一次):
文件“simple_test.py”,第73行,在
ort\u outs=sess.run([output\u name],{input\u name:to\u numpy(sample)})
文件“/home/ipu/anaconda3/envs/midas/lib/python3.7/site packages/onnxruntime/capi/session.py”,第111行,运行中
返回self.\u sess.run(输出\u名称、输入\u提要、运行\u选项)
onnxruntime.capi.onnxruntime\u pybind11\u state.RuntimeException:[ONNXRuntimeError]:6:运行时\u异常:运行Resize节点时返回的非零状态代码。名称:''状态消息:/onnxruntime\u src/onnxruntime/core/providers/cpu/tensor/upsample.h:283 void onnxruntime::UpsampleBase::ScalesValidation(const std::vector&,onnxruntime::UpsampleMode)const scales.size()==2 | |(scales.size()=4&&scales[0]==1&&scales[1]=1)为false。'“线性”模式和“立方”模式仅支持二维输入(“双线性”、“双三次”)或四维输入,在“调整大小”操作符中,对应的最外层2个刻度值为1
关于更多信息,我使用Pytorch(1.3.1)、ONNX(1.7.0)和Onnxruntime(1.3.0)


非常感谢您的帮助。

您能将onnx型号连接起来吗?我似乎无法运行导出脚本。它失败,出现以下错误“ImportError:无法导入名称'midas_net'”。
而且,这个错误是不言自明的。此处的scales是此处提到的scales数组:。比例输入是否与错误消息中提到的约束匹配?

能否连接onnx型号?我似乎无法运行导出脚本。它失败,出现以下错误“ImportError:无法导入名称'midas_net'”。
而且,这个错误是不言自明的。此处的scales是此处提到的scales数组:。刻度输入是否与错误消息中提到的约束匹配?

我通过将pytorch版本从1.3.1升级到1.4.0解决了这个问题

conda install pytorch=1.4.0 -c pytorch

我通过将pytorch版本从1.3.1升级到1.4.0解决了这个问题

conda install pytorch=1.4.0 -c pytorch