栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

onnx模型测试代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/618400.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号