下载模型
从官方页面https://paddlepaddle.github.io/PaddleX/latest/module_usage/tutorials/ocr_modules/text_detection.html下载PP-OCRv4_server_det 模型tar包并解压
paddle转onnx
安装paddle2onnx
pip install paddle2onnx
转onnx:
paddle2onnx --model_dir ~/Downloads/PP-OCRv4_server_det_infer \
--model_filename inference.pdmodel --params_filename inference.pdiparams \
--save_file ~/Downloads/PP-OCRv4_server_det_infer/model.onnx \
--opset_version 13 --enable_onnx_checker True
使用onnxruntime加载导出的onnx文件报错
[E:onnxruntime:, inference_session.cc:2117 operator()] Exception during initialization: [/onnxruntime_src/onnxruntime/core/providers/cpu/tensor/upsamplebase.h:278](https://file+.vscode-resource.vscode-cdn.net/onnxruntime_src/onnxruntime/core/providers/cpu/tensor/upsamplebase.h:278) onnxruntime::UpsampleMode onnxruntime::UpsampleBase::StringToUpsampleMode(const std::string&) mode attribute is . It can only be nearest(default) or linear or cubic.
原因及解决方法
导出的onnx文件中resize模块的mode为"",而onnxruntime要求必须是nearest(default) or linear or cubic.
import onnx
model_file = './Downloads/PP-OCRv4_server_det_infer/model.onnx'
model = onnx.load(model_file)
for node in model.graph.node:
if 'Resize' in node.name:
print(node.attribute)
[name: "mode"
s: "" # mode属性的值是空字符导致了报错
type: STRING
, name: "coordinate_transformation_mode"
s: "asymmetric"
type: STRING
]
...
遍历resize节点,将mode属性设置为linear
for node in model.graph.node:
if 'Resize' in node.name:
for attr in node.attribute:
if attr.name == 'mode':
node.attribute.remove(attr)
node.attribute.append(onnx.helper.make_attribute('mode', 'linear'))
ret = onnx.checker.check_model(model)
onnx.save(model, './Downloads/PP-OCRv4_server_det_infer/modified.onnx') # 保存修改后的onnx
再次使用onnxruntime加载修改后的onnx运行成功