许可优化
许可优化
产品
产品
解决方案
解决方案
服务支持
服务支持
关于
关于
软件库
当前位置:服务支持 >  软件文章 >  百度AI人脸识别案例详解(API调用与开发实战)

百度AI人脸识别案例详解(API调用与开发实战)

阅读数 3
点赞 0
article_banner

人脸分析


import requests, base64  def get_access_token():    url = 'https://aip.baidubce.com/oauth/2.0/token'    data = {        'grant_type': 'client_credentials',  # 固定值        'client_id': '',  # 在开放平台注册后所建应用的API Key        'client_secret': ''  # 所建应用的Secret Key    }    res = requests.post(url, data=data)    res = res.json()    access_token = res['access_token']    return access_token  def get_json(img):    access_token=get_access_token()    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"    file = open(img, 'rb')  # 二进制读取图片    base64_data = base64.b64encode(file.read())  # 将图片进行base64编码    base64_code = base64_data.decode()    params = {        'image': base64_code,        'image_type': 'BASE64',        'face_field': 'age,beauty,expression,face_shape,gender,glasses,landmark,landmark150,quality,eye_status,emotion,face_type,mask,spoofing'    }    request_url = request_url + "?access_token=" + access_token    headers = {'Content-Type': 'application/json'}    response = requests.post(request_url, data=params, headers=headers)    if response:        return response.json() if __name__ == '__main__':    img = './img/mjl.jpg'    json_data=get_json(img)

返回结果说明


必选类型说明
face_numint检测到的图片中的人脸数量
face_listarray人脸信息列表,具体包含的参数参考下面的列表。
+face_tokenstring人脸图片的唯一标识 (人脸检测face_token有效期为60min)
+locationarray人脸在图片中的位置
++leftdouble人脸区域离左边界的距离
++topdouble人脸区域离上边界的距离
++widthdouble人脸区域的宽度
++heightdouble人脸区域的高度
++rotationint64人脸框相对于竖直方向的顺时针旋转角,[-180,180]
+face_probabilitydouble人脸置信度,范围【0~1】,代表这是一张人脸的概率,0最小、1最大。其中返回0或1时,数据类型为Integer
+anglearray人脸旋转角度参数
++yawdouble三维旋转之左右旋转角[-90(左), 90(右)]
++pitchdouble三维旋转之俯仰角度[-90(上), 90(下)]
++rolldouble平面内旋转角[-180(逆时针), 180(顺时针)]
+agedouble年龄 ,当face_field包含age时返回
+beautyint64美丑打分,范围0-100,越大表示越美。当face_fields包含beauty时返回
+expressionarray表情,当 face_field包含expression时返回
++typestringnone:不笑;smile:微笑;laugh:大笑
++probabilitydouble表情置信度,范围【0~1】,0最小、1最大。
+face_shapearray脸型,当face_field包含face_shape时返回
++typedoublesquare: 正方形 triangle:三角形 oval: 椭圆 heart: 心形 round: 圆形
++probabilitydouble置信度,范围【0~1】,代表这是人脸形状判断正确的概率,0最小、1最大。
+genderarray性别,face_field包含gender时返回
++typestringmale:男性 female:女性
++probabilitydouble性别置信度,范围【0~1】,0代表概率最小、1代表最大。
+glassesarray是否带眼镜,face_field包含glasses时返回
++typestringnone:无眼镜,common:普通眼镜,sun:墨镜
++probabilitydouble眼镜置信度,范围【0~1】,0代表概率最小、1代表最大。
+eye_statusarray双眼状态(睁开/闭合) face_field包含eye_status时返回
++left_eyedouble左眼状态 [0,1]取值,越接近0闭合的可能性越大
++right_eyedouble右眼状态 [0,1]取值,越接近0闭合的可能性越大
+emotionarray情绪 face_field包含emotion时返回
++typestringangry:愤怒 disgust:厌恶 fear:恐惧 happy:高兴 sad:伤心 surprise:惊讶 neutral:无表情 pouty: 撅嘴 grimace:鬼脸
++probabilitydouble情绪置信度,范围0~1
+face_typearray真实人脸/卡通人脸 face_field包含face_type时返回
++typestringhuman: 真实人脸 cartoon: 卡通人脸
++probabilitydouble人脸类型判断正确的置信度,范围【0~1】,0代表概率最小、1代表最大。
+maskarray口罩识别 face_field包含mask时返回
++typeint没戴口罩/戴口罩 取值0或1 0代表没戴口罩 1 代表戴口罩
++probabilitydouble置信度,范围0~1
+landmarkarray4个关键点位置,左眼中心、右眼中心、鼻尖、嘴中心。face_field包含landmark时返回
+landmark72array72个特征点位置 face_field包含landmark72时返回
+landmark150array150个特征点位置 face_field包含landmark150时返回
+qualityarray人脸质量信息。face_field包含quality时返回
++occlusionarray人脸各部分遮挡的概率,范围[0~1],0表示完整,1表示不完整
+++left_eyedouble左眼遮挡比例,[0-1] ,1表示完全遮挡
+++right_eyedouble右眼遮挡比例,[0-1] , 1表示完全遮挡
+++nosedouble鼻子遮挡比例,[0-1] , 1表示完全遮挡
+++mouthdouble嘴巴遮挡比例,[0-1] , 1表示完全遮挡
+++left_cheekdouble左脸颊遮挡比例,[0-1] , 1表示完全遮挡
+++right_cheekdouble右脸颊遮挡比例,[0-1] , 1表示完全遮挡
+++chindouble下巴遮挡比例,,[0-1] , 1表示完全遮挡
++blurdouble人脸模糊程度,范围[0~1],0表示清晰,1表示模糊
++illuminationdouble取值范围在[0~255], 表示脸部区域的光照程度 越大表示光照越好
++completenessint64人脸完整度,0或1, 0为人脸溢出图像边界,1为人脸都在图像边界内
+spoofingdouble判断图片是否为合成图

人脸对比


import requests, base64  def get_access_token():    url = 'https://aip.baidubce.com/oauth/2.0/token'    data = {        'grant_type': 'client_credentials',  # 固定值        'client_id': '',  # 在开放平台注册后所建应用的API Key        'client_secret': ''  # 所建应用的Secret Key    }    res = requests.post(url, data=data)    res = res.json()    access_token = res['access_token']    return access_token # 根据图片名读取图片,并转换成base64def read_img(img):    with open(img, 'rb') as f:        base64_data = base64.b64encode(f.read())        base64_code = base64_data.decode()    return base64_code def get_json(img1,img2):    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"    params = [        {            "image": img1,            "image_type": "BASE64",            "face_type": "LIVE",            "quality_control": "LOW",            "liveness_control": "HIGH"        },        {            "image": img2,            "image_type": "BASE64",            "face_type": "LIVE",            "quality_control": "LOW",            "liveness_control": "HIGH"        }    ]    access_token = get_access_token()    request_url = request_url + "?access_token=" + access_token    headers = {'content-type': 'application/json'}    response = requests.post(request_url, json=params, headers=headers)    if response:        return response.json()  if __name__ == '__main__':    img1 = read_img('img/mm2.jpeg')    img2 = read_img('img/mjl.jpg')    json_data=get_json(img1,img2)    print(json_data)    if json_data['error_msg'] == 'SUCCESS':        score = json_data['result']['score']         if score > 80:            print("照片相似度为:" + str(score) + "基本确定是本人")        else:            print("照片相似度为:" + str(score) + "基本确定不是本人")        print(score)    else:        print('错误信息:', json_data['error_msg'])

返回结果说明


参数名必选类型说明
scorefloat人脸相似度得分,推荐阈值80分
face_listarray人脸信息列表
+face_tokenstring人脸的唯一标志

人脸融合


import requestsimport base64import json   # 获取tokendef get_access_token():    url = 'https://aip.baidubce.com/oauth/2.0/token'    data = {        'grant_type': 'client_credentials',  # 固定值        'client_id': '',  # 在开放平台注册后所建应用的API Key        'client_secret': ''  # 所建应用的Secret Key    }    res = requests.post(url, data=data)    res = res.json()    access_token = res['access_token']    return access_token  # 根据图片名读取图片,并转换成base64def read_photo(name):    with open(name, 'rb') as f:        base64_data = base64.b64encode(f.read())        base64_code = base64_data.decode()    return base64_code  # 调用百度的接口,实现融合图片def face_fusion(template, target):    access_token = get_access_token()    url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge'    request_url = url + '?access_token=' + access_token    params = {        "image_template": {            "image": template,            "image_type": "BASE64",            "quality_control": "NONE"        },        "image_target": {            "image": target,            "image_type": "BASE64",            "quality_control": "NONE"        },        "merge_degree": "NORMAL"    }    params = json.dumps(params)    headers = {'content-type': 'application/json'}    result = requests.post(request_url, data=params, headers=headers).json()    if result['error_code'] == 0:        res = result["result"]["merge_image"]        down_photo(res)    else:        print(str(result['error_code'])+result['error_msg']) # 下载融合后图片def down_photo(data):    imagedata = base64.b64decode(data)    file = open('./result.jpg', "wb")    file.write(imagedata) # 主程序if __name__ == '__main__':    template = read_photo('img/jjy.jpg')    target = read_photo('img/mzc.jpeg')    face_fusion(template, target)

返回结果说明


字段类型说明
merge_imagestring融合图的BASE64值

人像动漫画


import requests, base64  # 百度AI开放平台鉴权函数def get_access_token():    url = 'https://aip.baidubce.com/oauth/2.0/token'    data = {        'grant_type': 'client_credentials',  # 固定值        'client_id': '',  # 在开放平台注册后所建应用的API Key        'client_secret': ''  # 所建应用的Secret Key    }    res = requests.post(url, data=data)    res = res.json()    access_token = res['access_token']    return access_token  def image_process(img_before, img_after, how_to_deal):    # 函数的三个参数,一个是转化前的文件名,一个是转化后的文件名,均在同一目录下,第三个是图像处理能力选择    request_url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/' + how_to_deal    if how_to_deal == 'style_trans':  # 判断如果是 图像风格化,需要额外添加一个风格配置        others = 'cartoon'  # 风格化参数,具体可设置范围参见下面注释        ''' cartoon:卡通画风格 pencil:铅笔风格 color_pencil:彩色铅笔画风格 warm:彩色糖块油画风格 wave:神奈川冲浪里油画风格 lavender:薰衣草油画风格 mononoke:奇异油画风格 scream:呐喊油画风格 gothic:哥特油画风格 '''    else:        others = ''     file = open(img_before, 'rb')  # 二进制读取图片    origin_img = base64.b64encode(file.read())  # 将图片进行base64编码    headers = {'Content-Type': 'application/x-www-form-urlencoded'}    data = {        'access_token': get_access_token(),        'image': origin_img,        "type":'anime_mask',        "mask_id":"2"    }     res = requests.post(request_url, data=data, headers=headers)     res = res.json()    print(res)    if res:        f = open(img_after, 'wb')        after_img = res['image']        after_img = base64.b64decode(after_img)        f.write(after_img)        f.close()  if __name__ == '__main__':    img_before = 'img/mm1.jpg'  # 当前目录下的图片    img_after = img_before.split('.')  # 将原文件名分成列表    img_after = img_after[0] + '_2.' + img_after[1]  # 新生成的文件名为原文件名上加 _1     image_process(img_before, img_after, 'selfie_anime')    # 第三个参数: selfie_anime 为人像动漫化,colourize 图像上色,style_trans 为图像风格化    print('done!')

返回结果说明


字段是否必选类型说明
log_iduint64唯一的log id,用于问题定位
imagestring处理后图片的Base64编码


免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删


相关文章
技术文档
QR Code
微信扫一扫,欢迎咨询~
customer

online

联系我们
武汉格发信息技术有限公司
湖北省武汉市经开区科技园西路6号103孵化器
电话:155-2731-8020 座机:027-59821821
邮件:tanzw@gofarlic.com
Copyright © 2023 Gofarsoft Co.,Ltd. 保留所有权利
遇到许可问题?该如何解决!?
评估许可证实际采购量? 
不清楚软件许可证使用数据? 
收到软件厂商律师函!?  
想要少购买点许可证,节省费用? 
收到软件厂商侵权通告!?  
有正版license,但许可证不够用,需要新购? 
联系方式 board-phone 155-2731-8020
close1
预留信息,一起解决您的问题
* 姓名:
* 手机:

* 公司名称:

姓名不为空

姓名不为空

姓名不为空
手机不正确

手机不正确

手机不正确
公司不为空

公司不为空

公司不为空