使用DeepFace与OpenCV显示dominant_emotion时遇TypeError求助
解决DeepFace.analyze返回列表引发的TypeError问题
问题根源
DeepFace的analyze方法在检测到多张人脸时,会返回一个包含多个人脸分析字典的列表,而非单个字典。你提供的示例是单张脸的返回结构,但实际你的图片中存在多张脸,导致predictions为列表类型,直接用字符串索引['dominant_emotion']自然触发类型错误。
修复方案
方案1:仅处理第一张脸
如果只需要分析图片中的第一张脸,直接取列表的第一个元素即可:
import cv2 from deepface import DeepFace img = cv2.imread('img.jpeg') # 取列表第一个字典元素 predictions = DeepFace.analyze(img)[0] # 后续绘制代码 faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray,1.1,4) for (x, y ,w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, predictions['dominant_emotion'], (0,50), font, 3, (0,0,255), 2, cv2.LINE_AA)
方案2:批量处理多张脸
若图片中存在多张脸,需要将分析结果与人脸检测位置一一对应,分别标注情绪:
import cv2 from deepface import DeepFace img = cv2.imread('img.jpeg') predictions = DeepFace.analyze(img) faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray,1.1,4) font = cv2.FONT_HERSHEY_SIMPLEX # 遍历每张脸的检测位置和对应分析结果 for idx, (x, y, w, h) in enumerate(faces): cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) # 取对应索引的人脸情绪 dominant_emotion = predictions[idx]['dominant_emotion'] # 将情绪标注在人脸上方 cv2.putText(img, dominant_emotion, (x, y-10), font, 1, (0,0,255), 2, cv2.LINE_AA)
排查技巧
可以先打印predictions的类型和内容,确认返回结构:
print(type(predictions)) print(predictions)
通过输出能直观判断是列表还是字典,再调整索引方式。
内容的提问来源于stack exchange,提问作者May Mammaz
相关产品推荐
相关产品推荐

