Using Project Oxford's Emotion API

2019-07-20 08:41发布

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!

2条回答
地球回转人心会变
2楼-- · 2019-07-20 09:02

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))
查看更多
家丑人穷心不美
3楼-- · 2019-07-20 09:12

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

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

查看更多
登录 后发表回答