Using Project Oxford's Emotion API

我与影子孤独终老i 提交于 2019-12-10 23:56:15

问题


I came across Project Oxford and became really interested in it and using its API, specifically the emotion one. Microsoft provides sample code

########### Python 2.7 #############
import httplib, urllib, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': 'add key',

}

params = urllib.urlencode({
    # Request parameters
    'faceRectangles': '{string}',

})

try:
    conn = httplib.HTTPSConnection('api.projectoxford.ai')
    conn.request("POST", "/emotion/v1.0/recognize&%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()

except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

This doesn't contain the request body. I thought all I need to add was

body = {
    'url': 'url here',
}

and change

   conn.request("POST", "/emotion/v1.0/recognize&%s" % params, "{body}",headers)

to

conn.request("POST", "/emotion/v1.0/recognize&%s" % params, body, headers)

However that isn't working. I am getting this when I run it

Traceback (most recent call last):
File "C:/Users/User/Desktop/python/emotion.py", line 29, in <module>
print("[Errno {0}] {1}".format(e.errno, e.strerror))
AttributeError: 'exceptions.TypeError' object has no attribute 'errno'

Any help is much appreciated!


回答1:


The following works for me (Python 2.7), also based on the sample code provided by MSDN. You don't need to specify faceRectangles (unless you want to because they've already been detected, to save compute time).

import httplib, urllib, base64  

# Image to analyse (body of the request)

body = '{\'URL\': \'https://<path to image>.jpg\'}'

# API request for Emotion Detection

headers = {
   'Content-type': 'application/json',
}

params = urllib.urlencode({
   'subscription-key': '',  # Enter EMOTION API key
   #'faceRectangles': '',
})

try:
   conn = httplib.HTTPSConnection('api.projectoxford.ai')
   conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body , headers)
   response = conn.getresponse()
   print("Send request")

   data = response.read()
   print(data)
   conn.close()
except Exception as e:
   print("[Errno {0}] {1}".format(e.errno, e.strerror))



回答2:


You need to pass str(body) to the request.

Also, make sure to not include params if you don't have any face rectangles.



来源:https://stackoverflow.com/questions/33769708/using-project-oxfords-emotion-api

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