Skip to content

3.2.3 面部表情识别系统交互流程设计

1.导入库

python
import numpy as np
from PIL import Image
import onnxruntime as ort
  • numpy : ⽤于数值计算和数组操作
  • PIL.Image : Python 图像处理库,⽤于加载和处理图像
  • onnxruntime : ⽤于加载和运⾏ ONNX 模型

2.图像预处理函数

python
def preprocess(image_path):

定义预处理函数,参数:image_path : 图像⽂件路径

python
	input_shape = (1, 1, 64, 64)

定义模型期望的输入形状:

  • 1 : batch size ( ⼀次处理⼀张图像 )
  • 1 : 通道数 ( 灰度图像 )
  • 64 : ⾼度
  • 64 : 宽度
python
	img = Image.open(image_path).convert('L')
  • 打开指定路径的图像⽂件
  • .convert('L') 将图像转换为灰度图(单通道)
python
	img = img.resize((64, 64), Image.ANTIALIAS)
  • 调整图像⼤⼩为 64×64 像素
  • Image.ANTIALIAS : 使⽤⾼质量的重采样滤波器
python
	img_data = np.array(img, dtype=np.float32)
  • 将 PIL 图像转换为 numpy 数组
  • 指定数据类型为 float32 (模型要求的输入类型)
python
	img_data = np.expand_dims(img_data, axis=0)  # 添加 batch 维度
	img_data = np.expand_dims(img_data, axis=1)  # 添加 channel 维度
  • 第⼀次扩展添加 batch 维度 ( 从 (64,64) 变为 (1,64,64))
  • 第⼆次扩展添加通道维度 ( 从 (1,64,64) 变为 (1,1,64,64))
python
	assert img_data.shape == input_shape, f"Expected shape {input_shape}, but got 
{img_data.shape}"
  • 验证最终形状是否与模型期望的输入形状⼀致
  • 如果不⼀致,抛出错误信息
python
	return img_data

返回处理后的图像数据,形状为 (1,1,64,64)

3.情感类别映射表

python
emotion_table = {'neutral':0, 'happiness':1, 'surprise':2, 'sadness':3, 'anger':4, 
'disgust':5, 'fear':6, 'contempt':7}

创建情感标签与数字索引的映射字典:

  • 键:情感名称(字符串)
  • 值:对应的类别索引(整数)

4.加载模型

python
ort_session = ort.InferenceSession('emotion-ferplus.onnx')
  • 创建 ONNX 运⾏时会话
  • 加载名为 'emotion-ferplus.onnx' 的情感识别模型

5. 加载并预处理图像

python
input_data = preprocess('img_test.png')
  • 调⽤预处理函数处理 'img_test.png' 图像
  • 返回符合模型输入要求的图像数据

6.准备模型输入

python
ort_inputs = {ort_session.get_inputs()[0].name: input_data}
  • 获取模型输入节点的名称
  • 创建输入字典: { 输入节点名称 : 处理后的图像数据 }

7.运⾏模型推理

python
ort_outs = ort_session.run(None, ort_inputs)
  • 执⾏模型推理
  • None : 表⽰返回所有输出
  • ort_inputs : 输入数据字典
  • 返回包含模型输出的列表

8.解析预测结果

python
predicted_label = np.argmax(ort_outs[0])
  • ort_outs[0] : 获取第⼀个输出(通常是分类概率)
  • np.argmax() : 找到概率最⼤的类别索引

9.获取情感名称

python
predicted_emotion = list(emotion_table.keys())[predicted_label]
  • 将情感映射表的键(情感名称)转换为列表
  • 使⽤预测的索引获取对应的情感名称

10.输出预测结果

print(f"Predicted emotion: {predicted_emotion}")

打印预测的情感名称

人机交互的最优方式

(1)加载模型“emotion-ferplus.onnx”和加载情感类别与数字标签的映射表;

(2)加载一张本地图片“img_test.png”,并预处理图像;

(3)使用已训练的模型对图片面部表情识别;

(4)输出识别后的表情标签。

(6)用户界面设计:提供一个简洁直观的用户界面,方便用户上传图片和查看识别结果。