onnx2ncnn并在pc端调用ncnn模型
1、编译安装ncnn
首先应该在电脑上编译安装ncnn,配置安装过程可以参考笔者的这篇博文Linux下编译安装NCNN
2、确保已经转换好onnx模型
pytorch转onnx模型可以参考笔者的这篇 pytorch2onnx
3、onnx2ncnn
在经过步骤1的编译后,在目录ncnn/build/tools/onnx下,有onnx2ncnn这个可执行文件,这个文件是将模型onnx转化为ncnn模型。在ncnn/build/tools/caffe文件夹下有caffe2ncnn这个可执行文件,是将caffe模型转为ncnn,在ncnn/build/tools下有一个ncnn2mem 这个文件用来将ncnn模型进行加密的。onnx转化为ncnn模型时,我们需要使用的是onnx2ncnn这个可执行文件。
例如在笔者的这个模型中,使用
./onnx2ncnn lw50.onnx lw50.param lw50.bin
4、ncnn模型说明
ncnn模型有两个文件一个.param文件,一个是.bin文件,前者是神经网络的结构,后者是神经网络的参数。下面以一个简单的神经网络结构来说明.param文件的意义。
4.1 LeNet为例
caffe模型文件内容为,关于caffe模型文件的解析可以参考笔者的这篇博文 tensorflow2caffe
name: "LeNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 1 dim: 1 dim: 28 dim: 28 } }
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 20
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 2
stride: 2
}
}
layer {
name: "conv2"
type: "Convolution"
bottom: "pool1"
top: "conv2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 50
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool2"
type: "Pooling"
bottom: "conv2"
top: "pool2"
pooling_param {
pool: MAX
kernel_size: 2
stride: 2
}
}
layer {
name: "ip1"
type: "InnerProduct"
bottom: "pool2"
top: "ip1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 500
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "relu1"
type: "ReLU"
bottom: "ip1"
top: "ip1"
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1
}