首先编译腾讯开源的ncnn:
https://github.com/tongxiaobin/ncnn
在tools/pytorch里最下面有个链接:
https://github.com/Tencent/ncnn/wiki/practical-pytorch-to-onnx-to-ncnn
(将pytorch转为ncnn)
1、pytorch to onnx
新建pytorch2onnx.py文件,里面内容如下:
import torch
import torchvision
import torch.onnx
# An instance of your model
model = torchvision.models.resnet18()
# An example input you would normally provide to your model's forward() method
x = torch.rand(1, 3, 224, 224)
# Export the model
torch_out = torch.onnx._export(model, x, "resnet18.onnx", export_params=True)
导出的onnx模型包含许多冗余的维度,这是不支持ncnn的,所以需要进行去掉冗余的维度。
python3 -m onnxsim resnet18.onnx resnet18-sim.onnx
2、onnx to ncnn
ncnn编译完后,在build/tools/onnx里会生成个可执行文件onnx2ncnn
onnx2ncnn resnet18-sim.onnx resnet18.param resnet18.bin
最后得到的parm和bin文件即是ncnn所需要的模型。