在 python 中的请求正文中传递图像

pass image in request body in python

目前我正在尝试使用 Azure 提供的人脸检测 API。我目前正在使用 Rest 调用来检测图像中的人脸。 可以在此处找到更多详细信息: https://docs.microsoft.com/en-us/azure/cognitive-services/face/quickstarts/python

下面是检测图片中人脸的示例代码:

import json, os, requests
subscription_key = os.environ['FACE_SUBSCRIPTION_KEY']
assert subscription_key

face_api_url = os.environ['FACE_ENDPOINT'] + '/face/v1.0/detect'

image_url = 'https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/faces.jpg'

headers = {'Ocp-Apim-Subscription-Key': subscription_key}

params = {
'detectionModel': 'detection_02',
'returnFaceId': 'true'
}

response = requests.post(face_api_url, params=params,
                     headers=headers, json={"url": image_url})
print(json.dumps(response.json()))

现在需要的不是从 github 或任何 public URL 传递图像,而是从我的本地计算机传递图像。例如,我的本地计算机上的图像位于“/home/ubuntu/index.png”。

如能提供任何帮助,我将不胜感激。

将 POST 请求的 Content-Type header 设置为“application/octet-stream”并将图像添加到 HTTP body:

import os
import requests
import json

subscription_key = os.environ['FACE_SUBSCRIPTION_KEY']
face_api_url = os.environ['FACE_ENDPOINT'] + '/face/v1.0/detect'

headers = {'Content-Type': 'application/octet-stream', 
           'Ocp-Apim-Subscription-Key': subscription_key }

with open('/home/ubuntu/index.png', 'rb') as img:
    res = requests.post(face_api_url , headers=headers, data=img)
    res.raise_for_status()
    faces = res.json()
    print(faces)

API参考:https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236