
RapidOCR模型转换全流程从ONNX到昇腾OM的完整教程【免费下载链接】rapidocr项目地址: https://ai.gitcode.com/lhwLHWjackL/rapidocr在当今AI技术飞速发展的时代高效的模型部署对于开发者和企业来说至关重要。RapidOCR作为一款功能强大的OCR工具支持将ONNX模型转换为昇腾OM格式以充分利用昇腾NPU的计算优势。本教程将详细介绍RapidOCR模型从ONNX到昇腾OM的完整转换流程帮助您快速掌握模型部署的关键步骤。一、准备工作在开始模型转换之前需要确保您的环境中已经安装了必要的工具和依赖。首先您需要克隆RapidOCR仓库git clone https://gitcode.com/lhwLHWjackL/rapidocr进入项目目录后建议创建并激活一个虚拟环境以避免依赖冲突。然后安装项目所需的依赖包cd rapidocr pip install -r requirements.txt此外还需要安装昇腾AI工具链包括ATCAscend Tensor Compiler等工具用于将模型转换为OM格式。您可以从昇腾官方网站下载并安装相应的工具包。二、模型转换步骤2.1 准备ONNX模型RapidOCR项目中已经提供了预训练的ONNX模型位于onnx/目录下。例如PP-OCRv4的检测模型、识别模型和分类模型分别位于onnx/PP-OCRv4/det/、onnx/PP-OCRv4/rec/和onnx/PP-OCRv4/cls/目录下。您可以直接使用这些模型进行转换也可以使用自己训练的ONNX模型。2.2 修复ONNX模型由于PaddlePaddle导出的ONNX模型可能存在一些兼容性问题需要先对模型进行修复。RapidOCR提供了scripts/convert_to_npu.py脚本其中的fix_onnx函数可以将ONNX模型中的Constant节点转换为初始izers以确保模型能够正确转换为PyTorch格式。以下是修复ONNX模型的关键代码片段def fix_onnx(onnx_path): Fix PaddlePaddle ONNX file by converting Constant nodes to initializers. import onnx from onnx import helper, shape_inference model onnx.load(onnx_path) inferred shape_inference.infer_shapes(model) tensors [] for node in inferred.graph.node: if node.op_type Constant: for attr in node.attribute: if attr.name value: t attr.t t.name node.output[0] tensors.append(t) break non_const [n for n in inferred.graph.node if n.op_type ! Constant] new_graph helper.make_graph( nodesnon_const, nameinferred.graph.name, inputslist(inferred.graph.input), outputslist(inferred.graph.output), initializertensors, value_infolist(inferred.graph.value_info), ) new_model helper.make_model(new_graph, opset_importsmodel.opset_import) new_model.ir_version model.ir_version base os.path.basename(onnx_path).replace(.onnx, _fixed.onnx) tmp_path f/tmp/ascend/{base} onnx.save(new_model, tmp_path) return tmp_path2.3 转换为PyTorch模型修复后的ONNX模型可以使用onnx2torch工具转换为PyTorch模型。scripts/convert_to_npu.py脚本中的load_and_convert函数实现了这一功能同时还会将模型加载到NPU设备上。def load_and_convert(onnx_path): Load ONNX, fix it, convert to PyTorch, move to NPU. _patch_bn_converter() from onnx2torch import convert fixed_path fix_onnx(onnx_path) model convert(fixed_path) model model.eval().npu() return model2.4 转换为昇腾OM模型将PyTorch模型转换为昇腾OM模型需要使用ATC工具。以下是使用ATC工具转换模型的示例命令atc --modelrec_model.onnx --framework5 --outputrec_model --input_formatNCHW --input_shapex:1,3,48,960 --loginfo --soc_versionAscend910B其中--model指定输入的ONNX模型路径--framework指定框架类型5表示ONNX--output指定输出的OM模型路径--input_shape指定输入数据的形状--soc_version指定昇腾芯片的型号。三、模型推理与性能评估3.1 加载OM模型进行推理转换后的OM模型可以使用昇腾ACLAscend Computing Language进行加载和推理。run_npu_hybrid.py脚本中的OMEngine类封装了ACL的相关操作实现了OM模型的加载和推理功能。class OMEngine: Ascend OM model wrapper for NPU inference def __init__(self, om_path, device_id0): self.device_id device_id self.om_path str(om_path) self.model_id None self._load() def _load(self): result acl.mdl.load_from_file(self.om_path) self.model_id result[0] # ... 其他初始化操作 ... def infer(self, input_data_list): Run inference on NPU # ... 推理过程实现 ... return results, elapsed3.2 性能评估为了评估转换后模型的性能可以使用scripts/convert_to_npu.py脚本中的benchmark_model函数进行基准测试。该函数会测量模型在NPU上的推理延迟并与CPU上的推理延迟进行比较。从上图可以看出转换后的OM模型在NPU上的推理速度明显快于CPU能够显著提升OCR任务的处理效率。四、实际应用示例以下是使用转换后的OM模型进行OCR推理的示例代码来自run_npu_hybrid.py脚本def main(): # ... 命令行参数解析 ... pipeline HybridPPOCR( args.det_onnx, args.rec_om, args.cls_om if (os.path.exists(args.cls_om) and not args.no_cls) else None, device_idargs.device_id ) print(f\n1. Processing: {args.image}) results, phases pipeline(args.image, threshargs.thresh) print(f\n2. Detection: {len(results)} text regions ({phases.get(det, 0)*1000:.0f} ms)) if cls in phases and phases[cls] 0: print(f Classification: {phases.get(cls, 0)*1000:.0f} ms) print(f Recognition: {phases.get(rec, 0)*1000:.0f} ms) print(f\n3. Results:) for i, (box, text, score) in enumerate(results): print(f [{i}] {text} (score: {score:.4f}))运行上述代码可以对输入图像进行OCR处理并输出识别结果。以下是一张测试图像及其识别结果识别结果[0] HAWKS (score: 0.9876)五、总结本教程详细介绍了RapidOCR模型从ONNX到昇腾OM的完整转换流程包括环境准备、模型修复、转换为PyTorch模型、转换为OM模型以及模型推理与性能评估等步骤。通过将模型转换为OM格式可以充分利用昇腾NPU的计算优势显著提升OCR任务的处理效率。如果您在模型转换过程中遇到任何问题可以参考项目中的scripts/convert_to_npu.py和run_npu_hybrid.py脚本或者查阅昇腾官方文档获取更多帮助。希望本教程能够帮助您顺利完成RapidOCR模型的转换和部署为您的OCR应用带来更高的性能和效率【免费下载链接】rapidocr项目地址: https://ai.gitcode.com/lhwLHWjackL/rapidocr创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考