pt和onnx和ncnn之间的转换以及避坑

一,pt 转 onnx 其实就是深度学习模型转onnx模型这里不过多介绍

这个转化比较简单python里就可以

这个文件yolov5-5.0>models>export.py

下面那个根据自己的环境修改,环境是你yolov5运行的环境cpu就填cpu gpu就填 0 

修改好后运行

 有可能需要下载onnx包 直接pip

pip install onnx -i https://pypi.tuna.tsinghua.edu.cn/simple

直接运行就好了

 

onnx会直接在你pt模型路径下

 二,onnx转ncnn

ncnn有些特殊会生成两个文件

 然后把onnx模型用这个打开查看一下 Netron

 转化可以用这个直接转化

一键转换 Caffe, ONNX, TensorFlow 到 NCNN, MNN, Tengine (convertmodel.com)https://convertmodel.com/

选择模型,然后转换

 有可能报错

用刚刚那个应用打开onnx模型

 因为有些程序不支持切片所以需要删掉

这需要把pt到onnx重新转化才可以删掉切片内容

需要改一些东西

打开yolov5-5.0>models>common.py

#修改前
# class Focus(nn.Module):
#     # Focus wh information into c-space
#     def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
#         super(Focus, self).__init__()
#         self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
#         # self.contract = Contract(gain=2)
#
#     def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)
#         return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
#         # return self.conv(self.contract(x))
#修改后的
class Focus(nn.Module):
    # Focus wh information into c-space
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
        super(Focus, self).__init__()
        self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
        # self.contract = Contract(gain=2)

    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)
        # return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
        N, C, H, W = x.size()  # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'
        s = 2
        x = x.view(N, C, H // s, s, W // s, s)  # x(1,64,40,2,40,2)
        x = x.permute(0, 3, 5, 1, 2, 4).contiguous()  # x(1,2,2,64,40,40)
        y = x.view(N, C * s * s, H // s, W // s)  # x(1,256,40,40)
        return self.conv(y)

然后运行export.py文件转化得到新的onnx  然后把onnx模型用这个打开查看一下 Netron

一键转换 Caffe, ONNX, TensorFlow 到 NCNN, MNN, Tengine (convertmodel.com)https://convertmodel.com/

最后用这个网页上的那个转化程序进行转化就ok了 

猜你喜欢

转载自blog.csdn.net/qq_65356682/article/details/130154236