PaddleOCR Detector 是基于 PaddleOCR 框架的文本检测模型,用于检测图像中的文本区域。该模型使用 MobileNetV3 作为骨干网络,结合 DBNet(Differentiable Binarization)检测头,能够高效准确地定位图像中的文本行位置。
OCR 文本检测 (OCR-Detection)
x — [batch_size, 3, height, width],float32 类型
fetch_name_0 — [batch_size, 1, height, width],float32 类型
该模型为 ONNX 格式,可直接使用 ONNX Runtime 进行推理。在昇腾 NPU 上,通过 ONNX Runtime 的 CANNExecutionProvider 实现硬件加速。无需修改模型结构,只需在创建 ONNX Runtime Session 时指定 providers 参数即可。
CANNExecutionProvider 作为 ONNX Runtime 执行后端# 安装依赖
pip install -r requirements.txt
# 如使用清华 PyPI 镜像加速
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txtpython3 inference.py --device cpupython3 inference.py --device npupython3 compare_cpu_npu.py测试使用一张包含中英文文本的测试图像(640x160),包含文本 "Hello OCR World 你好世界" 和 "PaddleOCR NPU Test 2024"。
检测模型输出文本概率图后,通过阈值二值化和轮廓检测提取文本框。CPU 和 NPU 检测到的文本框位置基本一致。
精度对比使用以下指标:
| 指标 | 数值 |
|---|---|
| 余弦相似度 | 0.99864234 |
| 均方误差 (MSE) | 0.00003004 |
| 二值预测一致率 (threshold=0.1) | 99.9809% |
| 二值预测一致率 (threshold=0.3) | 99.9874% |
| 二值预测一致率 (threshold=0.5) | 99.9870% |
| 高值区域 MAE (>0.3) | 0.00936384 |
| CPU 平均推理耗时 | 119.23 ms |
| NPU 平均推理耗时 | 2.60 ms |
| 加速比 (CPU/NPU) | 45.88x |
精度测试结论:NPU 与 CPU 推理误差为 0.0126%(二值预测不一致率),符合精度误差小于 1% 的要求。
| 设备 | 平均推理耗时 |
|---|---|
| CPU (ONNX Runtime) | 119.23 ms |
| NPU (Ascend910, CANN EP) | 2.60 ms |
| 加速比 | 45.88x |

import onnxruntime as ort
# CPU 推理
session_cpu = ort.InferenceSession(
'detector.onnx',
providers=['CPUExecutionProvider']
)
# NPU 推理
session_npu = ort.InferenceSession(
'detector.onnx',
providers=[('CANNExecutionProvider', {'device_id': '0'}), 'CPUExecutionProvider']
)
# 预处理
# 1. 调整图像大小(32的倍数)
# 2. 归一化 (mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225])
# 3. 转换为 NCHW 格式
# 推理
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
output = session.run([output_name], {input_name: input_tensor})
# 后处理
# 1. 二值化(threshold=0.3)
# 2. 轮廓检测提取文本框
# 3. 坐标缩放回原图尺寸# 单次推理
python3 inference.py --device npu --image_path /path/to/your/image.png
# CPU/NPU 精度对比
python3 compare_cpu_npu.py本仓库提供完整的推理脚本,支持 CPU 和 NPU 双平台推理:
# NPU 推理
python3 inference.py --device npu
# CPU 推理
python3 inference.py --device cpu推理完成后会输出推理结果和耗时,表明模型在 NPU 上推理成功。
适配该模型时,Ascend910 NPU 显存占用约 200MB,CPU 内存占用约 500MB。NPU 推理速度相比 CPU 提升约 45 倍。