百度AI——人脸识别案例

人脸分析

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

# 根据图片名读取图片,并转换成base64
def 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 requests
import base64
import json



# 获取token
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


# 根据图片名读取图片,并转换成base64
def 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编码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值