基于 onnx-community/modnet-webnn 模型在华为昇腾 NPU (Ascend 910) 上的适配部署。
MODNet(无三分图实时人像抠图)是一种无需三分图(trimap)的实时人像抠图模型。本仓库提供了 MODNet 在华为昇腾 NPU (Ascend 910) 上的完整适配方案:
MODNet Architecture:
┌──────────────────────────────────────────────┐
│ Input: RGB Image [1, 3, 256, 256] │
├──────────────────────────────────────────────┤
│ MobileNetV2 Encoder (Backbone) │
│ ├─ s0: 1/2 scale, 16ch │
│ ├─ s1: 1/4 scale, 24ch │
│ ├─ s2: 1/8 scale, 32ch │
│ ├─ s3: 1/16 scale, 64ch │
│ ├─ s4: 1/16 scale, 96ch │
│ ├─ s5: 1/32 scale, 160ch │
│ └─ s6: 1/32 scale, 320ch │
├──────────────────────────────────────────────┤
│ LR Branch (Semantic) HR Branch (Detail) │
│ ├─ conv_lr16x (1/32) ├─ tohr_enc2x │
│ ├─ conv_lr8x (1/16) ├─ tohr_enc4x │
│ └─ upsample → 1/8 ├─ conv_enc2x │
│ ├─ conv_enc4x │
│ └─ conv_hr (refine)│
├──────────────────────────────────────────────┤
│ Fusion Branch │
│ ├─ conv_f (3x3) │
│ ├─ conv_f2x, conv_lr4x (multi-scale) │
│ └─ conv 1x1 → Sigmoid │
├──────────────────────────────────────────────┤
│ Output: Alpha Matte [1, 1, 256, 256] │
└──────────────────────────────────────────────┘modnet_npu/
├── README.md # 本文件 - 部署文档与模型卡片
├── inference.py # 推理脚本(多后端支持)
├── run_npu_inference.py # NPU 适配与评测一站式脚本
├── modnet_model.py # MODNet PyTorch 模型定义
├── modnet_arch.py # MODNet 架构分析
├── convert_onnx_to_torch.py # ONNX → PyTorch 转换器
├── weight_extractor.py # ONNX 权重提取工具
├── output/
│ ├── test_input.png # 测试输入图像
│ ├── matte_ort_cpu.png # ORT CPU 基准输出 (Alpha Matte)
│ ├── matte_npu.png # Ascend NPU 推理输出
│ └── evaluation_report.json # 评测报告 (JSON)
└── models/ # (可选) 缓存的 ONNX 模型| 组件 | 版本 |
|---|---|
| Python | 3.11+ |
| PyTorch | 2.9.0 |
| torch_npu | 2.9.0.post1 |
| CANN | 8.5.1 |
| ONNX Runtime | 1.26.0 |
| OpenCV | 4.11+ |
| Ascend NPU | 910 (2x) |
# 使用清华镜像安装(离线环境跳过)
pip install onnx onnxruntime opencv-python-headless Pillow numpy \
-i https://pypi.tuna.tsinghua.edu.cn/simple
# 下载模型(需要 ModelScope)
pip install modelscope
modelscope download --model onnx-community/modnet-webnnpython3 run_npu_inference.py自动完成:ORT CPU 基准推理 → ONNX→PyTorch 转换 → NPU 推理 → 精度对比 → 性能基准测试。
import numpy as np
from PIL import Image
from run_npu_inference import build_torch_model_from_onnx, preprocess, postprocess
# 加载模型
model = build_torch_model_from_onnx("path/to/model.onnx")
model.eval()
# 移动到 NPU
import torch
model = model.to(torch.device("npu:0"))
# 推理
input_data, orig_size = preprocess("input.jpg")
input_tensor = torch.from_numpy(input_data).to("npu:0")
with torch.no_grad():
output = model(input_tensor)
# 后处理
matte = postprocess(output.cpu().numpy(), orig_size)
# 保存结果
import cv2
cv2.imwrite("output_matte.png", matte)测试环境:Ascend 910 NPU ×2, CANN 8.5.1, PyTorch 2.9.0
| 指标 | ONNX Runtime CPU | Ascend NPU | 加速比 |
|---|---|---|---|
| 平均延迟 | 139.59 ms | 32.85 ms | 4.25× |
| 中位数延迟 | 107.13 ms | 31.93 ms | 3.36× |
| 吞吐量 | 7.16 FPS | 30.44 FPS | 4.25× |
| NPU 显存占用 | - | 26 MB | - |
注: 输入尺寸为 256×256。实际应用中可在保持宽高比的前提下调整至任意尺寸。
ORT CPU: ████████████████████████████████ 139.6ms
Ascend NPU: ████████ 32.8ms
0 50ms 100ms 150ms
|---------|----------|-----------|
| 指标 | 数值 | 通过标准 | 结果 |
|---|---|---|---|
| MAE (平均绝对误差) | 0.004857 | < 0.01 (1%) | ✅ 通过 |
| MSE (均方误差) | 0.002740 | - | - |
| PSNR (峰值信噪比) | 25.62 dB | - | - |
| Max Error (最大误差) | 0.9412 | - | - |
| 像素误差 < 1.0% | 97.82% | - | - |
| 像素误差 < 0.5% | 97.35% | - | - |
运行 python3 run_npu_inference.py 后,可在 output/ 目录查看:
test_input.png - 合成测试图像(含圆形和椭圆,模拟人像)matte_ort_cpu.png - ONNX Runtime CPU 基准输出 (Alpha Matte)matte_npu.png - Ascend NPU 推理输出evaluation_report.json - 完整评测数据 (JSON 格式)# 快速验证两个输出的一致性
python3 -c "
import numpy as np, cv2
a = cv2.imread('output/matte_ort_cpu.png', 0).astype(np.float32)/255
b = cv2.imread('output/matte_npu.png', 0).astype(np.float32)/255
mae = np.mean(np.abs(a - b))
print(f'MAE: {mae:.6f} ({"PASS" if mae < 0.01 else \"FAIL\"})')
"[1] ModelScope下载 modelscope download --model onnx-community/modnet-webnn
│
[2] ONNX 模型分析 解析 ONNX 图结构, 提取权重与架构信息
│
[3] PyTorch 模型构建 基于 ONNX 权重搭建 PyTorch nn.Module
│
[4] NPU 推理适配 设备感知张量创建, NPU 兼容算子替换
│ - InstanceNorm → 手动实现 (mean/var)
│ - 所有张量创建指定 device=npu
│
[5] 精度验证 NPU vs ORT CPU, MAE < 1% ✓
│
[6] 性能基准 延迟/吞吐量测试, 4.25× speedup ✓onnx.load + numpy_helper.to_array)提取全部 215 个权重张量InstanceNormalization 替换为手动实现((x - mean) / sqrt(var + eps))device 参数.to(device) 时权重正确迁移| 属性 | 值 |
|---|---|
| 模型名称 | MODNet (Portrait Matting) |
| 模型来源 | onnx-community/modnet-webnn (ModelScope) |
| 任务类型 | 图像分割 / 人像抠图 |
| 输入规格 | RGB 图像, [1, 3, H, W], 已归一化(mean=0.5, std=0.5) |
| 输出规格 | 阿尔法蒙版, [1, 1, H, W], 范围 [0, 1] |
| 骨干网络 | MobileNetV2(69 个卷积层) |
| 参数量 | ~6.6M |
| 输入分辨率 | 256 × 256(支持任意尺寸) |
| 适配硬件 | 昇腾 NPU 910 |
| 适配框架 | PyTorch 2.9.0 + torch_npu 2.9.0 |
| CANN 版本 | 8.5.1 |
| 推理延迟 (NPU) | 32.85 ms(256×256) |
| 推理吞吐 (NPU) | 30.44 FPS |
| 加速比 (vs CPU) | 4.25× |
| 精度 (MAE) | 0.00486(< 1%) |
| 软件许可 | Apache-2.0 |
tags:
- vision # 视觉任务
- background-removal # 背景移除
- portrait-matting # 人像抠图
- ascend # 昇腾
- npu # NPU 硬件
- torch_npu # NPU 框架
- image-segmentation # 图像分割
- CANN # 异构计算架构
- Ascend910 # NPU 型号
- Huawei # 华为
- Hardware#NPU # 硬件标签
- Task#ImageMatting # 任务标签
- Framework#PyTorch # 框架标签
- Backend#Ascend-NPU # 后端标签@inproceedings{ke2021modnet,
title={Is a Green Screen Really Necessary for Real-Time Portrait Matting?},
author={Ke, Zhanghan and Sun, Jiayu and Li, Kaican and Yan, Qiong and Lau, Rynson W.H.},
booktitle={Proc. IEEE Conf. on Computer Vision and Pattern Recognition (CVPR)},
year={2021}
}
@misc{modnet-npu-adaptation,
title={MODNet Portrait Matting - Ascend NPU Adaptation},
author={Model Agent},
year={2026},
howpublished={https://modelscope.cn/models/onnx-community/modnet-webnn},
note={Adapted for Huawei Ascend NPU 910 with torch_npu. MAE=0.00486, 4.25× speedup vs CPU.}
}由昇腾NPU适配模型代理生成 | 2026-05-20