使用 DeepFace 构建实时情绪检测系统

情绪识别技术在现代社会中变得越来越重要,它在人机交互、智能监控、教育评估等多个领域都有广泛应用。本文将介绍如何使用 DeepFace 库构建一个实时情绪检测系统,通过摄像头实时捕捉和分析人脸情绪。

DeepFace 简介

DeepFace 是一个轻量级的人脸识别和面部属性分析框架,支持年龄、性别、情绪和种族等多种面部属性的分析。它封装了多种最先进的模型,包括 VGG-Face、FaceNet、OpenFace、DeepFace、DeepID、ArcFace、Dlib、SFace、GhostFaceNet 和 Buffalo_L 等。

DeepFace 的主要特点包括:

  1. 高精度:集成了多种先进的人脸识别模型,准确率超过人类水平(97.53%)
  2. 多功能:不仅支持情绪识别,还支持年龄、性别、种族等面部属性分析
  3. 易于使用:提供了简洁的 API,只需几行代码即可实现复杂的人脸分析功能
  4. 灵活配置:支持多种人脸检测器和模型切换,可根据需求选择最适合的配置

环境准备

在开始之前,我们需要安装必要的依赖项。DeepFace 需要 Python 3.6 或更高版本。

1
2
3
4
5
# 安装 DeepFace 库
pip install deepface

# 或者从源码安装最新版本
pip install git+https://github.com/serengil/deepface.git

DeepFace 会自动安装所需的依赖项,包括 TensorFlow、OpenCV 等。

基础用法

让我们先从一个简单的图像情绪识别示例开始:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from deepface import DeepFace

# 分析图像中的情绪
results = DeepFace.analyze(img_path="person.jpg", actions=['emotion'])
print(results)

# 输出示例:
# [{'region': {'x': 170, 'y': 105, 'w': 200, 'h': 200},
# 'emotion': {'angry': 0.03, 'disgust': 0.01, 'fear': 0.02, 'happy': 85.21, 'sad': 0.05, 'surprise': 0.03, 'neutral': 14.65}}]

# 同时分析多种属性
results = DeepFace.analyze(img_path="person.jpg",
actions=['emotion', 'age', 'gender', 'race'])
print(results)

DeepFace 不仅可以分析情绪,还能同时分析年龄、性别和种族等多种属性,这是 FER 库不具备的功能。

实时情绪检测系统

现在让我们构建一个实时情绪检测系统,通过摄像头捕获视频流并实时分析人脸情绪。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import cv2
from deepface import DeepFace

def real_time_emotion_detection():
# 初始化摄像头
cap = cv2.VideoCapture(0)

print("实时情绪检测系统已启动,按 'q' 键退出")

while True:
# 读取摄像头帧
ret, frame = cap.read()

if not ret:
break

try:
# 检测情绪
results = DeepFace.analyze(frame, actions=['emotion'], detector_backend='opencv')

# 处理单个检测结果
if isinstance(results, dict):
results = [results]

# 在图像上绘制检测结果
for result in results:
# 获取边界框坐标
region = result["region"]
x, y, w, h = region["x"], region["y"], region["w"], region["h"]

# 获取情绪数据
emotions = result["emotion"]

# 找到置信度最高的情绪
dominant_emotion = max(emotions, key=emotions.get)
confidence = emotions[dominant_emotion]

# 绘制边界框
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

# 在边界框上方显示情绪和置信度
text = f"{dominant_emotion}: {confidence:.2f}"
cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.9, (0, 255, 0), 2)
except Exception as e:
# 如果检测不到人脸,继续下一帧
pass

# 显示结果
cv2.imshow('实时情绪检测', frame)

# 按 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# 释放资源
cap.release()
cv2.destroyAllWindows()

# 运行实时情绪检测系统
if __name__ == "__main__":
real_time_emotion_detection()

增强版情绪检测系统

为了提供更好的用户体验,我们可以创建一个增强版的情绪检测系统,它不仅显示实时情绪,还会统计一段时间内的情绪分布。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import cv2
from deepface import DeepFace
from collections import deque

class EnhancedEmotionDetector:
def __init__(self, max_history=100):
self.cap = cv2.VideoCapture(0)
self.emotion_history = deque(maxlen=max_history)
self.emotions_list = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']

def run(self):
print("增强版情绪检测系统已启动,按 'q' 键退出")

while True:
ret, frame = self.cap.read()

