Azure Detect面向API,如何将URL图片更改为本地图片?

时间:2018-06-04 01:53:04

标签: python azure face-detection microsoft-cognitive

我使用azure Detect faces API 但我发现image_url是一张网络图片。 现在我想使用我的本地图片,如何将URL图片更改为本地图片?

代码:

import requests
import matplotlib.pyplot as plt
from PIL import Image
from matplotlib import patches
from io import BytesIO
subscription_key = "XXX"
assert subscription_key
face_api_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect'
image_url = 'https://how-old.net/Images/faces2/main007.jpg'
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
    'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}
response = requests.post(
    face_api_url, params=params, headers=headers, json={"url": image_url})
faces = response.json()
print(faces)
response = requests.get(image_url)
image = Image.open(BytesIO(response.content))
plt.figure(figsize=(8, 8))
ax = plt.imshow(image, alpha=0.6)
for face in faces:
    fr = face["faceRectangle"]
    fa = face["faceAttributes"]
    origin = (fr["left"], fr["top"])
    p = patches.Rectangle(
        origin, fr["width"], fr["height"], fill=False, linewidth=2, color='b')
    ax.axes.add_patch(p)
    plt.text(origin[0], origin[1], "%s, %d"%(fa["gender"].capitalize(), fa["age"]),
             fontsize=20, weight="bold", va="bottom")
plt.axis("off")
plt.savefig('D:/test.jpg')
plt.show()

1 个答案:

答案 0 :(得分:0)

对于本地图片, Content-Type 应为 application/octet-stream multipart/form-data 和JSON应该是空的

headers = {
    'Content-type': 'application/octet-stream',
}
body = "" 
#load image
filename = 'C:/testPicutre.JPG'
f = open(filename, "rb")
body = f.read()
f.close()
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/face/v0/detections?%s" % params, body, headers)
response = conn.getresponse("")
data = response.read()
print(data)
conn.close()