百度AI - 人脸识别

作者: 虎七 | 来源:发表于2018-01-19 17:46 被阅读168次

AI现在是很火的词,BAT三家公司也都陆续走上了AI开源的道路,目前百度在AI方面走的稍微靠前一些。

今天利用百度AI开放平台提供的功能,来实现一下人脸检测功能。

接口文档: http://ai.baidu.com/docs#/Face-Python-SDK/top


在开始之前,首先得申请一个应用,这个应用拥有使用百度AI的一些权限。

具体看这个网址,很简单:  https://ai.baidu.com/docs#/Begin/top


还需要准备一些python库:

pip install baidu-aip

pip install Pillow


根据百度AI平台提供的文档,我们要做的其实就是构建一个AipFace,然后调用detect方法。

直接上脚本: (detect.py)

# -- coding: utf-8 --

from aip import AipFace

from PIL import Image, ImageDraw

import sys

# 检测参数,如果没有图片路径则返回

if len(sys.argv) <= 1:

    print 'Now params are: ', sys.argv,len(sys.argv)

    print "You should input a imagepath!"

    exit(0)

# 获取图片内容

filepath = sys.argv[1]

with open(filepath, 'rb') as fp:

    image = fp.read()

# 打开ai的客户端,下面的参数分别是申请应用后获取的:AppID, API Key, Secret Key

client = AipFace(' AppID ', ' API Key ',' Secret Key ')

# 填充参数,这里只检测一张人脸

options = {}

options['max_face_num'] = 1

options['face_fields'] = {'age'}

# 调用ai客户端的detect方法,这个方法返回的结果就是对人脸检测后的数据

result = client.detect(image, options)

print result

# 解析返回数据中的位置参数,获取到人脸的矩形信息

location = result['result'][0]['location']

width = location['width']

height = location['height']

left = location['left']

top = location['top']

right = left + width

bottom = top + height

# 使用PIL重新打开图片,绘制出人脸所在的矩形框

img = Image.open(filepath)

imgDraw = ImageDraw.Draw(img)

imgDraw.rectangle(((left, top), (right, bottom)), outline=(255, 0, 0))

img.show()

执行命令:

python detect.py your_img_path

其中检测返回的结果如下:

{

  u'log_id': 3799754530011917,

  u'result_num': 1,

  u'result': [

    {

      u'rotation_angle': -5,

      u'yaw': -10.247494697571,

      u'age': 22,

      u'location': {

        u'width': 197,

        u'top': 94,

        u'height': 177,

        u'left': 72

      },

      u'pitch': 7.9190526008606,

      u'roll': -5.076274394989,

      u'face_probability': 1

    }

  ]

}

对比下前后的结果:

从上面可以看出,检测基本是准确的。

从我测试了多组图片发现,检测结果都略微靠下一点。


其它参考文档:

图片处理框架PIL: http://effbot.org/imagingbook/

相关文章

网友评论

    本文标题:百度AI - 人脸识别

    本文链接:https://www.haomeiwen.com/subject/xicaoxtx.html