-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfer_onnx.py
51 lines (40 loc) · 1.39 KB
/
infer_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
'''
# @ Author: Ben.X
# @ E-Mail: [email protected]
# @ Create Time: 2023-03-25 19:54:09
# @ Description: onnx-python 模型预测
'''
import numpy as np
import torch
from PIL import Image
import numpy as np
import torch.nn.functional as F
import onnxruntime as ort
import torchvision.transforms as transforms
x_transform = transforms.Compose([
transforms.ToTensor(), # -> [0,1]
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
def pre_process(img):
img = x_transform(img)
inputs = torch.stack([img], dim=0)
return inputs
def predict(onnx_path, img_path):
# 1.图像预处理
img = Image.open(img_path)
img = img.resize((320,256), Image.NEAREST)
inputs = pre_process(img)
# 2.加载会话
sess = ort.InferenceSession(onnx_path,providers=['CPUExecutionProvider']) #'TensorrtExecutionProvider', 'CUDAExecutionProvider',
input_name = sess.get_inputs()[0].name
# 3.预测推理
result = sess.run([], {input_name: np.array(inputs)})
# 4.输出结果的后处理
result = np.array(result)
from process_data import gray2color
result = result.squeeze(0)
gray2color(result,save_path='ouput_imgs/infer_onnx.png')
if __name__ == '__main__':
onnx_path = r'exported_models/SegModel.onnx'
img_path = r"archive/images/0000051.jpg"
predict(onnx_path,img_path)