cv2.putText(frame, f'FPS: {fps:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
cv2.imshow("Emotion Detection", frame)
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
while True:
ret, frame = cap.read()
if not ret:
break
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)
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()