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.

export.py 2.8KB

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