Appearance
3.2.4 花朵智能识别系统交互流程设计
1.导入库
python
import onnxruntime as ort
import numpy as np
import scipy.special
from PIL import Imageonnxruntime: ⽤于加载和运⾏ ONNX 模型numpy: ⽤于数值计算和数组操作scipy.special: 提供特殊数学函数,这⾥使⽤ softmaxPIL.Image: Python 图像处理库
2.图像预处理函数
python
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 : 输⼊的 PIL 图像对象
- resize_size=256 : 先调整到的尺⼨(默认 256×256 )
- crop_size=224 : 中⼼裁剪的尺⼨(默认 224×224 )
- mean : 各通道的均值( ImageNet 数据集)
- std : 各通道的标准差( ImageNet 数据集)
python
image = image.resize((resize_size, resize_size), Image.BILINEAR)- 将图像缩放到指定⼤⼩,使⽤双线性插值
python
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))计算中⼼位置并裁剪出指定⼤⼩的区域
python
image = np.array(image).astype(np.float32)将 PIL 图像转换为 numpy 数组并转为 float32 类型
python
image = image / 255.0将像素值从 [0,255] 归⼀化到 [0,1]
python
image = (image - mean) / std使⽤ ImageNet 的均值和标准差进⾏标准化
python
image = np.transpose(image, (2, 0, 1))将图像数据从 (H,W,C) 转置为 (C,H,W) 格式
python
image = image.reshape((1,) + image.shape)添加 batch 维度,形状变为 (1,C,H,W)
return image返回处理后的 4 维张量
3.加载模型
python
session = ort.InferenceSession('flower-detection.onnx')创建 ONNX 运⾏时会话,加载花朵检测模型
4. 加载类别标签
python
with open('labels.txt') as f:
labels = [line.strip() for line in f.readlines()]读取标签⽂件,每⾏⼀个类别名称,去除⾸尾空格
5.获取输入输出名称
python
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name获取模型输⼊和输出节点的名称
6.加载测试图像
python
image = Image.open('flower_test.png').convert('RGB')打开测试图像并确保是 RGB 格式
7.预处理图像
python
processed_image = preprocess_image(image)
processed_image = processed_image.astype(np.float32)调用预处理函数,并确保数据类型为 float32
8.模型推理
python
output = session.run([output_name], {input_name: processed_image})[0]运⾏模型,获取输出结果
9.计算类别概率
python
accuracy = scipy.special.softmax(output, axis=-1)对模型输出应用 softmax ,得到各类别概率分布
10. 解析预测结果
predicted_idx = np.argmax(accuracy[0])找到概率最大的类别索引
python
prob_percentage = accuracy[0, predicted_idx] * 100将最高概率转换为百分比形式
python
predicted_label = labels[predicted_idx]根据索引获取对应的类别名称
11.输出结果
python
print(f"Predicted class: {predicted_label}, Accuracy: {prob_percentage:.2f}%")格式化输出预测结果,保留 2 位⼩数
人机交互的最优方式
(1)用户界面设计:提供一个简洁直观的用户界面,方便用户上传图片和查看识别结果。
(2)加载模型“flower-detection.onnx”和加载类别标签“labels.txt”;
(3)加载一张本地花朵图片“flower_test.png”,并预处理图像;
(4)使用flower-detection模型对花朵图片进行识别;
(5)输出花朵的预测类型和识别的准确率。