zoukankan      html  css  js  c++  java
  • 百度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_num int 检测到的图片中的人脸数量
    face_list array 人脸信息列表,具体包含的参数参考下面的列表。
    +face_token string 人脸图片的唯一标识 (人脸检测face_token有效期为60min)
    +location array 人脸在图片中的位置
    ++left double 人脸区域离左边界的距离
    ++top double 人脸区域离上边界的距离
    ++width double 人脸区域的宽度
    ++height double 人脸区域的高度
    ++rotation int64 人脸框相对于竖直方向的顺时针旋转角,[-180,180]
    +face_probability double 人脸置信度,范围【0~1】,代表这是一张人脸的概率,0最小、1最大。其中返回0或1时,数据类型为Integer
    +angle array 人脸旋转角度参数
    ++yaw double 三维旋转之左右旋转角[-90(左), 90(右)]
    ++pitch double 三维旋转之俯仰角度[-90(上), 90(下)]
    ++roll double 平面内旋转角[-180(逆时针), 180(顺时针)]
    +age double 年龄 ,当face_field包含age时返回
    +beauty int64 美丑打分,范围0-100,越大表示越美。当face_fields包含beauty时返回
    +expression array 表情,当 face_field包含expression时返回
    ++type string none:不笑;smile:微笑;laugh:大笑
    ++probability double 表情置信度,范围【0~1】,0最小、1最大。
    +face_shape array 脸型,当face_field包含face_shape时返回
    ++type double square: 正方形 triangle:三角形 oval: 椭圆 heart: 心形 round: 圆形
    ++probability double 置信度,范围【0~1】,代表这是人脸形状判断正确的概率,0最小、1最大。
    +gender array 性别,face_field包含gender时返回
    ++type string male:男性 female:女性
    ++probability double 性别置信度,范围【0~1】,0代表概率最小、1代表最大。
    +glasses array 是否带眼镜,face_field包含glasses时返回
    ++type string none:无眼镜,common:普通眼镜,sun:墨镜
    ++probability double 眼镜置信度,范围【0~1】,0代表概率最小、1代表最大。
    +eye_status array 双眼状态(睁开/闭合) face_field包含eye_status时返回
    ++left_eye double 左眼状态 [0,1]取值,越接近0闭合的可能性越大
    ++right_eye double 右眼状态 [0,1]取值,越接近0闭合的可能性越大
    +emotion array 情绪 face_field包含emotion时返回
    ++type string angry:愤怒 disgust:厌恶 fear:恐惧 happy:高兴 sad:伤心 surprise:惊讶 neutral:无表情 pouty: 撅嘴 grimace:鬼脸
    ++probability double 情绪置信度,范围0~1
    +face_type array 真实人脸/卡通人脸 face_field包含face_type时返回
    ++type string human: 真实人脸 cartoon: 卡通人脸
    ++probability double 人脸类型判断正确的置信度,范围【0~1】,0代表概率最小、1代表最大。
    +mask array 口罩识别 face_field包含mask时返回
    ++type int 没戴口罩/戴口罩 取值0或1 0代表没戴口罩 1 代表戴口罩
    ++probability double 置信度,范围0~1
    +landmark array 4个关键点位置,左眼中心、右眼中心、鼻尖、嘴中心。face_field包含landmark时返回
    +landmark72 array 72个特征点位置 face_field包含landmark72时返回
    +landmark150 array 150个特征点位置 face_field包含landmark150时返回
    +quality array 人脸质量信息。face_field包含quality时返回
    ++occlusion array 人脸各部分遮挡的概率,范围[0~1],0表示完整,1表示不完整
    +++left_eye double 左眼遮挡比例,[0-1] ,1表示完全遮挡
    +++right_eye double 右眼遮挡比例,[0-1] , 1表示完全遮挡
    +++nose double 鼻子遮挡比例,[0-1] , 1表示完全遮挡
    +++mouth double 嘴巴遮挡比例,[0-1] , 1表示完全遮挡
    +++left_cheek double 左脸颊遮挡比例,[0-1] , 1表示完全遮挡
    +++right_cheek double 右脸颊遮挡比例,[0-1] , 1表示完全遮挡
    +++chin double 下巴遮挡比例,,[0-1] , 1表示完全遮挡
    ++blur double 人脸模糊程度,范围[0~1],0表示清晰,1表示模糊
    ++illumination double 取值范围在[0~255], 表示脸部区域的光照程度 越大表示光照越好
    ++completeness int64 人脸完整度,0或1, 0为人脸溢出图像边界,1为人脸都在图像边界内
    +spoofing double 判断图片是否为合成图

    人脸对比

    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'])

    返回结果说明

    参数名必选类型说明
    score float 人脸相似度得分,推荐阈值80分
    face_list array 人脸信息列表
    +face_token string 人脸的唯一标志

    人脸融合

    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_image string 融合图的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_id uint64 唯一的log id,用于问题定位
    image string 处理后图片的Base64编码
  • 相关阅读:
    访问H2数据库的SpringBoot工程
    Spring Annotations
    衡量技术/工具好坏的标准
    Maven Waring : GroupId is duplicate of parent groupId 和 Version is duplicate of parent version
    MyEclipse中,使用Maven新建web项目后,提示The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
    Java Web报错:The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
    maven项目,代码正确的情况下,整个项目中的类报cannot be resolved to a type 错误
    day46_Webservice学习笔记_02
    CentOS6 PXE+Kickstart无人值守安装
    快速诊断Linux性能
  • 原文地址:https://www.cnblogs.com/MoooJL/p/14551325.html
Copyright © 2011-2022 走看看