准备工作
- 🌈 来个好玩的东西,百度开源的人脸识别接口,通过上传人像图片可以返回颜值打分,年龄等信息;
在运行代码之前,你需要先在Baidu开发者平台申请权限,步骤如下:
-
登录百度云「https://cloud.baidu.com/?from=console」,没有Baidu账号的注册一个;
-
通过界面右上角进入控制台;
-
找到人脸识别,进入并创建应用,创建时默认全选即可;
- 创建完成后,进入管理应用,你会得到两个key(API Key和Secret Key),会用于后期的接口认证;
接口认证
- 在请求人脸检测接口之前,需要通过API Key和Secret Key进行认证,认证代码如下。
- 认证成功的话返回一个
access_token
,用于后期人脸检测的接口请求,token
的有效期为30天,不必频繁请求;
def access_token(ak, sk):host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(ak, sk)response = requests.get(host)if response.status_code == 200:token = response.json()['access_token']return tokenelse:assert '获取Token失败...'
编码
上传的图表需要先进行Base64编码,代码如下:
def encode(img_path):with open(img_path, 'rb') as f:data = base64.b64encode(f.read())return data
人脸检测
需要两个参数,data是Base64编码后的图片文件,token即为前面提到的access_token
;
请求成功的话会返回一个json,其中包括颜值打分,年龄预测,人脸锚点等;
def appearance(data, token):url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token={}'.format(token)headers = {'content-type': 'application/json'}params = {"image": data,"image_type": "BASE64","face_field": "age,beauty,expression,face_shape,gender,glasses,""quality,eye_status,emotion,face_type,mask,spoofing"}res = requests.post(url, headers=headers, data=params)if res.status_code == 200:return res.json()
GO!
认证
将下方cell中的API Key和Secret Key替换为自己在百度开发者后台申请的,完成认证;
token = access_token('API Key', 'Secret Key')
李彦宏
看看这算法有没有对自己的老大有偏心~
有一说一,颜值这块,Robin在一众企业家中真难逢对手。
# 图片路径
page_path = '/home/kesci/work/appearance/robin.jpeg'
data = encode(page_path)
result = appearance(data, token)['result']['face_list'][0]
msg = '年龄:{}\n性别:{}\n颜值:{}\n脸型:{}\n是否戴眼镜:{}\n是否戴口罩:{}\n情绪:{}\n'
print(msg.format(result['age'],result['gender']['type'],result['beauty'],result['face_shape']['type'],result['glasses']['type'],result['mask']['type'],result['emotion']['type']))
Image(page_path)
马云
三角形脸型??
马化腾
除了颜值外还能识别是否戴眼镜~
小罗伯特·唐尼
除了普通眼镜还能判断是不是太阳镜☀️
小姐姐
拉高一下本项目的颜值平均分~
口罩
识别是否戴口罩
- 欢迎一键三连~~