用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
中的:
部分。
具体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识别人脸的更多相关文章
- 使用Python结合Face++ API识别人脸
Face++是北京旷视科技旗下的视觉服务平台,可以进行人脸识别.检测等功能.其人脸识别技术据悉在目前准确率较高,其API非常友好,免费使用,功能众多,而且调用几乎没有限制.这里我使用了Python调用 ...
- 如何通过Azure Service Management REST API管理Azure服务
通过本文你将了解: 什么是Azure Service Management REST API 如何获取微软Azure 订阅号 如何获取Azure管理证书 如何调用Azure Service Manag ...
- 【认知服务 Azure Cognitive Service】使用认知服务的密钥无法访问语音服务[ErrorCode=AuthenticationFailure] (2020-08时的遇见的问题,2020-09月已解决)
问题情形 根据微软认知服务的文档介绍,创建认知服务(Cognitive Service)后,可以调用微软的影像(计算机视觉,人脸),语言(LUIS, 文本分析,文本翻译),语音(文本转语音,语音转文本 ...
- 【应用服务 App Service】发布到Azure上的应用显示时间不是本地时间的问题,修改应用服务的默认时区
问题情形 应用程序发布到App Service后,时间显示不是北京时间,默认情况为UTC时间,比中国时间晚 8 个小时. 详细日志 无 问题原因 Azure 上所有的服务时间都采用了 UTC 时间. ...
- 下一个时代,对话即平台 —— 开始使用Bot Framework和Cognitive Service来打造你的智能对话服务
在16年3月30号微软的全球开发者大会Build上发布了Bot Framework,微软认为下一个big thing是Conversation as a Platform,简称CaaP,中文应该叫做& ...
- Azure 上通过 SendGrid 发送邮件
SendGrid 是什么? SendGrid 是架构在云端的电子邮件服务,它能提供基于事务的可靠的电子邮件传递. 并且具有可扩充性和实时分析的能力.常见的用例有: 自动回复用户的邮件 定期发送信息给用 ...
- 在公有云AZURE上部署私有云AZUREPACK以及WEBSITE CLOUD(一)
(一)前言 本文主要介绍了实践部署AzurePack的Website Cloud的过程.在部署之前, 首先要对AzurePack有个基本的了解. Azure Pack是微软的私有云方案,具有弹性. ...
- 在Azure上部署IPv6的App通过IOS App Store审核
随着中国企业出海Go Global,越来越多的用户开始在Global Azure部署自己的应用.由于对Global Azure功能和文档的不熟悉,使用过程中或多或少遇到了一些坑.事实上呢,这些并不是坑 ...
- SharePoint 2013 APP 开发示例 (六)服务端跨域访问 Web Service (REST API)
上个示例(SharePoint 2013 APP 开发示例 (五)跨域访问 Web Service (REST API))是基于JavaScript,运行在web browser内去访问REST AP ...
随机推荐
- java屏幕截取
CaptureScreen.java ```import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; i ...
- web应用路径问题(相对路径,绝对路径,动态获取路径)
1.相对路径和绝对路径 绝对路径:以 “ / ” 开头的路径,是完整的路径. 相对路径:不以 “ / ” 开头的路径,是相对于当前web资源目录的路径. 在绝对路径中, “ / ” 的含义有两种解释: ...
- Kafka详解六:Kafka如何通过源码实现监控
问题导读: 1.kafka的消费者组的消费偏移存储,kafka支持两个版本? 2.ConsumerOffsetChecker类的作用是什么? 3.Kafka如何通过源码实现 ...
- MVC 绑定 下拉框数据
HTML: <div class="form-group col-sm-12"> <div class="col-sm-4"> < ...
- 【转】Pearson,Spearman,Kendall相关系数的具体分析
测量相关程度的相关系数很多,各种参数的计算方法及特点各异. 连续变量的相关指标: 此时一般用积差相关系数,又称pearson相关系数来表示其相关性的大小,积差相关系数只适用于两变量呈线性相关时.其数值 ...
- UI(UGUI)框架(二)-------------UIManager单例模式与开发BasePanel面板基类/UIManage统一管理UI面板的实例化/开发字典扩展类
UIManage单实例: /// 单例模式的核心 /// 1,定义一个静态的对象 在外界访问 在内部构造 /// 2,构造方法私有化 private static UIManager _instanc ...
- 2017-02-23 错误信息:未在本地计算机上注册“Microsoft.ACE.oledb.12.0”提供程序。
问题如题,解决办法:去 http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/Access ...
- 隔行换色(WPF DataGrid 标准例子)
<DataGrid AlternationCount="2"> <DataGrid.RowStyle> ...
- "阿拉伯""伊斯兰""穆斯林"三个概念怎么分?
伊斯兰.阿拉伯.穆斯林这三个概念到底有什么不同?要言君将用五分钟给您概述这三个概念,并厘清其边界,说明其交集,帮您迅速构建"阿拉伯.伊斯兰.穆斯林"知识结构概图.相信您得沉思一下费 ...
- javascript ArrayBuffer类型化数组和视图的操作
个人理解类型化数据就是内存分配区域,不同数据的存储就是视图DataView咯 var buffers = []; var json = {"id":100, "name& ...