Created
October 3, 2016 15:47
-
-
Save mike10004/e420f60074aaf38aed8b06c3e87737e1 to your computer and use it in GitHub Desktop.
Microsoft Face API command line Python 2.7 program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# msfa_detect.py | |
# | |
# See https://www.microsoft.com/cognitive-services/en-us/face-api | |
# This code is based on the API reference sample code at | |
# https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236 | |
# | |
# If they provide it with some sort of license that requires redistribution | |
# under the same license, then this code is hereby distributed under that | |
# license. Otherwise, this code is distributed under the terms of the | |
# MIT License, (c) Mike Chaberski 2016. | |
import httplib, urllib, base64, json | |
import os, sys, os.path | |
from argparse import ArgumentParser | |
def do_detect(args): | |
if args.api_key is None: | |
with open(os.path.join(os.getenv("HOME"), '.config', 'microsoft', 'faceapi.credential'), 'r') as ifile: | |
args.api_key = ifile.read().strip() | |
with open(args.imagefile, 'rb') as ifile: | |
imagedata = ifile.read() | |
headers = { | |
# Request headers | |
'Content-Type': 'application/octet-stream', | |
'Ocp-Apim-Subscription-Key': args.api_key, | |
} | |
params = urllib.urlencode({ | |
# Request parameters | |
'returnFaceId': 'true', | |
'returnFaceLandmarks': 'true', | |
'returnFaceAttributes': args.attributes, | |
}) | |
try: | |
conn = httplib.HTTPSConnection('api.projectoxford.ai') | |
conn.request("POST", "/face/v1.0/detect?%s" % params, imagedata, headers) | |
response = conn.getresponse() | |
data = json.loads(response.read()) | |
print json.dumps(data, indent=2) | |
conn.close() | |
return 0 | |
except Exception as e: | |
print >> sys.stderr, "[Errno {0}] {1}".format(e.errno, e.strerror) | |
return 2 | |
_ATTRIBUTES = ('age','gender','headPose','smile','facialHair','glasses') | |
if __name__ == '__main__': | |
p = ArgumentParser(description="Submits an image file to Microsoft Face API for face detection and prints the result") | |
p.add_argument("imagefile", help="image file to send to Microsoft for face detection") | |
p.add_argument("--attributes", default=','.join(_ATTRIBUTES), help="attributes to include in response; choose from " + str(_ATTRIBUTES) + ", comma-delimited") | |
p.add_argument("--api-key", help="subscription key to use; if absent, key is assumed to be the text content of $HOME/.config/microsoft/faceapi.credential") | |
args = p.parse_args() | |
exit(do_detect(args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment