本文档记录 anyocr OCR 模型在华为昇腾 Ascend 910B NPU 上的适配、部署与验证结果。
anyocr 是基于 ONNX 格式的 OCR 工具,核心使用 ONNXRuntime 作为推理引擎。它包含三个子模型:
anyocr_det_ch_v4_lite.onnx):检测图像中的文本区域anyocr_cls_v4.onnx):判断文本方向(0°/180°)anyocr_rec_v4_server.onnx):识别文本内容该模型由 PaddleOCR 微调训练后导出为 ONNX 格式,覆盖中文、英文、数字、符号等多种场景。
适配要点:
相关获取地址:
| 组件 | 版本 |
|---|---|
| CANN | 8.5.1 |
| onnxruntime | 1.26.0 |
| onnxruntime-cann | 1.24.4 |
| torch | 2.9.0 |
| torch-npu | 2.9.0.post1 |
| Python | 3.11.14 |
| NPU | Ascend 910B(1 卡,64GB HBM) |
| 操作系统 | Linux 5.10.0 aarch64 |
| 属性 | 说明 |
|---|---|
| 模型名称 | anyocr |
| 任务类型 | OCR (光学字符识别) |
| 模型框架 | ONNX (ONNXRuntime) |
| 输入格式 | 图像 (RGB) |
| 输出格式 | 文本 + 边界框坐标 + 置信度 |
| 子模型 | 检测 (det) + 方向分类 (cls) + 识别 (rec) |
| 模型大小 | ~185 MB (三个 ONNX 模型合计) |
# 安装依赖
pip install onnxruntime onnxruntime-cann numpy opencv-python-headless pyclipper Shapely PyYAML Pillow pydantic
# 确认 NPU 环境
npu-smi info
python -c "import onnxruntime; print(onnxruntime.get_available_providers())"from modelscope import snapshot_download
model_dir = snapshot_download('anyforge/anyocr')CPU 推理:
python inference.py --image test_ocr_image.png --device cpuNPU 推理:
python inference.py --image test_ocr_image.png --device npuimport sys
sys.path.insert(0, '.')
from anyocr.pipeline import anyocr, anyocrConfig
# 配置模型路径
config = anyocrConfig(
det_model_path='models/anyocr_det_ch_v4_lite.onnx',
rec_model_path='models/anyocr_rec_v4_server.onnx',
cls_model_path='models/anyocr_cls_v4.onnx',
rec_keys_path='models/anyocr_keys_v4.txt',
# CPU 推理
det_use_cann=False,
cls_use_cann=False,
rec_use_cann=False,
# NPU 推理 (CANN)
# det_use_cann=True,
# cls_use_cann=True,
# rec_use_cann=True,
).model_dump()
# 初始化模型
model = anyocr(config)
# 执行 OCR
result, elapse = model.raw_completions('test_image.png')
print(result)使用同一张测试图片分别在 CPU 和 NPU 上运行 OCR 推理,对比:
| 指标 | CPU | NPU | 差异 |
|---|---|---|---|
| 检测文本块数 | 5 | 5 | 0 |
| 文本相似度 | - | - | 100.00% |
| 平均置信度 | 0.8509 | 0.8514 | 0.05% |
| 推理耗时 | 2.140s | 0.462s | 加速 ~4.6x |
| # | CPU 文本 | NPU 文本 | CPU 置信度 | NPU 置信度 |
|---|---|---|---|---|
| 0 | HelloWorldOCRTest | HelloWorldOCRTest | 0.9981 | 0.9981 |
| 1 | 09999990 | 09999990 | 0.7647 | 0.7667 |
| 2 | 099999990 | 099999990 | 0.6788 | 0.6810 |
| 3 | 00000000123 | 00000000123 | 0.8208 | 0.8189 |
| 4 | ABCDEFG abcdefg123456 | ABCDEFG abcdefg123456 | 0.9921 | 0.9922 |
精度测试结论:NPU 与 CPU 推理结果误差为 0.05%,文本完全一致,精度符合误差小于 1% 的要求。
| 设备 | 推理耗时 |
|---|---|
| CPU | 2.140s |
| NPU (预热后) | 0.462s |
NPU 相比 CPU 推理加速约 4.6 倍。
注意:NPU 首次推理包含 CANN session 初始化开销(约 74s),预热后稳定在 0.46s 左右。

inference.py — 推理脚本(支持 CPU/NPU)compare_cpu_npu.py — CPU/NPU 精度对比脚本requirements.txt — 依赖清单README.md — 本文档accuracy_report.log — 精度测试日志terminal_screenshot.png — 推理运行截图anyocr/ — anyocr Python 包(含修改后的 CANN 支持)本仓库提供完整的推理脚本,支持 CPU 和 NPU 双平台推理:
# NPU 推理
python3 inference.py --device npu
# CPU 推理
python3 inference.py --device cpu推理完成后会输出推理结果和耗时,表明模型在 NPU 上推理成功。