3.2.1
conda env listconda activate ai
jupyter notebook
import onnxruntime as ort模型
import numpy as np
import scipy.special科学计算
from PIL import Image图片
# 预处理图像
def preprocess_image(image, resize_size=256, crop_size=224, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
image = image.resize((resize_size, resize_size), Image.BILINEAR)
w, h = image.size
left = (w - crop_size) / 2
top = (h - crop_size) / 2
image = image.crop((left, top, left + crop_size, top + crop_size))
image = np.array(image).astype(np.float32)
image = image / 255.0
image = (image - mean) / std
image = np.transpose(image, (2, 0, 1))
image = image.reshape((1,) + image.shape)
return image
# 模型 加载 2分
session = _________________._________________('resnet.onnx')
---
session = ort.InferenSession('resnet.onnx')
代码解释:
resnet.onnx模型,
InferenSession
# 加载图片 2分
image = _________________._________________('img_test.jpg').convert('RGB')
---
image = Image.open('img_test.jpg').convert('RGB')
代码解释:
# 预处理图片 2分
# 加载图片 2分
image = Image.open('img_test.jpg').convert('RGB')
processed_image = _________________(_________________)
---
processed_image = preprocess_image(image)
代码解释:
# 获取模型输入和输出的名称
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
# 进行图片识别 2分
output = _________________._________________([output_name], {input_name: processed_image})[0]
---
output = session.run([output_name], {input_name: processed_image})[0]
代码解释:
run运行,运行就是识别
# 应用 softmax 函数获取概率 2分
probabilities = _________________._________________.softmax(output, axis=-1)
---
probabilities = scipy.special.softmax(output, axis=-1)
代码解释:
# 获取最高的5个概率和对应的类别索引 2分
top5_idx = np._________________(probabilities[0])[-5:][::-1]
top5_prob = _________________[0][top5_idx]
---
top5_idx = np.argsort(probabilities[0])[-5:][::-1]
top5_prob = probabilities[0][top5_idx]
代码解释: