Python调百度API实现人脸识别

前言

遍历文件夹下所有照片,进行人脸识别出性别年龄等信息

先看下效果

Python调百度API实现人脸识别_第1张图片

上代码

# 调用百度API完成人脸识别
import requests
import base64
import os

#获取access_token
def getAccessToken(client_id, client_secret):
    # client_id 为官网获取的AK, client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    response = requests.get(host)
    if response:
        tokenResult = response.json()
        access_token = tokenResult['access_token']
        return access_token
    return ""

#遍历获取图片路径
def getPicPath(client_id, client_secret,target_path):
    # 返回指定路径的文件夹名称
    dirs = os.listdir(target_path)
    # 循环遍历该目录下的照片
    for dir in dirs:
        # 拼接字符串
        pa = target_path+"\\"+dir
        print("图片路径:",pa.replace("\\","/"))
        #调百度API
        baidu_face(client_id, client_secret,pa)

#图片转码base64
def picToBase64(file_path):
    with open(file_path, 'rb') as f:
        img = base64.b64encode(f.read()).decode('utf-8')
        return img

#调用百度API完成人脸识别
def baidu_face(client_id, client_secret,file_path):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
    params = {"image": picToBase64(file_path), "image_type": "BASE64",
              "face_field": "age,beauty,glasses,gender,race"}
    access_token = getAccessToken(client_id, client_secret)
    if(access_token == ""):
        print("获取access_token失败")
        return
    
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-Type': 'application/json'}
    response = requests.post(request_url, data=params, headers=headers)
    json = response.json()
    errorcode = json['error_code']
    if(errorcode != 0):
        print("==未识别==")
        return
    
    print("性别为", json["result"]["face_list"][0]['gender']['type'])
    print("年龄为", json["result"]["face_list"][0]['age'], '岁')
    print("人种为", json["result"]["face_list"][0]['race']['type'])
    print("颜值评分为", json["result"]["face_list"][0]['beauty'], '分/100分')
    print("是否带眼镜", json["result"]["face_list"][0]['glasses']['type'])
    print("====================================================")

if __name__ == '__main__':

    client_id = 'pjEFqZvyavVGkwO7sjLjG7M7'  # ak
    client_secret = 'GBEsh6MZ9QG8wtsqxQsuW22VI76S5cK6'  # sk
    target_path = "E:\@python\spider\pic" #要遍历的目录
    #start
    getPicPath(client_id, client_secret,target_path)

思路分析

  1. 注册百度智能云,添加人脸识别应用获取ak和sk
  2. 遍历文件夹获取图片路径
  3. 图片base64编码
  4. 调用百度人脸识别API,获取识别结果

相关链接

  1. 百度智能云地址:https://login.bce.baidu.com/?account=
  2. 人脸检测API文档:https://ai.baidu.com/ai-doc/FACE/yk37c1u4t

你可能感兴趣的:(python)