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. JavaWeb 文件上传下载

    1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端,从服务器端下载文件到本地的过程.例如目前网站需要上传头像.上传下载图片或网盘等功能都是利用文件上传下 ...

  2. Linux 多线程编程实例

    一.多线程 VS 多进程 和进程相比,线程有很多优势.在Linux系统下,启动一个新的进程必须分配给它独立的地址空间,建立众多的数据表来维护代码段和数据.而运行于一个进程中的多个线程,他们之间使用相同 ...

  3. 使用UNIDAC连接oracle时的参数设置

    在uniconnection1里设置: server项位hostip:port:sid,如10.53.x.XX:1521:or10g 然后在Options里设置: charset:utf8 direc ...

  4. JAVA 写中文字符串到指定文件 中文乱码 问题解决

    之前试过下面代码里面的注释掉的 方法,都不行,后来想到了不如指定编码格式试试,果真可以了. String as= “中文字符”; //byte[] b = as.getBytes(); try{ Fi ...

  5. HYSBZ 1500 维修数列(伸展树模板)

    题意: 题解:典型伸展树的题,比较全面. 我理解的伸展树: 1 伸展操作:就是旋转,因为我们只需保证二叉树中序遍历的结果不变,所以我们可以旋转来保持树的平衡,且旋转有左旋与右旋.通过这种方式保证不会让 ...

  6. hdu 5147 Sequence II 树状数组

    Sequence II Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Prob ...

  7. 判断A字符串是B字符串的反转

    先将其中一个字符串进行反转操作,然后两个字符串进行判断. 1.反转 /** * 字符串反转 * @param str * @return */ private static String conver ...

  8. Spring Boot入门(二)

    一.Spring Boot项目打包 1.引入maven打包相关插件 2.项目右击run as>Maven clean.run as>Maven install在target文件夹下会生成相 ...

  9. 使用<s:property value="4"/>是报错

    报错的情况是 在jsp中引入标签 <%@ taglib uri="/struts-tags" prefix="s" %> 项目中也有ognl.jar ...

  10. setintervalue传参数的三种方法

    http://www.cnblogs.com/wkylin/archive/2012/09/07/2674911.html http://www.bhcode.net/article/20110822 ...