Python人脸识别检测

人脸检测小程序是基于百度智能云人脸识别API接口实现的,操作简单,最重要的是免费,步骤如下:

一、获取人脸识别API的访问令牌

# 获取 access_token 数据
def token():
    try:
        # client_id 为官网获取的AK, client_secret 为官网获取的SK
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=ei2nro5Ugpzn11NkWpyoZGhm&client_secret=raEg24ORrOfBfhhaPRZ8swkUK5boWc1G'
        response = requests.get(host).text
        access_token = json.loads(response)['access_token']
        return access_token
    except:
        pass

二、读取图片数据,并转化为base64数据

# 读取图片二进制数据,并转换为base64数据
def base():
    path = 'img/img.jpg'
    with open(path, 'rb')as f:
        content = f.read()
    image_b64 = base64.b64encode(content)
    image = str(image_b64, 'utf-8')
    return image

三、开始检测,筛选返回的参数信息

# 开始检测
def detection():
    # 调用API
    request_url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect' + '?access_token=' + token()
    headers = {'content-type': 'application/json'}
    data = {
        'image': base(),
        'image_type': 'BASE64',
        'face_field': 'age,beauty,expression,face_shape,gender,glasses,landmark,landmark150,quality,eye_status,emotion,face_type,mask,spoofing'
            }
    # 爬取返回内容
    responses = requests.post(request_url, data=data, headers=headers).text
    responses_json = json.loads(responses)

    # 获取返回信息
    result = responses_json['result']
    lists = result['face_list']
    
    # 人脸类别
    face_type = lists[0]['face_type']
    if face_type['type'] == 'human':
        print('类别:真实中的人\n')
    else:
        print('类别:卡通中的人\n')
    # 性别
    gender = lists[0]['gender']
    if gender['type'] == 'male':
        print('性别:男生\n')
    else:
        print('性别:女生\n')
    # 年龄
    age = lists[0]['age']
    print('年龄:{} 岁\n'.format(age))

温馨提示

1、人脸识别更多参数查看API相关文档

2、需要导入的库requests,json,base64 ,其中 requests 为第三方库,需要安装pip install requests

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容