遍历文件夹下所有照片,进行人脸识别出性别年龄等信息
# 调用百度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)