if not ret:
break

try:
# 检测情绪
results = DeepFace.analyze(frame, actions=['emotion'], detector_backend='opencv')

# 处理单个检测结果
if isinstance(results, dict):
results = [results]

# 处理检测结果
for result in results:
region = result["region"]
x, y, w, h = region["x"], region["y"], region["w"], region["h"]
emotions = result["emotion"]

# 找到主导情绪
dominant_emotion = max(emotions, key=emotions.get)
confidence = emotions[dominant_emotion]

# 添加到历史记录
self.emotion_history.append(dominant_emotion)

# 绘制边界框和情绪信息
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = f"{dominant_emotion}: {confidence:.2f}"
cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.9, (0, 255, 0), 2)

# 显示统计信息
if len(self.emotion_history) > 0:
self.display_statistics(frame)
except Exception as e:
# 如果检测不到人脸,继续下一帧
pass

cv2.imshow('增强版情绪检测系统', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):
break

self.cleanup()

def display_statistics(self, frame):
if len(self.emotion_history) == 0:
return

# 计算情绪分布
emotion_counts = {emotion: 0 for emotion in self.emotions_list}
for emotion in self.emotion_history:
emotion_counts[emotion] += 1

total = len(self.emotion_history)
dominant_overall = max(emotion_counts, key=emotion_counts.get)

# 在图像上显示统计信息
cv2.putText(frame, f"主导情绪:{dominant_overall}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
cv2.putText(frame, f"检测次数:{total}", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)

def cleanup(self):
self.cap.release()
cv2.destroyAllWindows()

# 运行增强版情绪检测系统
if __name__ == "__main__":
detector = EnhancedEmotionDetector()
detector.run()

视频文件情绪分析

DeepFace 提供了流式分析功能,可以直接对视频流进行实时情绪分析:

1
2
3
4
from deepface import DeepFace

# 对视频流进行实时分析
DeepFace.stream(db_path="./database", actions=['emotion'])

此外,DeepFace 还提供了更高级的功能,如人脸识别、验证等,这些都是 FER 库不具备的。

应用场景

实时情绪检测系统在多个领域都有广泛的应用前景:

1. 人机交互

通过实时识别用户的面部表情,调整应用程序的行为或提供个性化反馈。

2. 市场营销

了解顾客对商品或广告的真实反应,优化营销策略。

3. 智能驾驶

监控驾驶员的疲劳和情绪状态,提高驾驶安全性。

4. 娱乐产业

创造更具沉浸感的互动体验,根据用户表情调整游戏或影视内容。

5. 教育领域

通过分析学生的面部表情,评估教学效果,及时调整教学策略。

6. 心理健康

通过表情变化早期识别心理问题,为心理咨询提供辅助数据。

7. 安防监控

在公共场所监控系统中,通过识别异常表情进行预警。

注意事项和局限性

尽管 DeepFace 提供了便捷且高精度的情绪识别功能,但在实际应用中仍需注意以下几点:

  1. 计算资源消耗:DeepFace 集成了多种先进模型,对计算资源的要求较高,尤其是在使用复杂模型时。

  2. 光照和环境影响:在光线不足或变化剧烈的环境中,识别准确率会下降。

  3. 遮挡问题:当人脸被口罩、手等物体遮挡时,可能无法正确识别。

  4. 隐私考虑:在实际部署时需要考虑用户隐私保护问题。

  5. 模型选择:不同的模型有不同的特点,需要根据具体应用场景选择合适的模型和检测器。

总结

通过 DeepFace 库,我们可以快速构建功能强大且高精度的实时情绪检测系统。该库不仅提供了简单易用的 API,还集成了多种先进的人脸识别模型,使得开发者能够根据具体需求选择最适合的模型。

DeepFace 相比 FER 库具有明显优势:

  1. 更高的准确率:集成了多种先进模型,准确率超过人类水平
  2. 更多功能:支持情绪、年龄、性别、种族等多种属性分析
  3. 更好的灵活性:支持多种模型和检测器切换

情绪识别技术正处于快速发展阶段,随着深度学习技术的进步,未来的系统将更加准确和可靠。通过本文介绍的方法,你可以快速搭建自己的情绪检测系统,并在此基础上进行进一步的优化和扩展。


使用 DeepFace 构建实时情绪检测系统
https://bubao.github.io/posts/3c6adfa3.html
作者
一念
发布于
2025年12月7日
许可协议