基于 DeepFace 与 OpenCV 的实时情绪分析实战
利用深度学习库 DeepFace 结合 OpenCV,我们可以快速构建一个实时情绪识别系统。这个项目不仅能捕捉摄像头画面,还能在每一帧上标注出人脸的情绪状态和置信度,同时监控运行帧率(FPS)。
环境准备
主要依赖两个核心库:
- OpenCV (
cv2):负责视频流捕获、图像处理及绘图。 - DeepFace:封装了多种面部分析模型,这里专门用于情绪识别。
此外还需要 time 和 numpy 辅助计算帧率和处理数据。
核心逻辑梳理
整个流程其实很直观:打开摄像头 -> 读取帧 -> 计算 FPS -> 调用模型分析 -> 绘制结果 -> 显示窗口。
1. 初始化与循环
首先打开默认摄像头,并设置好 FPS 计算的变量。这里用了一个滑动平均算法来平滑 FPS 数值,避免数字跳动太剧烈影响观察。
import cv2
import time
import numpy as np
from deepface import DeepFace
cap = cv2.VideoCapture(0)
prev_time = time.time()
fps = 0
alpha = 0.9 # 滑动平均权重
2. 主循环处理
进入 while True 后,每读一帧就做一次完整的工作流。
帧率计算
通过记录当前时间和上一帧时间的差值,算出瞬时 FPS,再结合历史数据做加权平均。
current_time = time.time()
delta_time = current_time - prev_time
prev_time = current_time
if delta_time > 0:
instant_fps = 1.0 / delta_time
fps = alpha * fps + (1 - alpha) * instant_fps
情绪分析与绘图
这是最关键的一步。调用 DeepFace.analyze() 时,指定只分析情绪 (actions=['emotion']),并关闭强制检测 (enforce_detection=False) 以防无人脸时报错。拿到结果后,遍历每个人脸区域,画出矩形框并在上方标注情绪名称和百分比。
try:
result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
for face in result:
x, y, w, h = face['region']['x'], face['region']['y'], face['region']['w'], face['region']['h']
emotion = face['dominant_emotion']
confidence = face['emotion'][emotion]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = f'{emotion} ({confidence:.2f}%)'
cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
except Exception as e:
print("无法检测到人脸:", e)
显示与退出
最后把 FPS 画在左上角,展示图像。监听键盘输入,按 q 键即可安全退出并释放资源。
cv2.putText(frame, f'FPS: {fps:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
cv2.imshow("Emotion Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
完整代码
将上述片段整合,就是一个可直接运行的脚本:
import cv2
import time
import numpy as np
from deepface import DeepFace
# 打开摄像头
cap = cv2.VideoCapture(0)
# FPS 计算参数
prev_time = time.time()
fps = 0
alpha = 0.9 # 滑动平均权重,数值越大,FPS 越平稳
while True:
ret, frame = cap.read()
if not ret:
break
# 计算 FPS
current_time = time.time()
delta_time = current_time - prev_time
prev_time = current_time
if delta_time > 0:
instant_fps = 1.0 / delta_time
fps = alpha * fps + (1 - alpha) * instant_fps
# 进行表情识别
try:
result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
for face in result:
x, y, w, h = face['region']['x'], face['region']['y'], face['region']['w'], face['region']['h']
emotion = face['dominant_emotion']
confidence = face['emotion'][emotion]
# 绘制人脸矩形框
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 在人脸上方显示情绪信息
text = f'{emotion} ({confidence:.2f}%)'
cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
except Exception as e:
print("无法检测到人脸:", e)
# 显示 FPS(平滑更新)
cv2.putText(frame, f'FPS: {fps:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
# 显示图像
cv2.imshow("Emotion Detection", frame)
# 退出条件
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
效果预期
程序运行后,窗口会实时显示摄像头画面。当检测到人脸时,绿色方框会框住面部,上方标注如 "happy (85.42%)" 等字样。不同情绪下会有不同的识别结果:
自然状态
开心
伤心
恐惧
惊讶
总结
这个案例展示了如何组合现有 AI 库快速构建实用应用。核心在于利用 OpenCV 处理视频流,配合 DeepFace 完成推理,最终在画面上直观反馈结果。这不仅是一个情绪识别 Demo,也为后续开发更复杂的交互系统提供了基础框架。


