yoloV5-v3.0-model conversion, pt->onnx->ncnn

Personal WeChat public account

Insert picture description here

Version requirements

The version of yolov5 is v3.0

pytorch==1.5.0
torchvision==0.6.0

Model training

There are many tutorials on yoloV5 training on the Internet. You can Baidu by yourself. If you really don’t want to find it, you can refer to the following links.

pt to onnx

After the training is over, you can get the last.pt file, the next step is how to convert the pt file into an onnx file.

Modify common.py

note! When YOLOv5 is transferred to onnx, there is a huge pit, that is, there is a Focus mechanism in the network model, including a tensor slicing operation. This operation is not supported when transferring to ncnn, and the slicing operation of this model needs to be modified. !
The specific modification is the common.py file in the models folder. The original code is as follows:

class Focus(nn.Module):
    # Focus wh information into c-space
    def __init__(self, c1, c2, k=1):
        super(Focus, self).__init__()
        self.conv = Conv(c1 * 4, c2, k, 1)

    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)
        # return self.conv(torch.cat([x, x, x, x], 1)) 
        return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))

change into

class Focus(nn.Module):
    # Focus wh information into c-space
    def __init__(self, c1, c2, k=1):
        super(Focus, self).__init__()
        self.conv = Conv(c1 * 4, c2, k, 1)

    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)
        return self.conv(torch.cat([x, x, x, x], 1)) 
        # return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))

Conversion command

 export PYTHONPATH="$PWD" && python models/onnx_export.py --img-size 320 320

Up to this point, the pt model has been converted to the onnx model. It can be said that it has been separated from pytorch, but the conversion to ncnn requires a Simplifier operation on the model, because the transferred onnx model has a lot of redundancy, which is in ncnn It is also not supported, to avoid various errors when transferring to ncnn, just do it first!

python -m onnxsim  yolov5s.onnx yolov5s-sim.onnx

onnx to ncnn

Here directly use the conversion tool developed by the boss to directly convert

https://convertmodel.com/

Insert picture description here
If there is no error, congratulations on the success of the conversion, if not, then return to the above steps and try a few more times~~~

reference

Guess you like

Origin blog.csdn.net/zhonglongshen/article/details/115320514