【问题标题】:Using Project Oxford's Emotion API使用 Project Oxford 的 Emotion API
【发布时间】:2016-04-15 03:08:44
【问题描述】:

我遇到了 Project Oxford,并对它产生了浓厚的兴趣,并使用了它的 API,尤其是情感 API。微软提供示例代码

########### 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))

这不包含请求正文。我认为我需要添加的只是

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

改变

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

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

但是这不起作用。当我运行它时我得到了这个

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'

非常感谢任何帮助!

【问题讨论】:

  • print("[Errno {0}] {1}".format(e.errno, e.strerror)) 更改为 print(e.message) 以获得正确的错误消息。
  • @sobolevn 错误信息是“unhashable type”
  • @sobolevn conn.request("POST", "/emotion/v1.0/recognize&%s" % params, body, headers) 后抛出异常

标签: python python-2.7 microsoft-cognitive


【解决方案1】:

您需要将str(body) 传递给请求。

此外,如果您没有任何面部矩形,请确保不包含 params

【讨论】:

    【解决方案2】:

    以下内容适用于我(Python 2.7),同样基于 MSDN 提供的示例代码。您不需要指定 faceRectangles(除非您想这样做,因为它们已经被检测到,以节省计算时间)。

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-22
      • 2016-06-27
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2019-10-28
      相关资源
      最近更新 更多