Python+PyQt5实战:7种表情识别系统从训练到部署(附完整数据集)
最近在整理项目经验时,我翻出了几年前做的一个表情识别小工具。当时为了验证一个轻量级卷积网络在边缘设备上的可行性,从数据清洗到模型量化,再到最后打包成一个双击即用的桌面软件,踩的坑比预想的多得多。现在回头看,很多初学者在复现这类项目时,往往卡在从“模型跑通”到“应用落地”的最后一公里。这篇文章,我就以FER2013这个经典数据集为例,带你走一遍完整的工业级表情识别系统构建流程。我们不止要得到一个准确率不错的模型,更要把它变成一个普通人也能上手操作的桌面应用,过程中会重点分享那些教程里很少提及的超参数调优陷阱、数据增强的视觉化对比,以及如何用模型量化把几百兆的模型压缩到几十兆,方便分发。
如果你对深度学习有些基础,会用Python写点脚本,但对如何把一堆代码变成真正可交付的产品感到迷茫,那这篇文章就是为你准备的。我们会用到Keras(或TensorFlow)来训练模型,用OpenCV处理图像,最后用PyQt5来打造一个既美观又实用的图形界面。放心,我不止会给代码,更会解释每个决策背后的“为什么”。
1. 从“脏数据”到“干净样本”:FER2013深度清洗与增强实战
拿到FER2013数据集,很多人的第一步就是直接扔进模型开始训练。我最初也这么干,结果模型在验证集上的表现波动极大,时好时坏。后来花时间仔细分析了数据,才发现问题远比想象中复杂。FER2013包含约3.6万张48x48像素的灰度人脸图像,标注为7类表情(愤怒、厌恶、恐惧、高兴、悲伤、惊讶、中立)。但它的“脏”主要体现在两方面:一是大量图片存在严重的遮挡(如手、头发、眼镜),二是部分标签存在明显错误(比如一张明显大笑的脸被标为“愤怒”)。
直接使用原始数据,相当于让模型在噪音中学习规律,事倍功半。 我们的预处理管线必须足够鲁棒。
1.1 数据加载与异常样本排查
FER2013通常提供一个CSV文件,其中pixels列是以空格分隔的灰度值字符串。标准的加载方式如下,但我们需要加入检查环节。
import pandas as pd
import numpy as np
import cv2
from matplotlib import pyplot as plt
def load_fer2013_with_inspection(csv_path, display_samples=False):
"""
加载FER2013数据,并随机检查一些样本,直观感受数据质量。
"""
df = pd.read_csv(csv_path)
print(f"数据集大小: {len(df)}")
print(f"情绪类别分布:\n{df['emotion'].value_counts().sort_index()}")
pixels = df['pixels'].tolist()
width, height = 48, 48
faces = []
valid_indices = []
for idx, pixel_sequence in enumerate(pixels):
try:
# 转换像素字符串为数组
face = np.array([int(pixel) for pixel in pixel_sequence.split()], dtype=np.uint8)
if face.size != width * height:
print(f"警告: 索引 {idx} 的像素数量异常 ({face.size}),跳过。")
continue
face = face.reshape((height, width))
faces.append(face)
valid_indices.append(idx)
except Exception as e:
print(f"解析索引 {idx} 时出错: {e},跳过。")
continue
faces = np.array(faces, dtype=np.float32)
# 只保留有效索引对应的标签
emotions = pd.get_dummies(df.iloc[valid_indices]['emotion']).values
if display_samples:
# 随机可视化每个类别的几张图片
fig, axes = plt.subplots(2, 4, figsize=(12, 6))
axes = axes.ravel()
emotion_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
for i, label in enumerate(emotion_labels):
class_indices = np.where(df.iloc[valid_indices]['emotion'] == i)[0]
if len(class_indices) > 0:
sample_idx = np.random.choice(class_indices, 1)[0]
axes[i].imshow(faces[sample_idx], cmap='gray')
axes[i].set_title(f'{label}')
axes[i].axis('off')
axes[7].axis('off')
plt.tight_layout()
plt.show()
return faces, emotions, valid_indices
# 使用示例
faces, emotions, valid_idx = load_fer2013_with_inspection('fer2013/fer2013.csv', display_samples=True)
运行这段代码,你可能会立刻发现“厌恶”类别的样本数远少于其他类别(通常只有几百张),这是类别不平衡的典型问题。此外,可视化后能看到不少图像模糊、姿态极端或遮挡严重。
1.2 针对性的数据增强策略设计
数据增强不是为了炫技,而是为了弥补数据分布的缺陷。对于表情识别,我们需要增强的是那些光照变化、微小旋转、平移等不影响表情语义的特征,同时要避免产生误导性样本(例如,垂直翻转一张脸可能会产生奇怪的表情)。
Keras的ImageDataGenerator很方便,但默认参数可能不适合表情数据。下面是我调整后的一组参数,并附上了视觉对比,让你看清每种增强的实际效果。
from keras.preprocessing.image import ImageDataGenerator
# 创建两个数据生成器进行对比:基础增强 vs. 针对性增强
basic_datagen = ImageDataGenerator(
rotation_range=20, # 旋转范围偏大,可能导致非自然表情
width_shift_range=0.2, # 水平平移范围偏大
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True, # 水平翻转对于表情是危险的!
fill_mode='nearest'
)
advanced_datagen = ImageDataGenerator(
rotation_range=10, # 小幅旋转,模拟头部轻微倾斜
width_shift_range=0.1, # 小幅平移
height_shift_range=0.1,
shear_range=0.05, # 轻微剪切
zoom_range=0.1, # 轻微缩放
horizontal_flip=False, # 关键:禁用水平翻转!
brightness_range=[0.9, 1.1], # 微调亮度,模拟光照变化
fill_mode='constant',
cval=0 # 用黑色填充新出现的区域
)
# 可视化增强效果
sample_image = faces[0].reshape(1, 48, 48, 1)
fig, axes = plt.subplots(2, 5, figsize=(15, 6))
axes[0, 0].imshow(sample_image[0, :, :, 0], cmap='gray')
axes[0, 0].set_title('原始图像')
axes[0, 0].axis('off')
# 生成基础增强样本
basic_gen = basic_datagen.flow(sample_image, batch_size=1)
for i in range(4):
augmented = next(basic_gen)[0].astype(np.uint8)
axes[0, i+1].imshow(augmented[:, :, 0], cmap='gray')
axes[0, i+1].set_title(f'基础增强 {i+1}')
axes[0, i+1].axis('off')
axes[1, 0].imshow(sample_image[0, :, :, 0], cmap='gray')
axes[1, 0].set_title('原始图像')
axes[1, 0].axis('off')
# 生成针对性增强样本
advanced_gen = advanced_datagen.flow(sample_image, batch_size=1)
for i in range(4):
augmented = next(advanced_gen)[0].astype(np.uint8)
axes[1, i+1].imshow(augmented[:, :, 0], cmap='gray')
axes[1, i+1].set_title(f'针对性增强 {i+1}')
axes[1, i+1].axis('off')
plt.tight_layout()
plt.show()
注意:禁用
horizontal_flip是我从多次失败训练中得出的教训。一张左脸微笑的图像翻转后变成右脸微笑,虽然对人眼仍是微笑,但像素分布发生了镜像变化,对于卷积核来说,这可能会学习到与方向相关的错误特征,尤其是数据集本身可能已存在侧脸偏见时。
1.3 处理类别不平衡:不止是权重的游戏
“厌恶”类别样本少,常见的做法是给损失函数中的该类增加权重。但这只是表面功夫。更有效的方法是过采样(Oversampling) 与 SMOTE式混合增强 结合。
我们可以利用ImageDataGenerator的flow方法配合自定义的数据-标签数组,实现针对少数类的更强增强。
from sklearn.utils import resample
def balanced_data_generator(faces, emotions, batch_size=32, augmenter=None):
"""
创建一个平衡的数据生成器,对少数类进行过采样。
"""
num_classes = emotions.shape[1]
class_indices = [np.where(emotions.argmax(axis=1) == i)[0] for i in range(num_classes)]
max_class_size = max(len(indices) for indices in class_indices)
while True:
batch_faces = []
batch_emotions = []
for i in range(num_classes):
# 对每个类别,如果样本数不足,则进行过采样
sampled_indices = resample(class_indices[i],
replace=True, # 允许重复采样
n_samples=max_class_size // num_classes,
random_state=None)
# 如果提供了增强器,则对采样出的图像进行增强
if augmenter is not None:
class_faces = faces[sampled_indices]
class_emotions = emotions[sampled_indices]
# 这里简化处理:实际应对每个样本单独增强,此处为示例逻辑
aug_iter = augmenter.flow(class_faces, class_emotions, batch_size=len(sampled_indices), shuffle=False)
aug_faces, aug_emotions = next(aug_iter)
batch_faces.append(aug_faces)
batch_emotions.append(aug_emotions)
else:
batch_faces.append(faces[sampled_indices])
batch_emotions.append(emotions[sampled_indices])
# 拼接并打乱批次
batch_faces = np.vstack(batch_faces)
batch_emotions = np.vstack(batch_emotions)
shuffle_idx = np.random.permutation(len(batch_faces))
batch_faces = batch_faces[shuffle_idx]
batch_emotions = batch_emotions[shuffle_idx]
# 分批产出
for start in range(0, len(batch_faces), batch_size):
end = start + batch_size
yield batch_faces[start:end], batch_emotions[start:end]
# 使用平衡生成器
balanced_gen = balanced_data_generator(faces, emotions, batch_size=64, augmenter=advanced_datagen)
通过这样的预处理流程,我们为模型提供的“食物”质量更高、营养更均衡,为后续训练打下坚实基础。记住,高质量的数据集往往比复杂的模型结构更能提升最终性能。
2. 模型选择与超参数调优:避开那些“隐形”的坑
数据准备好了,接下来就是模型。很多教程会直接给你一个mini_XCEPTION或MobileNet的代码,让你照搬。但你知道为什么选它吗?它的计算量有多大?在你的硬件上跑一次训练要多久?超参数怎么设?这一节,我们抛开黑箱,聊聊模型背后的权衡,并分享一套我常用的渐进式超参数搜索法。
2.1 轻量级模型架构对比:不只是准确率
我们的目标是部署到桌面应用,因此模型必须在准确率和速度/体积间取得平衡。下表对比了三种适合表情识别的轻量级架构:
| 模型名称 | 参数量 (约) | 在FER2013上预期准确率 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|---|---|
| mini_XCEPTION | 0.5 - 1 百万 | 68% - 72% | 专为面部分析设计,深度可分离卷积效率高 | 对小数据集可能过拟合,需要仔细调参 | 研究、对准确率有一定要求的应用 |
| MobileNetV2 | 2 - 3 百万 | 70% - 74% | 极致的速度与体积优化,有预训练权重 | 参数量稍大,微调策略影响大 | 移动端、实时性要求高的应用 |
| 自定义浅层CNN | < 0.5 百万 | 65% - 68% | 完全可控,过拟合风险低,训练快 | 特征提取能力有限,天花板较低 | 快速原型验证、极度轻量级需求 |
对于大多数桌面应用,我推荐从mini_XCEPTION开始。它虽然不是最小的,但在表情识别这个特定任务上,其架构设计更为贴切。下面是我们实现的版本,我加入了一些调整,比如在特定层后增加了Dropout,以及使用了全局平均池化代替全连接层来减少参数。
from keras.models import Model
from keras.layers import Input, Conv2D, SeparableConv2D, BatchNormalization, Activation
from keras.layers import MaxPooling2D, GlobalAveragePooling2D, Dropout, add
from keras.regularizers import l2
def build_mini_xception(input_shape=(48, 48, 1), num_classes=7, l2_reg=1e-4, dropout_rate=0.4):
"""
构建改进版的mini_XCEPTION模型,增加了Dropout和更强的正则化。
"""
regularization = l2(l2_reg)
img_input = Input(shape=input_shape)
# --- 初始卷积块 ---
x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization, use_bias=False)(img_input)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization, use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# --- 模块 1 (带残差连接) ---
residual = Conv2D(16, (1, 1), strides=(2, 2), padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(16, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(16, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = add([x, residual])
x = Dropout(dropout_rate * 0.5)(x) # 浅层使用较低的Dropout
# --- 模块 2 ---
residual = Conv2D(32, (1, 1), strides=(2, 2), padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(32, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(32, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = add([x, residual])
x = Dropout(dropout_rate)(x)
# --- 模块 3 ---
residual = Conv2D(64, (1, 1), strides=(2, 2), padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(64, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(64, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = add([x, residual])
x = Dropout(dropout_rate)(x)
# --- 输出层 ---
x = Conv2D(num_classes, (3, 3), padding='same')(x)
x = GlobalAveragePooling2D()(x)
output = Activation('softmax', name='predictions')(x)
model = Model(img_input, output)
return model
# 实例化模型
model = build_mini_xception()
model.summary()
2.2 超参数调优:一个系统性的方法
调超参数最忌盲目。我的策略是分层调优,先确定学习率、批大小等对训练动态影响最大的参数,再调整模型本身的正则化参数。
第一步:寻找最佳学习率 使用学习率范围测试(LR Range Test)。这不是跑完整训练,而是用一个周期,让学习率从很低(如1e-6)线性增加到很大(如1),观察损失的变化。理想的学习率应在损失开始下降最快且尚未剧烈震荡的区域。
from keras.callbacks import Callback
import numpy as np
class LRFinder(Callback):
"""
简易学习率查找器。
"""
def __init__(self, start_lr=1e-6, end_lr=1, steps_per_epoch=None, epochs=1):
super().__init__()
self.start_lr = start_lr
self.end_lr = end_lr
self.total_iterations = steps_per_epoch * epochs if steps_per_epoch else 100
self.iteration = 0
self.history = {}
def on_train_begin(self, logs=None):
self.iteration = 0
self.history = {'lr': [], 'loss': []}
def on_batch_end(self, batch, logs=None):
lr = self.start_lr + (self.end_lr - self.start_lr) * (self.iteration / self.total_iterations)
keras.backend.set_value(self.model.optimizer.lr, lr)
self.history['lr'].append(lr)
self.history['loss'].append(logs.get('loss'))
self.iteration += 1
# 使用示例(需要先编译模型)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 假设我们有一个小批量数据用于测试
lr_finder = LRFinder(start_lr=1e-6, end_lr=0.1, steps_per_epoch=100, epochs=1)
model.fit(train_generator, steps_per_epoch=100, epochs=1, callbacks=[lr_finder], verbose=0)
# 绘制损失-学习率曲线
plt.plot(lr_finder.history['lr'], lr_finder.history['loss'])
plt.xscale('log')
plt.xlabel('Learning Rate')
plt.ylabel('Loss')
plt.title('LR Range Test')
plt.grid(True)
plt.show()
从图中找到损失下降最陡峭的区域,例如在3e-4附近。我们就可以将初始学习率设为3e-4。
第二步:设置回调函数(Callbacks) 这是稳定训练、防止过拟合和自动保存最佳模型的关键。
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLogger
# 模型保存路径
checkpoint_path = "models/emotion_mini_xception_best.h5"
callbacks = [
# 监控验证集损失,只保存最好的模型
ModelCheckpoint(checkpoint_path,
monitor='val_loss',
save_best_only=True,
mode='min',
verbose=1),
# 当验证损失在10个epoch内不再下降时,将学习率减半
ReduceLROnPlateau(monitor='val_loss',
factor=0.5,
patience=10,
min_lr=1e-7,
verbose=1),
# 当验证损失在25个epoch内不再下降时,提前终止训练
EarlyStopping(monitor='val_loss',
patience=25,
restore_best_weights=True,
verbose=1),
# 记录训练日志,方便后续分析
CSVLogger('training_log.csv')
]
第三步:编译与训练
使用我们找到的学习率,并选择Adam优化器。批大小(batch size)根据你的GPU内存来定,32或64是常见选择。太大的批大小可能降低模型泛化能力。
model.compile(optimizer=keras.optimizers.Adam(learning_rate=3e-4),
loss='categorical_crossentropy',
metrics=['accuracy'])
# 假设我们已经有了训练和验证数据生成器 (train_gen, val_gen)
history = model.fit(train_gen,
validation_data=val_gen,
epochs=200, # 设置一个较大的值,靠EarlyStopping来终止
callbacks=callbacks,
verbose=1)
训练过程中,密切观察训练损失和验证损失的差距。如果训练损失持续下降而验证损失早早就开始上升,那是典型的过拟合,需要回头检查数据增强是否足够,或者增加Dropout率、L2正则化强度。
3. 模型评估、分析与可解释性:你的模型真的“理解”表情吗?
训练完成后,在测试集上得到一个70%的准确率,这就算成功了吗?远远不够。对于分类任务,尤其是像表情识别这种类别间可能存在混淆(如“恐惧”和“惊讶”)的任务,我们需要更细致的分析工具。
3.1 超越准确率:混淆矩阵与分类报告
混淆矩阵能清晰展示模型在哪里犯了错。是总把“厌恶”认成“愤怒”,还是分不清“恐惧”和“悲伤”?这能指导我们后续的改进方向。
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
# 在测试集上进行预测
y_pred_probs = model.predict(test_faces)
y_pred = np.argmax(y_pred_probs, axis=1)
y_true = np.argmax(test_emotions, axis=1)
# 计算混淆矩阵
cm = confusion_matrix(y_true, y_pred)
class_names = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
# 可视化混淆矩阵
plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_names, yticklabels=class_names)
plt.ylabel('真实标签')
plt.xlabel('预测标签')
plt.title('表情识别混淆矩阵')
plt.tight_layout()
plt.show()
# 打印详细的分类报告
print(classification_report(y_true, y_pred, target_names=class_names, digits=4))
从报告中,你可能会发现“厌恶”类的f1-score极低,召回率几乎为0。这说明模型几乎没学会识别这个类别,原因就是我们之前提到的样本极度稀少。解决方案除了之前的数据过采样,还可以考虑集成学习或迁移学习,从相关任务(如人脸属性识别)中迁移特征。
3.2 可视化模型关注点:Grad-CAM
模型做出预测时,它到底在看脸的哪一部分?是眼睛、嘴巴还是眉毛?使用Grad-CAM(梯度加权类激活映射)可以生成一张热力图,直观显示输入图像中哪些区域对预测某个表情贡献最大。这不仅能增加模型的可信度,还能帮助我们诊断问题——如果模型总是根据背景或无关物体做判断,那就有大问题了。
import tensorflow as tf
from keras import backend as K
def generate_grad_cam(model, img_array, layer_name='module_3_add'):
"""
为给定图像和模型生成Grad-CAM热力图。
img_array: 预处理后的单张图像,形状 (1, 48, 48, 1)
layer_name: 要可视化的卷积层的名称
"""
# 获取模型和特定层
grad_model = tf.keras.models.Model(
inputs=[model.inputs],
outputs=[model.get_layer(layer_name).output, model.output]
)
# 计算梯度
with tf.GradientTape() as tape:
conv_outputs, predictions = grad_model(img_array)
class_idx = tf.argmax(predictions[0])
loss = predictions[:, class_idx]
# 计算梯度
grads = tape.gradient(loss, conv_outputs)
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
# 计算权重和热力图
conv_outputs = conv_outputs[0]
heatmap = tf.reduce_sum(tf.multiply(pooled_grads, conv_outputs), axis=-1)
heatmap = tf.maximum(heatmap, 0) / (tf.math.reduce_max(heatmap) + 1e-10) # 归一化
heatmap = heatmap.numpy()
# 将热力图缩放到原图大小
heatmap = cv2.resize(heatmap, (img_array.shape[2], img_array.shape[1]))
return heatmap, class_idx.numpy()
# 使用示例:对一张测试图像生成热力图
sample_img = test_faces[10:11] # 取第10张测试图
heatmap, pred_class = generate_grad_cam(model, sample_img)
# 可视化
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].imshow(sample_img[0, :, :, 0], cmap='gray')
axes[0].set_title('原始图像')
axes[0].axis('off')
axes[1].imshow(heatmap, cmap='jet')
axes[1].set_title('Grad-CAM 热力图')
axes[1].axis('off')
# 叠加显示
heatmap_rescaled = np.uint8(255 * heatmap)
heatmap_colored = cv2.applyColorMap(heatmap_rescaled, cv2.COLORMAP_JET)
superimposed = cv2.addWeighted(cv2.cvtColor(np.uint8(sample_img[0]*255), cv2.COLOR_GRAY2BGR), 0.6,
heatmap_colored, 0.4, 0)
axes[2].imshow(cv2.cvtColor(superimposed, cv2.COLOR_BGR2RGB))
axes[2].set_title(f'叠加效果 (预测: {class_names[pred_class]})')
axes[2].axis('off')
plt.tight_layout()
plt.show()
如果热力图正确地高亮了嘴角(对于“高兴”)或眉间(对于“愤怒”),说明模型学到了有意义的特征。如果热力图散乱或集中在背景上,就需要警惕了。
4. 从H5到EXE:模型量化、封装与PyQt5桌面应用开发
模型评估满意后,我们终于来到了最后一步:部署。一个保存在本地的.h5文件对用户毫无意义。我们需要一个友好的界面,让用户可以选择图片、开启摄像头,并实时看到识别结果。这一步的核心挑战在于:如何将深度学习模型无缝集成到桌面应用中,并保持足够的运行效率?
4.1 模型量化与优化:为部署“瘦身”
训练好的Keras模型通常包含32位浮点数权重,体积大且推理慢。模型量化可以将权重转换为8位整数,在几乎不损失精度的情况下,将模型体积减小至约1/4,并显著提升CPU上的推理速度。TensorFlow Lite是完成此任务的利器。
import tensorflow as tf
def convert_to_tflite_and_quantize(keras_model_path, tflite_path):
"""
将Keras模型转换为TensorFlow Lite格式,并进行动态范围量化。
"""
# 加载Keras模型
model = tf.keras.models.load_model(keras_model_path)
# 创建TFLite转换器
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# 设置优化选项:动态范围量化(兼顾精度与速度)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# 如果需要进一步减小体积,可尝试全整数量化,但可能需要代表数据集进行校准
# converter.representative_dataset = representative_data_gen
# 转换模型
tflite_model = converter.convert()
# 保存模型
with open(tflite_path, 'wb') as f:
f.write(tflite_model)
print(f"模型已量化并保存至: {tflite_path}")
original_size = os.path.getsize(keras_model_path) / (1024 * 1024)
quantized_size = os.path.getsize(tflite_path) / (1024 * 1024)
print(f"原始模型大小: {original_size:.2f} MB")
print(f"量化后大小: {quantized_size:.2f} MB")
# 执行转换
convert_to_tflite_and_quantize('models/emotion_mini_xception_best.h5', 'models/emotion_model_quantized.tflite')
量化后,我们还需要一个高效的推理函数。TFLite解释器比直接加载Keras模型更轻量。
class TFLiteEmotionClassifier:
def __init__(self, tflite_model_path):
self.interpreter = tf.lite.Interpreter(model_path=tflite_model_path)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
def predict(self, face_image):
"""
face_image: 预处理后的灰度人脸图像,形状 (48, 48),值范围 [0, 1]
"""
# 准备输入数据
input_data = face_image.astype(np.float32).reshape(1, 48, 48, 1)
self.interpreter.set_tensor(self.input_details[0]['index'], input_data)
# 运行推理
self.interpreter.invoke()
# 获取输出
output_data = self.interpreter.get_tensor(self.output_details[0]['index'])
return output_data[0] # 返回7个类别的概率分布
# 初始化分类器
classifier = TFLiteEmotionClassifier('models/emotion_model_quantized.tflite')
4.2 PyQt5界面设计:美观与实用并重
PyQt5允许我们创建专业的桌面界面。设计原则是:功能清晰、布局简洁、反馈及时。我们的主界面将包含以下区域:
- 模型加载状态显示。
- 媒体选择区(图片/视频/摄像头按钮)。
- 显示区域(用于展示图片、视频帧或摄像头画面)。
- 结果展示区(表情标签、置信度条形图)。
下面是一个核心界面的代码框架,展示了如何将OpenCV的视频流与PyQt5的界面结合起来。
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QFileDialog, QGroupBox)
from PyQt5.QtCore import QTimer, Qt, pyqtSignal, QThread
from PyQt5.QtGui import QImage, QPixmap
import cv2
import numpy as np
class VideoThread(QThread):
""" 用于独立处理摄像头视频流的线程,避免阻塞界面 """
change_pixmap_signal = pyqtSignal(np.ndarray)
def __init__(self):
super().__init__()
self._run_flag = True
self.cap = None
def run(self):
self.cap = cv2.VideoCapture(0) # 打开默认摄像头
while self._run_flag:
ret, cv_img = self.cap.read()
if ret:
self.change_pixmap_signal.emit(cv_img)
else:
break
self.cap.release()
def stop(self):
self._run_flag = False
self.wait()
class EmotionRecognitionApp(QMainWindow):
def __init__(self, classifier):
super().__init__()
self.classifier = classifier
self.video_thread = None
self.current_image = None
self.init_ui()
def init_ui(self):
self.setWindowTitle('7种表情识别系统')
self.setGeometry(100, 100, 1200, 700)
# 中央部件和主布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QHBoxLayout(central_widget)
# 左侧控制面板
control_panel = QGroupBox("控制面板")
control_layout = QVBoxLayout()
self.btn_load_image = QPushButton('加载图片')
self.btn_load_video = QPushButton('加载视频')
self.btn_camera = QPushButton('开启/关闭摄像头')
self.btn_camera.setCheckable(True)
self.label_status = QLabel('就绪')
self.label_status.setStyleSheet("border: 1px solid gray; padding: 5px;")
control_layout.addWidget(self.btn_load_image)
control_layout.addWidget(self.btn_load_video)
control_layout.addWidget(self.btn_camera)
control_layout.addStretch()
control_layout.addWidget(QLabel('状态:'))
control_layout.addWidget(self.label_status)
control_panel.setLayout(control_layout)
control_panel.setMaximumWidth(250)
# 中间图像显示区域
display_panel = QGroupBox("显示区域")
display_layout = QVBoxLayout()
self.label_image = QLabel()
self.label_image.setAlignment(Qt.AlignCenter)
self.label_image.setMinimumSize(640, 480)
self.label_image.setStyleSheet("border: 2px solid darkGray;")
display_layout.addWidget(self.label_image)
display_panel.setLayout(display_layout)
# 右侧结果面板
result_panel = QGroupBox("识别结果")
result_layout = QVBoxLayout()
self.label_emotion = QLabel('等待识别...')
self.label_emotion.setStyleSheet("font-size: 24px; font-weight: bold; color: blue;")
self.label_confidence = QLabel('')
# 这里可以添加一个自定义的条形图Widget来显示7个类别的置信度,限于篇幅省略具体实现
result_layout.addWidget(QLabel('识别表情:'))
result_layout.addWidget(self.label_emotion)
result_layout.addWidget(QLabel('置信度:'))
result_layout.addWidget(self.label_confidence)
result_layout.addStretch()
result_panel.setLayout(result_layout)
result_panel.setMaximumWidth(300)
# 将各面板加入主布局
main_layout.addWidget(control_panel)
main_layout.addWidget(display_panel, stretch=1)
main_layout.addWidget(result_panel)
# 连接信号与槽
self.btn_load_image.clicked.connect(self.load_image)
self.btn_camera.toggled.connect(self.toggle_camera)
# ... 其他连接
def load_image(self):
""" 加载图片并识别 """
file_name, _ = QFileDialog.getOpenFileName(self, "选择图片", "", "Image Files (*.png *.jpg *.jpeg *.bmp)")
if file_name:
self.label_status.setText(f"处理中: {file_name}")
cv_img = cv2.imread(file_name)
self.current_image = cv_img
self.display_image(cv_img)
# 调用人脸检测和表情识别函数
self.process_frame(cv_img)
def toggle_camera(self, checked):
""" 开启或关闭摄像头 """
if checked:
self.label_status.setText("摄像头开启中...")
self.video_thread = VideoThread()
self.video_thread.change_pixmap_signal.connect(self.update_camera_frame)
self.video_thread.start()
self.btn_camera.setText('关闭摄像头')
else:
if self.video_thread:
self.video_thread.stop()
self.video_thread = None
self.label_image.clear()
self.label_status.setText("摄像头已关闭")
self.btn_camera.setText('开启摄像头')
def update_camera_frame(self, cv_img):
""" 更新摄像头画面,并进行实时识别 """
self.display_image(cv_img)
self.process_frame(cv_img) # 对每一帧进行处理
def display_image(self, cv_img):
""" 将OpenCV图像转换为QPixmap并显示在QLabel上 """
rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
h, w, ch = rgb_image.shape
bytes_per_line = ch * w
qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
self.label_image.setPixmap(QPixmap.fromImage(qt_image).scaled(
self.label_image.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
def process_frame(self, frame):
"""
核心处理函数:检测人脸,裁剪,预处理,调用模型识别,更新结果。
这里需要集成人脸检测(如使用face_recognition或OpenCV Haar Cascade)。
"""
# 1. 人脸检测 (伪代码)
face_locations = detect_faces(frame) # 返回人脸矩形框列表
if not face_locations:
self.label_emotion.setText("未检测到人脸")
return
# 2. 对检测到的每张脸进行处理
for (top, right, bottom, left) in face_locations:
face_roi = frame[top:bottom, left:right]
# 3. 预处理:转为灰度,缩放到48x48,归一化
gray_face = cv2.cvtColor(face_roi, cv2.COLOR_BGR2GRAY)
resized_face = cv2.resize(gray_face, (48, 48))
normalized_face = resized_face.astype(np.float32) / 255.0
# 4. 表情识别
emotion_probs = self.classifier.predict(normalized_face)
predicted_class = np.argmax(emotion_probs)
confidence = emotion_probs[predicted_class]
# 5. 在图像上绘制结果
emotion_labels = ['愤怒', '厌恶', '恐惧', '高兴', '悲伤', '惊讶', '中立']
label = f"{emotion_labels[predicted_class]}: {confidence:.2f}"
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, label, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# 6. 更新UI结果(以最后一张脸为准,或显示多脸结果)
self.label_emotion.setText(emotion_labels[predicted_class])
self.label_confidence.setText(f"{confidence*100:.1f}%")
# 更新置信度条形图...
# 重新显示处理后的图像
self.display_image(frame)
def detect_faces(frame):
""" 使用OpenCV的DNN人脸检测器或Haar级联分类器 """
# 示例:使用OpenCV的DNN模块加载Caffe模型(需提前下载模型文件)
net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'res10_300x300_ssd_iter_140000.caffemodel')
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
net.setInput(blob)
detections = net.forward()
face_locations = []
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5: # 置信度阈值
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
face_locations.append((startY, endX, endY, startX)) # 转换为(top, right, bottom, left)
return face_locations
if __name__ == '__main__':
app = QApplication(sys.argv)
# 初始化分类器
classifier = TFLiteEmotionClassifier('models/emotion_model_quantized.tflite')
window = EmotionRecognitionApp(classifier)
window.show()
sys.exit(app.exec_())
这个框架提供了完整的交互逻辑。在实际开发中,你还需要处理更多细节,例如:
- 多线程:确保界面在长时间处理(如视频文件分析)时不会卡死。
- 错误处理:优雅地处理模型加载失败、文件损坏等情况。
- 用户体验:添加进度条、历史记录保存、识别结果导出等功能。
4.3 打包与分发:生成独立的可执行文件
最后一步,我们将整个项目(Python脚本、模型文件、界面资源)打包成一个.exe文件,让没有Python环境的用户也能直接运行。PyInstaller是目前最常用的工具。
首先,创建一个spec文件(或直接使用命令行)来指导打包过程。关键点在于确保TFLite模型文件等资源被正确打包进去。
# 基本打包命令
pyinstaller --onefile --windowed --name "EmotionRecognitionSystem" ^
--add-data "models/emotion_model_quantized.tflite;models" ^
--hidden-import=sklearn.utils._weight_vector ^
--hidden-import=sklearn.neighbors._typedefs ^
main.py
这条命令会创建一个单文件的EmotionRecognitionSystem.exe。--add-data参数将模型文件复制到打包后的程序所在目录的models子文件夹中。程序运行时需要通过sys._MEIPASS来访问这些打包进去的资源。
在代码中,我们需要修改模型加载路径,使其在开发环境和打包后环境中都能工作:
import sys
import os
def get_resource_path(relative_path):
""" 获取资源的绝对路径。在开发环境中和在PyInstaller打包后环境中都能工作 """
if hasattr(sys, '_MEIPASS'):
# PyInstaller创建的临时文件夹
base_path = sys._MEIPASS
else:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# 加载模型时
tflite_model_path = get_resource_path('models/emotion_model_quantized.tflite')
classifier = TFLiteEmotionClassifier(tflite_model_path)
打包过程可能会遇到各种依赖问题,特别是与OpenCV、TensorFlow Lite相关的库。通常需要多次测试和调整。一个实用的技巧是先在干净的虚拟环境中安装所有依赖,然后在该环境中使用PyInstaller。
完成打包后,你得到的就不仅仅是一堆代码,而是一个真正可以交付给用户、解决实际问题的桌面应用了。从数据准备到模型训练,再到界面开发和最终打包,这套流程覆盖了AI项目产品化的核心环节。
313



被折叠的 条评论
为什么被折叠?



