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可以非常方便的进行人脸识别的工作。

用Azure上Cognitive Service的Face API识别人脸的更多相关文章

  1. 使用Python结合Face++ API识别人脸

    Face++是北京旷视科技旗下的视觉服务平台,可以进行人脸识别.检测等功能.其人脸识别技术据悉在目前准确率较高,其API非常友好,免费使用,功能众多,而且调用几乎没有限制.这里我使用了Python调用 ...

  2. 如何通过Azure Service Management REST API管理Azure服务

    通过本文你将了解: 什么是Azure Service Management REST API 如何获取微软Azure 订阅号 如何获取Azure管理证书 如何调用Azure Service Manag ...

  3. 【认知服务 Azure Cognitive Service】使用认知服务的密钥无法访问语音服务[ErrorCode=AuthenticationFailure] (2020-08时的遇见的问题,2020-09月已解决)

    问题情形 根据微软认知服务的文档介绍,创建认知服务(Cognitive Service)后,可以调用微软的影像(计算机视觉,人脸),语言(LUIS, 文本分析,文本翻译),语音(文本转语音,语音转文本 ...

  4. 【应用服务 App Service】发布到Azure上的应用显示时间不是本地时间的问题,修改应用服务的默认时区

    问题情形 应用程序发布到App Service后,时间显示不是北京时间,默认情况为UTC时间,比中国时间晚 8 个小时. 详细日志 无 问题原因 Azure 上所有的服务时间都采用了 UTC 时间. ...

  5. 下一个时代,对话即平台 —— 开始使用Bot Framework和Cognitive Service来打造你的智能对话服务

    在16年3月30号微软的全球开发者大会Build上发布了Bot Framework,微软认为下一个big thing是Conversation as a Platform,简称CaaP,中文应该叫做& ...

  6. Azure 上通过 SendGrid 发送邮件

    SendGrid 是什么? SendGrid 是架构在云端的电子邮件服务,它能提供基于事务的可靠的电子邮件传递. 并且具有可扩充性和实时分析的能力.常见的用例有: 自动回复用户的邮件 定期发送信息给用 ...

  7. 在公有云AZURE上部署私有云AZUREPACK以及WEBSITE CLOUD(一)

    (一)前言 本文主要介绍了实践部署AzurePack的Website Cloud的过程.在部署之前, 首先要对AzurePack有个基本的了解.   Azure Pack是微软的私有云方案,具有弹性. ...

  8. 在Azure上部署IPv6的App通过IOS App Store审核

    随着中国企业出海Go Global,越来越多的用户开始在Global Azure部署自己的应用.由于对Global Azure功能和文档的不熟悉,使用过程中或多或少遇到了一些坑.事实上呢,这些并不是坑 ...

  9. SharePoint 2013 APP 开发示例 (六)服务端跨域访问 Web Service (REST API)

    上个示例(SharePoint 2013 APP 开发示例 (五)跨域访问 Web Service (REST API))是基于JavaScript,运行在web browser内去访问REST AP ...

随机推荐

  1. MySQL-版本及服务介绍

    一.MySQL各版本 1.MySQL产品 下载地址:https://www.mysql.com/downloads/ Oracle MySQL Cloud Service(commercial) 商业 ...

  2. no xxx find in java.library.path

    JAVA系统运行时候load native lib时候会遇到下面错误,如 java.lang.UnsatisfiedLinkError: no JSTAF in java.library.path这可 ...

  3. Linux自定义别名alias重启失效问题

    Linux上的别名功能非常方便,例如ll可以显示文件列表的长信息,但是却不是以human能读懂的方式显示,所以我尝试直接在命令行中自定义一个别名: alisa lk='ls -lh' 然后lk就能正常 ...

  4. struts2发送ajax的几个问题(不使用struts2-json-plugin的情况下)

    采用原始方式发送ajax到action时,会遇到get,post的不同,原因是ContentType的问题,ContentType必须是text/html,struts获取到的inputStream才 ...

  5. springcloud-搭建服务注册中心

    创建服务注册中心 1.创建一个springboot 命名为eureka-server 1)添加Eureka依赖 pom.xml <?xml version="1.0" enc ...

  6. 剑指Offer——重建二叉树2

    Question 输入某二叉树的后序遍历和中序遍历的结果,请重建出该二叉树.假设输入的后序遍历和中序遍历的结果中都不含重复的数字.例如输入后序遍历序列{1, 3, 4, 2}和中序遍历序列{1, 2, ...

  7. SolrCloud 5.5.5 + Zookeeper + HDFS使用

    安装sol r 三个节点192.168.1.231,192.168.1.234,192.168.1.235 下载安装包solr.tar.gz 解压 tar -zxvf solr.tar.gz 配置ZK ...

  8. SQL server 2008 T-sql 总结

    数据库的实现 1.添加数据:insert [into] 表名 (字段1,字段2,···) values (值1,值2,····)     其中,into可选. 2.修改数据:update 表名 set ...

  9. UOJ14 DZY Loves Graph

    DZY开始有 nn 个点,现在他对这 nn 个点进行了 mm 次操作,对于第 ii 个操作(从 11 开始编号)有可能的三种情况: Add a b: 表示在 aa 与 bb 之间连了一条长度为 ii ...

  10. numpy加权平均

    import numpy as np a = np.arange(15).reshape(3,5) a array([[ 0, 1, 2, 3, 4],    [ 5, 6, 7, 8, 9],   ...