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.

38 lines
1.5KB

  1. # Exports a pytorch *.pt model to *.onnx format
  2. # Example usage (run from ./yolov5 directory):
  3. # $ export PYTHONPATH="$PWD" && python models/onnx_export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
  4. import argparse
  5. import onnx
  6. from models.common import *
  7. if __name__ == '__main__':
  8. parser = argparse.ArgumentParser()
  9. parser.add_argument('--weights', type=str, default='./weights/yolov5s.pt', help='weights path')
  10. parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
  11. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  12. opt = parser.parse_args()
  13. print(opt)
  14. # Parameters
  15. f = opt.weights.replace('.pt', '.onnx') # onnx filename
  16. img = torch.zeros((opt.batch_size, 3, opt.img_size, opt.img_size)) # image size, (1, 3, 320, 192) iDetection
  17. # Load pytorch model
  18. google_utils.attempt_download(opt.weights)
  19. model = torch.load(opt.weights)['model']
  20. model.eval()
  21. # model.fuse()
  22. # Export to onnx
  23. model.model[-1].export = True # set Detect() layer export=True
  24. torch.onnx.export(model, img, f, verbose=False, opset_version=11)
  25. # Check onnx model
  26. model = onnx.load(f) # load onnx model
  27. onnx.checker.check_model(model) # check onnx model
  28. print(onnx.helper.printable_graph(model.graph)) # print a human readable representation of the graph
  29. print('Export complete. ONNX model saved to %s\nView with https://github.com/lutzroeder/netron' % f)