引言:
目录
下载 shape_predictor_68_face_landmarks.dat 文件 --点击进入
-
下载
shape_predictor_68_face_landmarks.dat
文件 --点击进入
import cv2
import dlib
import numpy as np
# 初始化dlib的人脸检测器和特征点检测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 初始化表情识别器
# 这里假设你已经有了一个训练好的表情识别模型,例如使用SVM或神经网络
# emotion_classifier = ...
# 加载表情标签
EMOTIONS = ["anger", "disgust", "fear", "happiness", "sadness", "surprise", "neutral"]
# 实时视频流处理
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# 转为灰度图
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
rects = detector(gray, 0)
for rect in rects:
# 获取特征点
shape = predictor(gray, rect)
shape = np.array([(shape.part(i).x, shape.part(i).y) for i in range(0, 68)])
# 在图像上绘制特征点
for pt in shape:
cv2.circle(frame, pt, 2, (0, 255, 0), -1)
# 这里可以添加代码进行表情识别
# 例如:emotion = emotion_classifier.predict(shape)
# emotion_label = EMOTIONS[emotion]
# cv2.putText(frame, emotion_label, (rect.left(), rect.top() - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
cv2.imshow("Face Detection with Emotion Recognition", frame)
# 退出条件
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()