не могу отправить / запросить base64 к Azure Face API с Python - PullRequest
0 голосов
/ 01 июня 2019

Я хочу отправить изображение на API-интерфейсе Azure Face, но преобразовать файл изображения в base64 просто, и он не может отправлять запросы.

Это код запроса API Azure Face, работает на Python, но код показывает ошибку

import requests
import json
import base64

subscription_key = 'my_key'
assert subscription_key

face_api_url = 'https://southeastasia.api.cognitive.microsoft.com/face/v1.0/detect'


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

#data = 'test.jpg'

with open("test.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    print(encoded_string)

params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
}

#body={
#    "url": 'data:image/jpeg;base64' + str(encoded_string)
#}
#data={
#    "data": encoded_string,
#    "contentType": "application/octet-stream",
#}

response = requests.post(face_api_url, params=params, headers=headers, json={"data": "image/JPEG;base64,/"+str(encoded_string)})
print(json.dumps(response.json()))

это ошибка:

{"error": {"code": "InvalidURL", "message": "Invalid image URL."}}

это правильно:

[{"faceId": "f9fd11a4-8855-4304-af98-f200afcae843", "faceRectangle": {"top": 621, "left": 616, "width": 195, "height": 195}, "faceAttributes": {"smile": 0.0, "headPose": {"pitch": -11.4, "roll": 7.7, "yaw": 5.3}, "gender": "male", "age": 29.0, "facialHair": {"moustache": 0.4, "beard": 0.4, "sideburns": 0.1}, "glasses": "NoGlasses", "emotion": {"anger": 0.0, "contempt": 0.0, "disgust": 0.0, "fear": 0.0, "happiness": 0.0, "neutral": 0.999, "sadness": 0.001, "surprise": 0.0}, "blur": {"blurLevel": "high", "value": 0.89}, "exposure": {"exposureLevel": "goodExposure", "value": 0.51}, "noise": {"noiseLevel": "medium", "value": 0.59}, "makeup": {"eyeMakeup": true, "lipMakeup": false}, "accessories": [], "occlusion": {"foreheadOccluded": false, "eyeOccluded": false, "mouthOccluded": false}, "hair": {"bald": 0.04, "invisible": false, "hairColor": [{"color": "black", "confidence": 0.98}, {"color": "brown", "confidence": 0.87}, {"color": "gray", "confidence": 0.85}, {"color": "other", "confidence": 0.25}, {"color": "blond", "confidence": 0.07}, {"color": "red", "confidence": 0.02}]}}}, {"faceId": "6c83b2c8-2cdc-43ea-994c-840932601b1d", "faceRectangle": {"top": 693, "left": 1503, "width": 180, "height": 180}, "faceAttributes": {"smile": 0.003, "headPose": {"pitch": -9.0, "roll": -0.5, "yaw": -1.5}, "gender": "female", "age": 58.0, "facialHair": {"moustache": 0.0, "beard": 0.0, "sideburns": 0.0}, "glasses": "NoGlasses", "emotion": {"anger": 0.0, "contempt": 0.001, "disgust": 0.0, "fear": 0.0, "happiness": 0.003, "neutral": 0.984, "sadness": 0.011, "surprise": 0.0}, "blur": {"blurLevel": "high", "value": 0.83}, "exposure": {"exposureLevel": "goodExposure", "value": 0.41}, "noise": {"noiseLevel": "high", "value": 0.76}, "makeup": {"eyeMakeup": false, "lipMakeup": false}, "accessories": [], "occlusion": {"foreheadOccluded": false, "eyeOccluded": false, "mouthOccluded": false}, "hair": {"bald": 0.06, "invisible": false, "hairColor": [{"color": "black", "confidence": 0.99}, {"color": "gray", "confidence": 0.89}, {"color": "other", "confidence": 0.64}, {"color": "brown", "confidence": 0.34}, {"color": "blond", "confidence": 0.07}, {"color": "red", "confidence": 0.03}]}}}]

Ответы [ 2 ]

0 голосов
/ 05 июня 2019

Я вижу, что вы хотите отправить локальное изображение для обнаружения лица через REST API.

На самом деле, вам просто нужно изменить код из трех мест, чтобы он работал, как показано ниже.

  1. Добавить заголовок {"Content-Type": "application/octet-stream"}
  2. Чтение байтов из файла, например data = open('<your filename>', 'rb').read()
  3. Используйте data=data для двоичных данных вместо json={...} для URL-адреса изображения в методе requests.post

