Python | Dictionary Formatting with Azure Face API

最后都变了- 提交于 2021-01-29 08:35:09

问题


I have this which looks like a dictionary but isn't:

{'additional_properties': {}, 'anger': 0.001, 'contempt': 0.002, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.542, 'neutral': 0.455, 'sadness': 0.0, 'surprise': 0.0}

I tried this solution to fix it

Given:

d = {'additional_properties': {}, 'anger': 0.001, 'contempt': 0.002, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.542, 'neutral': 0.455, 'sadness': 0.0, 'surprise': 0.0}

Formater:

print(', '.join([f'{v:.0%} {k}' for k,v in d.items() if k != 'additional_properties']))

Output:

0% anger, 0% contempt, 0% disgust, 0% fear, 54% happiness, 46% neutral, 0% sadness, 0% surprise

But it does not work because the Emotion class does not have any items() method like dictionaries do

The API I am using: https://azure.microsoft.com/en-us/services/cognitive-services/face/#demo

More info on the Emotion class in the documentation: https://docs.microsoft.com/en-us/python/api/azure-cognitiveservices-vision-face/azure.cognitiveservices.vision.face.models.emotion?view=azure-python


回答1:


Regarding the issue, please refer to the following code

from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
import os
import json

endpoint = ''
key = ''
face_client = FaceClient(endpoint, CognitiveServicesCredentials(key))
single_face_image_url = 'https://azurecomcdn.azureedge.net/cvt-4c22a847f7d6cb9f6d140f4927646992a7343e54da079181e641d3aae5d130bb/images/shared/cognitive-services-demos/face-detection/detection-1-thumbnail.jpg'
single_image_name = os.path.basename(single_face_image_url)
face_attributes = ['emotion']
detected_faces = face_client.face.detect_with_url(
    url=single_face_image_url,
    detectionModel='detection_02',
    return_face_attributes=face_attributes)
if not detected_faces:
    raise Exception('No face detected from image {}'.format(single_image_name))

for face in detected_faces:
    emotionObject = face.face_attributes.emotion.as_dict()
    print(', '.join([f'{v:.0%} {k}' for k, v in emotionObject.items(
    ) if k != 'additional_properties']))



来源:https://stackoverflow.com/questions/65271003/python-dictionary-formatting-with-azure-face-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!