【问题标题】:pass image in request body in python在python的请求正文中传递图像
【发布时间】:2021-02-06 10:56:01
【问题描述】:

目前我正在尝试使用 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 或任何公共 URL 传递图像,而是从我的本地计算机传递图像。例如,我的本地计算机上的图像位于“/home/ubuntu/index.png”。

任何关于如何做的帮助将不胜感激。

【问题讨论】:

标签: azure rest face-detection azure-rest-api


【解决方案1】:

将 POST 请求的 Content-Type 标头设置为“application/octet-stream”,并将图像添加到 HTTP 正文中:

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

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2021-07-15
    • 2017-08-15
    相关资源
    最近更新 更多