知识点:
实现步骤:
搜索【百度大脑】,打开【百度AI开放平台】网站,其中有人脸识别技术,根据人脸识别SDK文档安装Python SDK。安装命令(cmd命令):
pip install baidu-aip # 安装了pip,可通过该命令安装
python setup.py install # 安装了setup.tool,通过该命令安装
在【百度AI开放平台】中控制台中创建人脸识别应用,获取系统为你分配的APPID AK SK(需先注册百度账号)
代码实现:
导包
import base64
from aip import AipFace
创建百度对象
""" 你的 APPID AK SK """
APP_ID = '你的 App ID' # 百度AI平台提供
API_KEY = '你的 Api Key' # 百度AI平台提供
SECRET_KEY = '你的 Secret Key' # 百度AI平台提供
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
设置人脸检测接口的参数
# 该参数为可选参数,默认只返回face_token、人脸框、概率和旋转角度,其他的属性值需自行获取并用 , 隔开
option = {
'face_field': "age,gender,beauty"}
# 图片类型 BASE64:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M
imageType = "BASE64"
# 文件路径
file = 'image路径'
处理图片格式
# 该函数用于处理图片格式
def set_img(file):
with open(file, 'rb') as f:
res = base64.b64encode(f.read())
# print(type(res))
return res.decode('utf-8')
调用人脸检测
""" 调用人脸检测 """
results = client.detect(set_img(file), imageType, option)
print(results)
返回结果示例
{
'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 2012579895594,'timestamp': 1572346654, 'cached': 0, 'result': {
'face_num': 1,
'face_list': [{
'face_token': '3099def6a6b4611ee4f54e0c40dcbe71','location': {
'left': 92.53, 'top': 88.92, 'width': 90, 'height': 94, 'rotation': 12},
'face_probability': 1, 'angle': {
'yaw': -0.02, 'pitch': 6.33, 'roll': 8.31}, 'age': 23, 'gender': {
'type': 'male', 'probability': 1}, 'beauty': 79.28}]}}
对人脸检测返回的结果进行处理
def get_score(file):
sex = ''
results = client.detect(set_img(file), imageType, option)
age = results['result']['face_list'][0]['age']
gender = results['result']['face_list'][0]['gender']['type']
sex = ('男' if gender == 'male' else '女')
beauty = results['result']['face_list'][0]['beauty']
return print(f"姓名:wyb,性别:{sex},年龄:{age},颜值:{beauty}")
get_score(file)
处理后的结果
姓名:wyb,性别:男,年龄:23,颜值:79.28