Вот мой пример изображения person_of_interest-5.jpg, загруженный с Bing Image.

enter image description here

И мой код, как показано ниже.

import requests

subscription_key = '<your key>'

face_api_url = 'https://southeastasia.api.cognitive.microsoft.com/face/v1.0/detect'

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

data = open('person_of_interest-5.jpg', "rb").read()

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, data=data)
print(response.text)

Тогда это работает, и его результат будет ниже.

[{"faceId":"e07cc105-143e-4ee3-9d84-a2830c8ddd07","faceRectangle":{"top":1501,"left":2582,"width":471,"height":471},"faceAttributes":{"smile":0.391,"headPose":{"pitch":-4.3,"roll":41.8,"yaw":20.8},"gender":"male","age":40.0,"facialHair":{"moustache":0.1,"beard":0.1,"sideburns":0.1},"glasses":"NoGlasses","emotion":{"anger":0.016,"contempt":0.008,"disgust":0.01,"fear":0.0,"happiness":0.391,"neutral":0.569,"sadness":0.003,"surprise":0.003},"blur":{"blurLevel":"medium","value":0.36},"exposure":{"exposureLevel":"goodExposure","value":0.53},"noise":{"noiseLevel":"medium","value":0.52},"makeup":{"eyeMakeup":false,"lipMakeup":false},"accessories":[],"occlusion":{"foreheadOccluded":false,"eyeOccluded":false,"mouthOccluded":false},"hair":{"bald":0.18,"invisible":false,"hairColor":[{"color":"gray","confidence":0.96},{"color":"black","confidence":0.95},{"color":"other","confidence":0.6},{"color":"brown","confidence":0.34},{"color":"blond","confidence":0.12},{"color":"red","confidence":0.02}]}}},{"faceId":"a54d8823-0518-4cb6-942c-4d5357316e69","faceRectangle":{"top":451,"left":1168,"width":427,"height":427},"faceAttributes":{"smile":0.0,"headPose":{"pitch":0.9,"roll":0.0,"yaw":1.0},"gender":"male","age":43.0,"facialHair":{"moustache":0.1,"beard":0.1,"sideburns":0.1},"glasses":"ReadingGlasses","emotion":{"anger":0.0,"contempt":0.0,"disgust":0.0,"fear":0.0,"happiness":0.0,"neutral":0.959,"sadness":0.0,"surprise":0.04},"blur":{"blurLevel":"medium","value":0.66},"exposure":{"exposureLevel":"goodExposure","value":0.66},"noise":{"noiseLevel":"high","value":1.0},"makeup":{"eyeMakeup":false,"lipMakeup":false},"accessories":[{"type":"glasses","confidence":1.0}],"occlusion":{"foreheadOccluded":false,"eyeOccluded":false,"mouthOccluded":false},"hair":{"bald":0.02,"invisible":false,"hairColor":[{"color":"brown","confidence":0.99},{"color":"black","confidence":0.94},{"color":"gray","confidence":0.52},{"color":"other","confidence":0.1},{"color":"red","confidence":0.09},{"color":"blond","confidence":0.03}]}}}]
0 голосов
/ 04 июня 2019

Предполагается, что ваш URL изображения неверен. Поскольку я использовал приведенный ниже код, он работал для меня.

import requests
import json

subscription_key = None
assert subscription_key

face_api_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect'

image_url = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.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})
print(json.dumps(response.json()))

Хотя я бы посоветовал вам использовать Python SDK для Face, который вы можете установить здесь.

pip install cognitive_face

Распознавание лиц довольно просто, выполнив ниже

import cognitive_face as CF

KEY = '<Subscription Key>'  # Replace with a valid subscription key (keeping the quotes in place).
CF.Key.set(KEY)

BASE_URL = 'https://westus.api.cognitive.microsoft.com/face/v1.0/'  # Replace with your regional Base URL
CF.BaseUrl.set(BASE_URL)

# You can use this example JPG or replace the URL below with your own URL to a JPEG image.
img_url = 'https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg'
faces = CF.face.detect(img_url)
print(faces)

Вот пример ответа

[{'faceId': '26d8face-9714-4f3e-bfa1-f19a7a7aa240', 'faceRectangle': {'top': 124, 'left': 459, 'width': 227, 'height': 227}}]

Надеюсь, это поможет.

...