Cognitive Services
Cognitive Services(原Project Oxford) 為整個 Cortana Intelligence Suite 的其中一環(Intelligence),
主要提供了電腦與周遭環境(大多是非結構化資料)間的橋樑,幫助開發者精確運用這些資料,開發智慧應用。
Cognitive Services 提供一系列API,分為五大方向
- Vision
- Speech
- Knowledge
- Search
- Language
Face API
進行人臉相關處理可以使用 Face API,目前為V1.0版本,共提供了以下幾類API
- Face Detection – 偵測性別, 年齡
- Face Verification – 分辨是否同一人
- Similar Face Searching – 找相近的人臉
- Face Grouping – 人臉分群
- Face Identification – 辨別是哪個人
API使用方式大同小異,以下將用 Face Detection API 當作例子
Get Key
- 至 https://www.microsoft.com/cognitive-services/ 註冊,取得 API Key
Sample Code
以下 code 是從API Doc修改而來
主要步驟
- 準備API url (即_url)
- 準備API key (即_key)
- 準備API POST參數 (param, headers)
- 此範例使用 returnFaceLandmarks = True 將會回傳 Face Landmark
- returnFaceAttributes = Age, Gender 將會回傳性別與年齡
- 將欲偵測圖片網址用json送出 (同時也提供了讀取圖檔的方式)
face_detection.py
import time
import requests
import operator
import numpy as np
_url = 'https://api.projectoxford.ai/face/v1.0/detect'
_key = '??????' #API Key
_maxNumRetries = 10
def processRequest( json, data, headers, params = None ):
"""
Helper function to process the request to Project Oxford
Parameters:
json: Used when processing images from its URL. See API Documentation
data: Used when processing image read from disk. See API Documentation
headers: Used to pass the key information and the data type request
"""
retries = 0
result = None
while True:
response = requests.request( 'post', _url, json = json, data = data, headers = headers, params = params )
if response.status_code == 429:
print "Message: %s" % ( response.json()['error']['message'] )
if retries <= _maxNumRetries:
time.sleep(1)
retries += 1
continue
else:
print 'Error: failed after retrying!'
break
elif response.status_code == 200 or response.status_code == 201:
if 'content-length' in response.headers and int(response.headers['content-length']) == 0:
result = None
elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str):
if 'application/json' in response.headers['content-type'].lower():
result = response.json() if response.content else None
elif 'image' in response.headers['content-type'].lower():
result = response.content
else:
print "Error code: %d" % ( response.status_code )
print "Message: %s" % ( response.json()['error']['message'] )
break
return result
# Face detection parameters
params = { 'returnFaceAttributes': 'age,gender',
'returnFaceLandmarks': 'true'}
headers = dict()
headers['Ocp-Apim-Subscription-Key'] = _key
headers['Content-Type'] = 'application/json'
# URL direction to image
urlImage = 'https://raw.githubusercontent.com/Microsoft/ProjectOxford-ClientSDK/master/Face/Windows/Data/identification1.jpg'
json = { 'url': urlImage }
data = None
# Load raw image file into memory
#pathToFileInDisk = r'D:\tmp\identification1.jpg'
#with open( pathToFileInDisk, 'rb' ) as f:
# data = f.read()
#json = None
# Get result
result = processRequest( json, data, headers, params )