windows下pytorch模型转换为ncnn可用模型

1:首先给出几个需要下载的工具网址
(1)protobuf: https://github.com/protocolbuffers/protobuf/releases/tag/v3.7.1 (我使用的是protobuf-all-3.7.1.zip 版本)
(2)onnx-simplifier
https://github.com/daquexian/onnx-simplifier(注意不用下载,直接使用pip进行安装即可,安装指令为:pip install onnx-simplifier)
(3)ncnn
https://github.com/Tencent/ncnn
2:用cmake编译protobuf
(1)在protobuf-3.7.1目录下新建一个名为mybuild-vs2015的文件夹
(2)使用VS2015 x64本机工具命令提示符进入到解压目录
cd /d D:\onnx_android_ncnn\protobuf-all-3.7.1-test\protobuf-3.7.1\build-vs2015
(3)cmake -G"NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=%cd%/install -Dprotobuf_BUILD_TESTS=OFF -Dprotobuf_MSVC_STATIC_RUNTIME=OFF …/cmake
nmake
nmake install
编译完毕之后在install文件夹下面有4个文件夹:bin、camke、include、lib
3:编译ncnn
(1)在ncnn-master目录下新建一个名为mybuild-vs2015的文件夹
(2)使用VS2015 x64本机工具命令提示符进入到解压目录
(3)
cmake -G"NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=%cd%/install
-DProtobuf_INCLUDE_DIR=D:/onnx_android_ncnn/protobuf-all-3.7.1-test/protobuf-3.7.1/build-vs2015/install/include
-DProtobuf_LIBRARIES=D:/onnx_android_ncnn/protobuf-all-3.7.1-test/protobuf-3.7.1/build-vs2015/install/lib/libprotobuf.lib
-DProtobuf_PROTOC_EXECUTABLE=D:/onnx_android_ncnn/protobuf-all-3.7.1-test/protobuf-3.7.1/build-vs2015/install/bin/protoc.exe … 。
nmake
nmake install
4:模型转换:
(1)
输入一下代码:
import torch
import torchvision
import torch.onnx
import cv2 as cv
mean = torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32)
std = torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32)
model = torchvision.models.resnet18(pretrained=True)
x = torch.Tensor(cv.cvtColor(cv.resize(cv.imread(‘11.jpg’),(224,224)),cv.COLOR_BGR2RGB)).float()/255.0
x = (x-mean)/std
x = x.contiguous()
x = torch.Tensor.unsqueeze(x.permute([2,0,1]),dim = 0)
model.eval()
with torch.no_grad():
pre = torch.Tensor.argmax(model(x))
torch_out = torch.onnx._export(model, x, “resnet18.onnx”, export_params=True,keep_initializers_as_inputs=True)
pre1 = torch.Tensor.argmax(torch_out,1)
print(pre,pre1)
(注意:keep_initializers_as_inputs=True一定要设置为True,否则在模型简化时,会报错)
(2)模型简化
python -m onnxsim resnet18.onnx resnet18-sim.onnx
(3)获取ncnn可识别的bin文件和param文件
onnx2ncnn resnet18-sim.onnx resnet18-sim.param resnet18-sim.bin

发布了36 篇原创文章 · 获赞 1 · 访问量 6384

猜你喜欢

转载自blog.csdn.net/qq_34291583/article/details/102838598
今日推荐