居然长得的还没一只熊好看?用Python做一个颜值检测,结果就离了大谱
准备工作
在写代码之前,你需要先在Baidu开发者平台申请权限,步骤如下:
对于本篇文章有疑问的同学可以加【资料白嫖、解答交流群:910981974】
先去要一些美女的照片素材回来做颜值检测
开发环境
- Python 3.8
- Pycharm 2021.2
- 会使用API接口 百度云接口
模块使用
- requests >>> pip install requests
- tqdm >>> pip install tqdm
- os
- base64
第一个阶段 去采集主播照片数据
请求数据
url = f'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&gameId=2168&tagAll=0&page=1'
# headers 请求头 伪装Python的代码 不被识别出来是爬虫程序...
# headers 是一个字典数据类型
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
}
# 通过requests模块去对url地址发送请求
response = requests.get(url=url, headers=headers)
解析数据,提取我们想要数据内容,主播名字,主播封面图url地址
# json数据提取内容 根据冒号左边的内容 提取冒号右边内容
data_list = response.json()['data']['datas']
for index in data_list:
# pprint.pprint(index)
name = index['nick']
img_url = index['screenshot']
翻页
for page in range(1, 11):
url = f'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&gameId=2168&tagAll=0&page={page}'
保存图片数据内容
img_content = requests.get(url=img_url, headers=headers).content
# 'img\\' 文件路径 name 文件名字 '.jpg' 文件后缀 >>> 文件名
# mode 保存方式 wb 二进制模式写入
# as 重命名 为 f
filename = 'img_1\\'
if not os.path.exists(filename):
os.mkdir(filename)
with open(filename + name + '.jpg', mode='wb') as f:
f.write(img_content) # 写入数据
print('正在保存: ', name)
颜值检测
调用接口进行识别
def get_beauty(img_base64): host = 'https://aip.baidubce.com/oauth/2.0/token' data = { 'grant_type': 'client_credentials', 'client_id': 'vXONiwhiVGlBaI2nRRIYLgz5', 'client_secret': 'ouZMTMuCGLi7pbeg734ftNxn9h3qN7R4' } response = requests.get(url=host, params=data) token = response.json()['access_token'] # print(token) ''' 人脸检测与属性分析 ''' request_url = f"https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token={token}" params = { "image": img_base64, # 需要传递 图片 base64 "image_type": "BASE64", "face_field": "beauty" } headers = {'content-type': 'application/json'} response = requests.post(request_url, data=params, headers=headers) try: beauty = response.json()['result']['face_list'][0]['beauty'] return beauty except: return '识别失败'
获取所有图片,进行排名
lis = [] files = os.listdir('img_1\\') print('正在识别人脸, 颜值检测中, 请稍后.....') for file in tqdm(files): img_file = 'img_1\\' + file img_name = file.split('.')[0] # print(img_file) f = open(img_file, mode='rb') # 读取一张图片内容 img_base64 = base64.b64encode(f.read()) beauty = get_beauty(img_base64) if beauty != '识别失败': dit = { '主播': img_name, '颜值': beauty, } lis.append(dit) # 把字典添加到空列表里面 # print(f'{img_name}颜值评分是{beauty}') lis.sort(key=lambda x:x['颜值'], reverse=True) num = 1 # 前10张照片的颜值排名 for index in lis: print(f'颜值排名第{num}的是{index["主播"]}, 颜值评分是{index["颜值"]}') num += 1
看看排名情况
前三名
emmm。。。。。。
然我看来看看最后三名
我不服,最后一名居然输给了一只熊和一个男的,而且才得22分?
看了下官方的文档,最后一名可能是因为手挡住了脸部,但被一只熊给打败了,就离谱