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.

onnx_export.py 1.5KB

4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536
  1. # Exports a pytorch *.pt model to *.onnx format. Example usage:
  2. # $ export PYTHONPATH="$PWD"
  3. # $ 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', default='./weights/yolov5s.pt', help='model path RELATIVE to ./models/')
  10. parser.add_argument('--img-size', default=640, help='inference size (pixels)')
  11. parser.add_argument('--batch-size', default=1, help='batch size')
  12. opt = parser.parse_args()
  13. # Parameters
  14. f = opt.weights.replace('.pt', '.onnx') # onnx filename
  15. img = torch.zeros((opt.batch_size, 3, opt.img_size, opt.img_size)) # image size, (1, 3, 320, 192) iDetection
  16. # Load pytorch model
  17. google_utils.attempt_download(opt.weights)
  18. model = torch.load(opt.weights)['model']
  19. model.eval()
  20. # model.fuse() # optionally fuse Conv2d + BatchNorm2d layers TODO
  21. # Export to onnx
  22. model.model[-1].export = True # set Detect() layer export=True
  23. torch.onnx.export(model, img, f, verbose=False, opset_version=11)
  24. # Check onnx model
  25. model = onnx.load(f) # load onnx model
  26. onnx.checker.check_model(model) # check onnx model
  27. print(onnx.helper.printable_graph(model.graph)) # print a human readable representation of the graph
  28. print('Export complete. ONNX model saved to %s\nView with https://github.com/lutzroeder/netron' % f)