MNN编译模型转换工具

编译和安装 MNN

要在不同平台上编译和安装 MNN,首先需要满足以下环境要求:

  • Microsoft Visual Studio(>=2017)
  • CMake(>=3.13)
  • PowerShell
  • Ninja(构建工具,比 nmake 更快)

可以从以下链接下载 CMake 和 Ninja:

安装 Protobuf

Protobuf 是 MNN 依赖的库,确保安装 3.0 及以上版本。

bash 复制代码
# macOS
brew install protobuf

其他平台请参考 官方安装步骤。

编译 MNN 主库
bash 复制代码
cd MNN
mkdir build
cd build
cmake -G "Ninja" -DMNN_BUILD_SHARED_LIBS=OFF -DMNN_BUILD_CONVERTER=ON -DCMAKE_BUILD_TYPE=Release -DMNN_WIN_RUNTIME_MT=ON ..
ninja

如遇到无法正常编译的问题,可以参考 此博客。

模型转换

MNN 提供了 MNNConvert 工具,可以将其他格式的模型转换为 MNN 格式。

使用示例
bash 复制代码
Usage:
  MNNConvert [OPTION...]

  -h, --help            Convert Other Model Format To MNN Model
  -v, --version         show current version
  -f, --framework arg   model type, ex: [TF,CAFFE,ONNX,TFLITE,MNN]
      --modelFile arg   tensorflow Pb or caffeModel, ex: *.pb,*caffemodel
      --prototxt arg    only used for caffe, ex: *.prototxt
      --MNNModel arg    MNN model, ex: *.mnn
      --benchmarkModel  Do NOT save big size data, such as Conv's weight,BN's
                        gamma,beta,mean and variance etc. Only used to test
                        the cost of the model
      --bizCode arg     MNN Model Flag, ex: MNN
      --debug           Enable debugging mode.
TensorFlow/ONNX/TFLite 模型转换示例
bash 复制代码
./MNNConvert -f TF/ONNX/TFLITE --modelFile XXX.pb/XXX.onnx/XXX.tflite --MNNModel XXX.XX --bizCode XXX

例如:

bash 复制代码
./MNNConvert -f TF --modelFile path/to/mobilenetv1.pb --MNNModel model.mnn --bizCode MNN
Caffe 模型转换示例
bash 复制代码
./MNNConvert -f CAFFE --modelFile XXX.caffemodel --prototxt XXX.prototxt --MNNModel XXX.XX --bizCode XXX

例如:

bash 复制代码
./MNNConvert -f CAFFE --modelFile path/to/mobilenetv1.caffemodel --prototxt path/to/mobilenetv1.prototxt --MNNModel model.mnn --bizCode MNN
查看版本号
bash 复制代码
./MNNConvert --version

MNNDump2Json

将 MNN 模型二进制文件 dump 成可读的类 JSON 格式文件,以方便对比原始模型参数。

PyTorch 模型转换

使用 PyTorch 的 onnx.export 接口转换为 ONNX 模型文件:

python 复制代码
import torch
import torchvision

dummy_input = torch.randn(10, 3, 224, 224, device='cuda')
model = torchvision.models.alexnet(pretrained=True).cuda()

input_names = ["actual_input_1"] + ["learned_%d" % i for i in range(16)]
output_names = ["output1"]

torch.onnx.export(model, dummy_input, "alexnet.onnx", verbose=True, input_names=input_names, output_names=output_names, do_constant_folding=True)

然后将 ONNX 模型文件转换为 MNN 模型:

bash 复制代码
./MNNConvert -f ONNX --modelFile alexnet.onnx --MNNModel alexnet.mnn --bizCode MNN
相关推荐
回眸&啤酒鸭5 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智5 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
AI的探索之旅5 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein5 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
LaughingZhu5 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
美狐美颜SDK开放平台5 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
wukangjupingbb5 天前
智能网联汽车安全能力框架
人工智能
龙亘川5 天前
明月照湾区,智启新赛道:从顶流文旅IP盛会看智慧文旅升级路径
人工智能·智慧城市·开源软件·数据可视化
飞猫的边缘AI5 天前
边缘AI应用:家用AI摄像头怎么做数据训练?
人工智能·边缘计算·ai算法·边缘ai