【onnx模型 双输入,模型推理测试】
import onnx,cv2
import numpy as np
import onnxruntime as ort
from pip import main
# exit()
# read images
def read_images(left_img,right_img,width=None):
left = cv2.imread(str(left_img), cv2.IMREAD_COLOR)
right = cv2.imread(str(right_img), cv2.IMREAD_COLOR)
if width is not None and width != left.shape[1]:
height = int(round(width / left.shape[1] * left.shape[0]))
left = cv2.resize(
left,
(width, height),
interpolation=cv2.INTER_CUBIC,
)
right = cv2.resize(
right,
(width, height),
interpolation=cv2.INTER_CUBIC,
)
left = left[..., [2, 1, 0]]
left = np.transpose(left, (2, 0, 1))
left = left.astype(np.float32) / 255
left = np.expand_dims(left,0)
right = right[..., [2, 1, 0]]
right = np.transpose(right, (2, 0, 1))
right = right.astype(np.float32) / 255
right = np.expand_dims(right,0)
print('left:',left.shape)
print('right:',right.shape)
return left,right
if __name__ == "__main__":
# check model
# model = onnx.load("./tinyhitnet.onnx") # 加载onnx
# onnx.checker.check_model(model) # 检查生成模型是否错误
# print(onnx.helper.printable_graph(model.graph))
left_image = './TinyHITNet-master/images/004358L.png'
right_image = './TinyHITNet-master/images/004358R.png'
ort_session = ort.InferenceSession("./TinyHITNet-master/tinyhitnet.onnx") # 创建一个推理session
x=np.random.randn(1, 3, 640, 512).astype(np.float32) # 注意输入type一定要np.float32!!!!!
y=np.random.randn(1, 3, 640, 512).astype(np.float32)
input_name1 = ort_session.get_inputs()[0].name
input_name2 = ort_session.get_inputs()[1].name
output_name = ort_session.get_outputs()[0].name
print('input_name1:',input_name1)
print('input_name2:',input_name2)
print('output_name:',output_name)
# exit()
left,right = read_images(left_image,right_image)
outputs = ort_session.run([output_name],{input_name1 : left,input_name2:right})
print(outputs)
# sess = ort.InferenceSession('./tinyhitnet.onnx')
# input_name = sess.get_inputs()[0].name
# label_name = sess.get_outputs()[0].name
# pred_onx = sess.run([label_name], {input_name:data.astype(np.float32)})[0]
# print(pred_onx)
# print(np.argmax(pred_onx))
########################################