Python POST 使用 Microsoft Face API 请求错误 "image format unsupported"

Python POST request error "image format unsupported" using Microsoft Face API

我正在尝试发送二进制图像文件来测试 Microsoft Face API。使用 POSTMAN 效果很好,我按预期返回 faceId。但是,我尝试将其转换为 Python 代码,但它目前给我这个错误:

{"error": {"code": "InvalidImage", "message": "Decoding error, image format unsupported."}}

我读了这个 但它没有帮助。这是我发送请求的代码。我试图模仿 POSTMAN 正在做的事情,例如用 header application/octet-stream 标记它,但它不起作用。有什么想法吗?

url = "https://api.projectoxford.ai/face/v1.0/detect"

headers = {
  'ocp-apim-subscription-key': "<key>",
  'content-type': "application/octet-stream",
  'cache-control': "no-cache",
}

data = open('IMG_0670.jpg', 'rb')
files = {'IMG_0670.jpg': ('IMG_0670.jpg', data, 'application/octet-stream')}

response = requests.post(url, headers=headers, files=files)

print(response.text)

因此 API 端点采用字节数组,但还需要输入正文参数作为 data,而不是 files。无论如何,下面的代码对我有用。

url = "https://api.projectoxford.ai/face/v1.0/detect"

headers = {
  'ocp-apim-subscription-key': "<key>",
  'Content-Type': "application/octet-stream",
  'cache-control': "no-cache",
}

data = open('IMG_0670.jpg', 'rb').read()

response = requests.post(url, headers=headers, data=data)

print(response.text)