找了好几个例子,看的一头雾水,但是推理过程的核心代码如图:能写出输出处理和输出处理就可以了
根据上述代码写onnx的推理代码:
举个栗子:
使用onnx模型对1000个种类进行分类,并输出topk的结果:
# -*-coding: utf-8 -*-
import os, sys
sys.path.append(os.getcwd())
import onnxruntime
import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image
def to_numpy(tensor):
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
class_names = ['省略1000个类别']
o_model_path="E:/project/Template_detection/pytorch_net/test_model.onnx"
arr_img_path="E:/project/Template_detection/pytorch_net/attr_pred_demo1.jpg"
# img = cv2.imread("E:/project/Template_detection/pytorch_net/attr_pred_demo1.jpg")
# img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)
"""
# scipy.misc.imread 读取的图片数据是 RGB 格式
# cv2.imread 读取的图片数据是 BGR 格式
# PIL.Image.open 读取的图片数据是RGB格式
# 注意要与pth测试时图片读入格式一致
"""
#模型图片输入的预处理,可以抄pth或者pt的图片处理
def get_img_tensor(img_path, use_cuda, get_size=False):
img = Image.open(img_path)
original_w, original_h = img.size
img_size = (224, 224) # crop image to (224, 224)
img.thumbnail(img_size, Image.ANTIALIAS)
img = img.convert('RGB')
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
transform = transforms.Compose([
# transforms.RandomResizedCrop(img_size[0]), #随机裁剪
# transforms.RandomHorizontalFlip(), #平移
transforms.ToTensor(),
normalize,
])
img_tensor = transform(img)
img_tensor = torch.unsqueeze(img_tensor, 0)
if use_cuda:
img_tensor = img_tensor.cuda()
if get_size:
return img_tensor, original_w, original_w
else:
return img_tensor
to_tensor = get_img_tensor(arr_img_path,False)
# print('to_tensor',to_tensor)
onet_session = onnxruntime.InferenceSession(o_model_path)
# compute ONNX Runtime output prediction
inputs = {onet_session.get_inputs()[0].name: to_numpy(to_tensor)}
outs = onet_session.run(None, inputs)
preds = outs[0]
# print(preds)
#print(preds.shape)
tops_type = [3, 5, 10] #输出topk的值
#np.argsort(a) 返回的是元素值从小到大排序后的索引值的数组 [::-1] 将元素倒序排列
indexes = np.argsort(preds[0])[::-1]
print('np.argsort(preds[0]):',np.argsort(preds[0]))
print('np.argsort(preds[0][::-1]):',np.argsort(preds[0])[::-1])
# print(indexes)
# print(indexes[:10])
for topk in tops_type:
idxes = indexes[:topk]
print('[ Top%d Attribute Prediction ]' % topk)
for idx in idxes:
print(class_names[idx])
通过模型推理得到的结果展示:
大自然所造成的奇迹没办法复制,就像你在那一年正好的年纪里头,当时遇见亭亭玉立的她一样,没有办法复制。——董宇辉