LoginSignup
14
11

More than 5 years have passed since last update.

【Python】Microsoft Cognitive ServicesのFace APIを使う

Posted at

Microsoft Cognitive Services - Face API

https://www.microsoft.com/cognitive-services/en-us/face-api
画像中に含まれている顔の位置やその人の性別、年齢などを検出することができます。

Subscription Key

Cognitive ServicesでFace Preview(無料)のSubscription Keyを入手してください。
Key1とKey2がありますが、Key1のみでいいです。
key

PythonからAPIを叩く

Versionは2.7です。3でも動くと思います。
予めpipでrequestsをインストールしておきます。

$ pip install requests

画像ファイル版

detect.py
import sys
import requests


url = 'https://api.projectoxford.ai/face/v1.0/detect'
headers = {
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': '[your subscription key]',
}
params = {
    'returnFaceId': 'true',  # The default value is true.
    'returnFaceLandmarks': 'false', # The default value is false.
    'returnFaceAttributes': 'age,gender', # age, gender, headPose, smile, facialHair, and glasses.
}
if __name__ == '__main__':
    argv = sys.argv
    if len(argv) == 1:
        print 'Usage: # python %s [filename]'  % argv[0]
        quit()
    r = requests.post(url ,headers = headers,params = params,data = open(argv[1],'rb'))

    print(r.text)

image.pngの顔検出を行いたいときは、以下のように実行します。

$ python detect.py image.png

画像URL版

画像をURLで指定するときは以下のようにします。

detect.py
import sys
import json
import requests


url = 'https://api.projectoxford.ai/face/v1.0/detect'
image_url = 'http://example.com/image.png'
headers = {
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '[your subscription key]',
}
params = {
    'returnFaceId': 'true',  # The default value is true.
    'returnFaceLandmarks': 'false', # The default value is false.
    'returnFaceAttributes': 'age, gender', # age, gender, headPose, smile, facialHair, and glasses.
}

payload = {
    'url': image_url,
}

if __name__ == '__main__':
    r = requests.post(url ,headers = headers, params = params, data = json.dumps(payload))

    print(r.text)

image_urlの顔検出を行いたいときは、以下のように実行します。

$ python detect.py

出力結果

[
    {
        "faceId": "xxxxxxxxxxxxxxxxxxxxxxxx",
        "faceRectangle": {
            "top": 119,
            "left": 177,
            "width": 144,
            "height": 144
        },
        "faceAttributes": {
            "gender": "female",
            "age": 17.9
        }
    }
]

Jsonで結果が返ってきていることがわかります。
paramsを変更することで顔の部位の位置情報なども取得することができるようになります。

14
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
11