-
Notifications
You must be signed in to change notification settings - Fork 0
/
OverNet_to_ONNX.py
61 lines (45 loc) · 2.13 KB
/
OverNet_to_ONNX.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import json
import importlib
import argparse
import os
import torch
import torch.nn as nn
from torchvision.transforms import ToTensor
import torch.onnx
from PIL import Image
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str,default='OverNet')
parser.add_argument("--ckpt_path", type=str, default='./checkpoints/OverNet_test_x2.pth.tar')
parser.add_argument('--image', type=str, required=True, help='input image to use')
parser.add_argument('--model_out', type=str, default='OverNet.onnx')
parser.add_argument("--ONNX_dir", type=str, default='ONNX')
parser.add_argument("--group", type=int, default=4)
parser.add_argument("--scale", type=int, default=2)
parser.add_argument("--upscale", type=int, default=3)
return parser.parse_args()
def main(cfg):
module = importlib.import_module("{}".format(cfg.model))
net = module.Network(scale=cfg.scale,upscale=cfg.upscale,group=cfg.group)
print(json.dumps(vars(cfg), indent=4, sort_keys=True))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Running on device: " + str(device))
state_dict = torch.load(cfg.ckpt_path, map_location=device)
net.load_state_dict(state_dict['model_state_dict'])
print("Model is loaded...")
img = Image.open(cfg.image)
img_to_tensor = ToTensor()
input = img_to_tensor(img).view(1,-1,img.size[1], img.size[0]).to(device)
print('Input image size ---> {:d}x{:d}'.format(img.size[0], img.size[1]))
output = ['SR']
dynamic_axes= {'inputs':{0:'input' , 2:'scale', 3:'upscale'}}
print('Exporting model to ONNX...')
ONNX_dir = os.path.join(cfg.ONNX_dir,"x{}".format(cfg.scale))
os.makedirs(ONNX_dir, exist_ok=True)
file_name = os.path.join(ONNX_dir, "OverNet.onnx")
torch.onnx.export(net, (input, cfg.scale, cfg.upscale), file_name, export_params=True, opset_version=13,
input_names = ['inputs','scale','upscale'], output_names=output, dynamic_axes=dynamic_axes)
print('Model exported to {:s}'.format(cfg.model_out))
if __name__ == "__main__":
cfg = parse_args()
main(cfg)