前言:yolov5训练生成.pt模型后即可继续使用yolov5进行测试,但是
开发环境:yolov5-tag2+python3.8+window10
一、export.py
"""Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
Usage:
$ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
"""
import argparse
from models.common import *
from utils import google_utils
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights', type=str, default=r'G:\yolov\yolov5-2.0\runs\exp26\weights\best.pt', help='weights path')
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size')
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
opt = parser.parse_args()
opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
print(opt)
# Input
img = torch.zeros((opt.batch_size, 3, *opt.img_size)) # image size(1,3,320,192) iDetection
# Load PyTorch model
google_utils.attempt_download(opt.weights)
model = torch.load(opt.weights, map_location=torch.device('cpu'))['model'].float()
model.eval()
model.model[-1].export = True # set Detect() layer export=True
y = model(img) # dry run
# TorchScript export
try:
print('\nStarting TorchScript export with torch %s...' % torch.__version__)
f = opt.weights.replace('.pt', '.torchscript.pt') # filename
ts = torch.jit.trace(model, img)
ts.save(f)
print('TorchScript export success, saved as %s' % f)
except Exception as e:
print('TorchScript export failure: %s' % e)
# ONNX export
try:
import onnx
print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
f = opt.weights.replace('.pt', '.onnx') # filename
model.fuse() # only for ONNX
torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
output_names=['classes', 'boxes'] if y is None else ['output'])
# Checks
onnx_model = onnx.load(f) # load onnx model
onnx.checker.check_model(onnx_model) # check onnx model
print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
print('ONNX export success, saved as %s' % f)
except Exception as e:
print('ONNX export failure: %s' % e)
# CoreML export
try:
import coremltools as ct
print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
# convert model from torchscript and apply pixel scaling as per detect.py
model = ct.convert(ts, inputs=[ct.ImageType(name='images', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
f = opt.weights.replace('.pt', '.mlmodel') # filename
model.save(f)
print('CoreML export success, saved as %s' % f)
except Exception as e:
print('CoreML export failure: %s' % e)
# Finish
print('\nExport complete. Visualize with https://github.com/lutzroeder/netron.')
说明:修改下自己训练生成的weights的位置,然后将--img-size的大小设置成训练时使用的网络结构的输入大小
还有就是python环境要对,有时候环境不对会报很多错误,就是在export时环境里面没有对应的模块导致的。
?
运行成功后在 .pt的同级目录下将生成.onnx和.torchscript.pt两个个文件,网上有说三个文件的,多一个.mlmodel 文件(linux系统),笔者这里没有生成这个文件。
二、简化模型
为什么要简化?在训练完深度学习的pytorch或者tensorflow模型后,有时候需要把模型转成onnx,但是很多时候,很多节点比如cast节点,Identity 这些节点可能都不需要,我们需要进行简化,这样会方便我们把模型转成ncnn或者mnn等这些端侧部署的模型格式或者通过TensorRT进行部署。
依赖库:onnx-simplifier
导航到.onnx所在文件夹下,运行cmd命令
python -m onnxsim 原名.onnx 修改后自定义.onnx
G:\yolov\yolov5-2.0\runs\exp26\weights>python -m onnxsim best.onnx best220314_sim.onnx Simplifying... Checking 0/3... Checking 1/3... Checking 2/3... Ok!
G:\yolov\yolov5-2.0\runs\exp26\weights>
前者best.onnx是需要简化的onnx的名,后者best220314_sim.onnx是简化后模型的名字。
三、NCNN转换
3.1 下载ncnn模型并编译
编译后主要使用到onnx2ncnn进行模型转换。
3.2 ncnn转换命令
onnx2ncnn.exe best220314_sim.onnx best220314_sim.param best220314_sim.bin
最后两个参数顺序不能换,一个是.param,一个是.bin,名字可以自定义
G:\ncnn-20210525-windows-vs2019\ncnn-20210525-windows-vs2019\x64\bin>onnx2ncnn.exe best220314_sim.onnx best220314_sim.param best220314_sim.bin Unsupported slice step ! Unsupported slice step ! Unsupported slice step ! Unsupported slice step ! Unsupported slice step ! Unsupported slice step ! Unsupported slice step ! Unsupported slice step !
G:\ncnn-20210525-windows-vs2019\ncnn-20210525-windows-vs2019\x64\bin>?
四、转换和实现focus模块
?直接参考nihui大佬的博客就可以了详细记录u版YOLOv5目标检测ncnn实现 - 知乎
|