如何借助Azure Face API实现Python应用的人脸情绪识别?
解决Azure Face API情绪识别的问题
没问题,我来帮你搞定情绪识别的部分!你已经完成了人脸识别的核心步骤,只需要在调用人脸检测接口时明确要求返回情绪属性,就能拿到你想要的情绪数据了。
关键要点说明
Azure Face API的detect_with_url方法默认不会返回面部属性(包括情绪),你需要通过return_face_attributes参数指定要获取的属性类型,这里我们需要传入['emotion']。这样返回的每个detected_face对象里就会包含face_attributes.emotion字段,里面包含8种情绪的置信度分数(范围0-1,分数越高代表该情绪越明显)。
修改后的完整代码
import urllib.request from azure.cognitiveservices.vision.face import FaceClient from azure.cognitiveservices.vision.face.models import Emotion from msrest.authentication import CognitiveServicesCredentials # Image URL = "https://upload.wikimedia.org/wikipedia/commons/5/55/Dalailama1_20121014_4639.jpg" # API KEY = "xxx" ENDPOINT = "https://happyai.cognitiveservices.azure.com/" # Initialize FaceClient predictor = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY)) # 调用detect_with_url时指定return_face_attributes=['emotion']来获取情绪数据 detected_faces = predictor.face.detect_with_url( url=URL, return_face_attributes=['emotion'] # 关键:添加这一行获取情绪属性 ) if not detected_faces: raise Exception('No face detected from image {}'.format(URL)) # 输出检测到的人脸ID和对应的情绪数据 print('Detected faces and their emotions from', URL, ':') for idx, face in enumerate(detected_faces): print(f"\nFace {idx+1} ID: {face.face_id}") print("Emotion scores:") # 获取情绪对象 emotion = face.face_attributes.emotion # 遍历所有情绪字段并打印分数 emotions_dict = { "Anger": emotion.anger, "Contempt": emotion.contempt, "Disgust": emotion.disgust, "Fear": emotion.fear, "Happiness": emotion.happiness, "Neutral": emotion.neutral, "Sadness": emotion.sadness, "Surprise": emotion.surprise } for emotion_name, score in emotions_dict.items(): print(f"- {emotion_name}: {score:.4f}") # 如果你只需要第一张脸的情绪,可以这样获取 first_face_emotion = detected_faces[0].face_attributes.emotion print("\nFirst face's top emotion:", max(emotions_dict, key=emotions_dict.get))
代码解释
- 添加
return_face_attributes=['emotion']:这是触发情绪识别的核心参数,告诉API我们需要返回情绪数据。 - 访问
face.face_attributes.emotion:每个检测到的人脸对象都会包含这个字段,里面是各种情绪的置信度分数。 - 格式化输出:把情绪数据整理成易读的格式,你也可以根据需求只展示分数最高的情绪(比如最后一行的
max方法)。
这样运行代码后,你就能看到每个人脸对应的8种情绪的具体分数了!
内容的提问来源于stack exchange,提问作者Stanislav Jirák
相关产品推荐
相关产品推荐

