用Azure上Cognitive Service的Face API识别人脸

Azure在China已经发布了Cognitive Service,包括人脸识别、计算机视觉识别和情绪识别等服务。

本文将介绍如何用Face API识别本地或URL的人脸。

一 创建Cognitive Service

1 在Azure上创建Cognitive Service的Face服务:

2 获取服务的链接和key:

创建成功后,在overview的页面上可以看到服务链接,已经Key:

有了这些信息后,就可以开始进入coding的阶段了。

二 Python code

1 通过URL链接实现人脸识别

关于Azure 人脸识别的API内容可以参考:

https://docs.microsoft.com/en-us/azure/cognitive-services/Face/APIReference

中的:

https://eastasia.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236/console

部分。

具体python的实现如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

#导入相关模块
import httplib, urllib, json

#Face API相关的Key和Endpoint
subscription_key = '30a236e53b924f2c943892711d8d0e45'
uri_base = 'api.cognitive.azure.cn'

#定义html的header,这里Content-type决定了body中的类型,是URL还是文件类型的,这里的Json支持URL模式
headers = {
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key,
}
#定义返回的内容,包括FaceId,年龄、性别等等
params = urllib.urlencode({
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
})
#图片的URL
body = "{'url':'http://www.bidmc.org/~/media/Images/Research_NotDepartmentResearch/ResearchCenters/Cancer%20Research%20Institute/Wenyi%20Wei%20250.jpg'}"

#Call Face API,进行人脸识别
try:
    conn = httplib.HTTPSConnection('api.cognitive.azure.cn')
    conn.request("POST", "/face/v1.0/detect?%s" % params, body, headers)
    response = conn.getresponse()
    data = response.read()
    parsed = json.loads(data)
    print ("Response:")
    print (json.dumps(parsed, sort_keys=True, indent=2))
    conn.close()

except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

输出结果如下:

[
    {
    "faceAttributes": {
        "age": 45.5,
        ...
        "gender": "male",
        "faceId": "b15284c9-ce1c-40eb-a76b-99d5ce381081",
        "faceRectangle": {
            "height": 56,
            "left": 155,
            "top": 50,
            "width": 56
            }
        }
    }
]

 

可以看到是一个Json的输出,里面包含有FaceId,年龄,性别等各种信息。

2 用本地文件作为源文件进行图片识别

具体的代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

#导入相关模块
import httplib, urllib, json
from os.path import expanduser

#Face API相关的Key和Endpoint
subscription_key = '30a236e53b924f2c943892711d8d0e45'
uri_base = 'api.cognitive.azure.cn'

#定义html的header,这里Content-type决定了body中的类型,是URL还是文件类型的,这里的Json支持URL模式
headers = {
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': subscription_key,
}
#定义返回的内容,包括FaceId,年龄、性别等等
params = urllib.urlencode({
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
})
#打开本地图片
img = open(expanduser('D:\\Heng\\Pictures\\100EOS5D\\C5D_5131.JPG'), 'rb')
#Call Face API,进行人脸识别
try:
    conn = httplib.HTTPSConnection('api.cognitive.azure.cn')
    conn.request("POST", "/face/v1.0/detect?%s" % params, img, headers)
    response = conn.getresponse()
    data = response.read()
    parsed = json.loads(data)
    print ("Response:")
    print (json.dumps(parsed, sort_keys=True, indent=2))
    conn.close()

except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

 

输出和前面的类似。

3 给图片中的人脸打框,并表示年龄

根据前面的人脸识别,可以根据返回值,对人脸进行打框,并标识其返回的年龄,具体Python程序如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

#导入相关模块
import httplib, urllib, json
from os.path import expanduser
from PIL import Image, ImageDraw, ImageFont

def getRectangle(mydata):
    left = mydata[u'left']
    top = mydata[u'top']
    bottom = left + mydata[u'height']
    right = top + mydata[u'width']
    return ((left, top), (bottom, right))

#Face API相关的Key和Endpoint
subscription_key = '30a236e53b924f2c943892711d8d0e45'
uri_base = 'api.cognitive.azure.cn'

#定义html的header,这里Content-type决定了body中的类型,是URL还是文件类型的,这里的Json支持URL模式
headers = {
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': subscription_key,
}
#定义返回的内容,包括FaceId,年龄、性别等等
params = urllib.urlencode({
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
})
#打开本地图片
#imgfile = 'D:\\Heng\\Pictures\\C5D_3966.JPG'
imgfile = 'D:\\Heng\\desktop\\face.JPG'

img = open(expanduser(imgfile), 'rb')
#Call Face API,进行人脸识别
try:
    conn = httplib.HTTPSConnection('api.cognitive.azure.cn')
    conn.request("POST", "/face/v1.0/detect?%s" % params, img, headers)
    response = conn.getresponse()
    data = response.read()
    parsed = json.loads(data)
    conn.close()

except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))
#新建一个文件
newimg = Image.open(imgfile)
draw = ImageDraw.Draw(newimg)
#判断其大小
size = len(str(newimg.size[0]))
#根据大小分配字体大小和字的位置
if size>= 4:
    fs = 50
    ps = 130
else:
    fs = 10
    ps = 13
#图片的字体和颜色
font = ImageFont.truetype("consola.ttf", fs)
draw.ink = 255 + 0 * 256 + 0 * 256 * 256
#给每个识别出的人脸画框、并标识年龄
for a in parsed:
    b = a[u'faceRectangle']
    c = getRectangle(b)
    draw.rectangle(c, outline='red')
    draw.text([c[0][0],c[0][1]-ps],"Age="+str(a[u'faceAttributes'][u'age']),font=font)
newimg.show()
 

其输出是一张如下d 照片:

 

总结:

通过Azure的Cognitive Service的Face API可以非常方便的进行人脸识别的工作。

posted @ 2017-12-23 16:57  衡子  阅读(3226)  评论(3编辑  收藏  举报