微软牛津计划认知API调用(Python网络编程)

参加penta-Hackathon时,摸索了下通过Python网络编程调用微软认知服务的API(以人脸情绪识别为例)

首先,需要注册微软账户并开通API并获取认知服务密钥! key.png

编程部分:

1
2
3
4
5
6
7
8
9
10
# coding: utf-8
import requests
import json

myheaders = {Content-Type': 'application/json',
'Host': 'api.projectoxford.ai',
'Ocp-Apim-Subscription-Key': '********your key here********'}
req = {'url': 'https://portalstoragewuprod2.blob.core.chinacloudapi.cn/emotion/recognition2-thumbnail.jpg'}
r = requests.post("https://api.projectoxford.ai/emotion/v1.0/recognize", json = req, headers = myheaders)
# 注意:POST报文数据段必须为json=***, 其余body, data之类均不可

我使用了requests包的API,如未安装,可使用pip安装:

pip install requests

程序运行结果如图所示:

result.png

可得到面部位置以及情绪隶属度的八维度集合。

Analysing image... https://portalstoragewuprod2.blob.core.chinacloudapi.cn/emotion/recognition2-thumbnail.jpg response: [{"faceRectangle":{"height":61,"left":50,"top":54,"width":61},"scores":{"anger":3.891969E-06,"contempt":4.409651E-05,"disgust":1.34714737E-05,"fear":0.00045348765,"happiness":0.107304245,"neutral":0.00419454137,"sadness":4.36249138E-06,"surprise":0.8879819}}] Judgement: surprise (relevance: 0.8879819 )