You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.9KB

  1. """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
  2. Usage:
  3. $ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
  4. """
  5. import argparse
  6. import torch
  7. from utils.general import set_logging
  8. from utils.google_utils import attempt_download
  9. if __name__ == '__main__':
  10. parser = argparse.ArgumentParser()
  11. parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
  12. parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size')
  13. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  14. opt = parser.parse_args()
  15. opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
  16. print(opt)
  17. set_logging()
  18. # Input
  19. img = torch.zeros((opt.batch_size, 3, *opt.img_size)) # image size(1,3,320,192) iDetection
  20. # Load PyTorch model
  21. attempt_download(opt.weights)
  22. model = torch.load(opt.weights, map_location=torch.device('cpu'))['model'].float()
  23. model.eval()
  24. model.model[-1].export = True # set Detect() layer export=True
  25. y = model(img) # dry run
  26. # TorchScript export
  27. try:
  28. print('\nStarting TorchScript export with torch %s...' % torch.__version__)
  29. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  30. ts = torch.jit.trace(model, img)
  31. ts.save(f)
  32. print('TorchScript export success, saved as %s' % f)
  33. except Exception as e:
  34. print('TorchScript export failure: %s' % e)
  35. # ONNX export
  36. try:
  37. import onnx
  38. print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
  39. f = opt.weights.replace('.pt', '.onnx') # filename
  40. model.fuse() # only for ONNX
  41. torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
  42. output_names=['classes', 'boxes'] if y is None else ['output'])
  43. # Checks
  44. onnx_model = onnx.load(f) # load onnx model
  45. onnx.checker.check_model(onnx_model) # check onnx model
  46. print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
  47. print('ONNX export success, saved as %s' % f)
  48. except Exception as e:
  49. print('ONNX export failure: %s' % e)
  50. # CoreML export
  51. try:
  52. import coremltools as ct
  53. print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
  54. # convert model from torchscript and apply pixel scaling as per detect.py
  55. model = ct.convert(ts, inputs=[ct.ImageType(name='images', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
  56. f = opt.weights.replace('.pt', '.mlmodel') # filename
  57. model.save(f)
  58. print('CoreML export success, saved as %s' % f)
  59. except Exception as e:
  60. print('CoreML export failure: %s' % e)
  61. # Finish
  62. print('\nExport complete. Visualize with https://github.com/lutzroeder/netron.')