Python |使用Azure Face API进行字典格式化 [英] Python | Dictionary Formatting with Azure Face API
本文介绍了Python |使用Azure Face API进行字典格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像字典的东西,但不是:
{'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}
我尝试了此解决方案以对其进行修复
给出:
d = {'additional_properties':{},'anger':0.001,'contempt':0.002,'disgust':0.0,'fear':0.0,'happiness':0.542,'neutral':0.455,悲伤":0.0,惊讶":0.0}
格式化程序:
print(','.join([f'{v:.0%} {k}'对于d.items()中的k,v,如果k!='additional_properties'])))
输出:
0%愤怒,0%蔑视,0%厌恶,0%恐惧,54%快乐,46%中立,0%悲伤,0%意外
但是它不起作用,因为Emotion类没有像字典那样的item()方法
我正在使用的API:
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
解决方案
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']))
这篇关于Python |使用Azure Face API进行字典格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文