from fer import FER
import cv2
from PIL import ImageFont, ImageDraw, Image
import numpy as np
# 创建情感分析器
detector = FER()
# 加载中文字体
font_path = "./font/Aillbaba/Alibaba_PuHuiTi_2.0_55_Regular_55_Regular.ttf" # 替换为您的中文字体文件路径
font = ImageFont.truetype(font_path, 30)
# 英文到中文的情感标签映射
emotion_map = {'angry': '愤怒','disgust': '厌恶','fear': '恐惧','happy': '高兴','sad': '悲伤','surprise': '惊讶','neutral': '中性'}
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# 获取情感分析结果
result = detector.top_emotion(frame)
# 显示结果
if result and result[1] is not None:
emotion, score = result
emotion_chinese = emotion_map.get(emotion, "未知情感")
# 将 OpenCV 图像转换为 PIL 图像
pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(pil_image)
# 在 PIL 图像上绘制中文文本
text = f"{emotion_chinese}: {score:.2f}"
draw.text((50, 50), text, font=font, fill=(255, 0, 0))
# 将 PIL 图像转换回 OpenCV 图像
frame = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
# 显示当前帧
cv2.imshow("Emotion Recognition", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()