Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

85 lines
3.3KB

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