onnx模型测试代码

import io
import torch
import torch.onnx
from model import resnet34
import onnx
import onnxruntime
import numpy as np
from PIL import Image
from torchvision import transforms,datasets 
import os


class_names = ['empty-run', 'have','empty-stop'] #这个顺序很重要,要和训练时候的类名顺序一致
 
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
img_path = 'data/1/1-0086.jpg'

##载入模型并读取权重

os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES'] = '1' 
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

def softmax(x):
    x = x.reshape(-1)
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=0)

def postprocess(result):
    return softmax(np.array(result)).tolist()


tf = transforms.Compose([
    transforms.Resize([224,224]), #先放大再旋转后裁剪
    transforms.ToTensor(),
    transforms.Normalize(mean = [0.485,0.456,0.406], std = [0.229,0.224,0.225])
])


image = Image.open(img_path).convert('RGB')

# w, h = image.size
# scale = 224./max(w, h)
# img = image.resize([int(x) for x in [w*scale, h*scale]])
# img_size = img.size
# isize = 224
# imgx= Image.new('RGB', (isize,isize))
# imgx.paste(img,((isize - img_size[0]) // 2,
#                                     (isize - img_size[1]) //2 ))
# image = imgx


img_ = tf(image)#拓展维度
img_.unsqueeze_(0)


session = onnxruntime.InferenceSession("resnet18.onnx")
# input = {session.get_inputs()[0].name: to_numpy(img_)}
# output = session.run(None, input)
output = np.array(session.run(None, { "input": to_numpy(img_)}))
print(output)


res = postprocess(output)#后处理 softmax
idx = np.argmax(res)
result=class_names[idx]
print(result)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值