百度开源的人脸识别接口,通过上传人像图片可以返回颜值打分,年龄等信息;今天我们使用这个接口实现一款Python颜值打分神器
import requests
import base64
import time
import os
def access_token(ak, sk):
"""获取接口认证,获取认证代码"""
response = requests.get(f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}')
if response.status_code == 200:
return response.json()['access_token']
else:
print('获取token失败...')
ak = '22F5CIXEg69Uc9vyMggrgZAb'
sk = 'cd5wylpIu1W19rLtqzrVh1FHnVO73uRH'
token = access_token(ak, sk)
img = 'XXX.jpg'
# 检测
# 颜值打分
def appearance(file_path, token):
# 图片打开成二进制
with open(file_path, 'rb') as f:
# 转成base64编码 只要二进制图片数据
data = base64.b64encode(f.read())
headers = {'content-type': 'application/json'}
params = {
'image': data,
'image_type': 'BASE64',
# 要获取的颜值打分分数
'face_field': 'beauty'
}
url = f'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token={token}'
res = requests.post(url, headers=headers, data=params)
if res.status_code == 200:
beauty = res.json()['result']['face_list'][0]["beauty"]
return beauty
else:
return '认证失败'
path = 'C:\\Users\\Administrator\\Desktop\\代码堆\\手机壁纸'
img_list = os.listdir(path)
score_dict = {}
for image in img_list:
try:
name = image.split('.')[0]
image_path = path + '/' + image
score = appearance(image_path, token)
score_dict[name] = score
except:
print(f'正在检测{name} | 检测失败!!!')
else:
print(f'正在检测{name} | 颜值打分为:{score}')
time.sleep(0.5)
print('\n======================================================检测完成======================================================\n')
print(score_dict)
print(score_dict.items())
change_score = sorted(score_dict.items(),key=lambda x: x[1], reverse=True)
print(change_score)
# enumerate 枚举,把change_score里面的数据一一列出来
print(list(enumerate(change_score)))
for a, b in enumerate(change_score):
print(f'小姐姐的名字是: {change_score[a][0]} | 颜值名次是: 第{a + 1} | 她的颜值分数为: {change_score[a][1]}')
图片的话,可以自己去爬一些壁纸或者美女图片,最好都是有正脸的