本项目将使用 计算机视觉 + CNN 模型来识别人脸表情,例如:
开心 | 生气 | 悲伤 | 惊讶 | 厌恶 | 害怕 | 中性
实时摄像头捕捉人脸
分析面部表情
显示识别结果(文字/emoji)
Python
OpenCV(人脸检测)
TensorFlow / Keras(表情分类)
预训练模型或 FER2013 数据集(表情识别)
bash
pip install opencv-python tensorflow keras numpy
你可以选择两种方式:
✔️ 使用预训练模型(推荐)
用一个训练好的模型,比如:
FER2013 数据集 + CNN 模型
预训练 .h5 模型权重文件
✔️ 自己训练模型(需要时间)
python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(48, 48, 1)),
MaxPooling2D(2, 2),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(2, 2),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.3),
Dense(7, activation='softmax') # 7 个表情类别
])
python
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
def detect_faces(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
return faces, gray
python
import numpy as np
emotion_labels = [' 中性', ' 开心', ' 悲伤', ' 生气', ' 惊讶', ' 害怕', ' 厌恶']
def predict_emotion(face_img, model):
resized = cv2.resize(face_img, (48, 48))
resized = resized / 255.0
resized = resized.reshape(1, 48, 48, 1)
prediction = model.predict(resized)
return emotion_labels[np.argmax(prediction)]
python
model = ... # 加载你训练好或下载的模型
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
faces, gray = detect_faces(frame)
for (x, y, w, h) in faces:
face_img = gray[y:y+h, x:x+w]
emotion = predict_emotion(face_img, model)
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.putText(frame, emotion, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2)
cv2.imshow('表情识别', frame)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
把 emoji 加入窗口,增强可视化
做表情日记记录:统计当天的情绪趋势
加上语音反馈:识别表情并说出来
接入心理分析 API(例如聊天情绪建议)