内容参考了多篇他人的博客
import base64
import requests
import os
"""
流程:
1、遍历文件夹所有图片,返回其路径的列表
2、将路径列表中的所有路径,读取图片,转换为base64格式
3、通过百度API,给base64格式的图片打分
"""
# client_id 为官网获取的AK, client_secret 为官网获取的SK
# host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'
AK=""#自己申请的AK
CK=""#自己申请的CK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s'%(AK,CK)
header={'Content-Type': 'application/json; charset=UTF-8'}
response1=requests.post(url=host,headers=header)#<class 'requests.models.Response'>
json1 = response1.json()#<class 'dict'>
access_token=json1['access_token']
def walkFile(file):
for root, dirs, files in os.walk(file):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
# 遍历文件
list_of_photo_path=[]
for f in files:
list_of_photo_path.append(os.path.join(root,f))
print(os.path.join(root, f))
# 遍历所有的文件夹
for d in dirs:
print(os.path.join(root, d))
return list_of_photo_path
def picture_transform(filepath):
'''转换图片格式'''
with open("%s"%filepath, 'rb') as f:
base64_data = base64.b64encode(f.read())
return base64_data
list_of_photo_path=walkFile(r"E:\1\netbian")
print(list_of_photo_path)
print(len(list_of_photo_path))
for photo_path in list_of_photo_path:
base64_data=picture_transform(photo_path)
photo_name=photo_path.replace("E:\\1\\netbian\\", "")
try:
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
params = {"image":base64_data,"image_type":"BASE64","face_field":"faceshape,facetype,beauty,"}
header={'Content-Type': 'application/json'}
request_url = request_url + "?access_token=" + access_token
response1=requests.post(url=request_url,data=params,headers=header)#<class 'requests.models.Response'>
json1 = response1.json()
# print(json1)
print(photo_name,"颜值评分为")
print (json1["result"]["face_list"][0]['beauty'],'分/100分')
if json1["result"]["face_list"][0]['beauty']<60 or json1["result"]["face_list"][0]['beauty']>80:
print(photo_path)
else:
pass
except:
print("Warning!错误:",photo_path)