当前位置 博文首页 > singlezzz的博客:python实现颜值检测

    singlezzz的博客:python实现颜值检测

    作者:[db:作者] 时间:2021-07-31 21:24

    前几天爬了一点主播的图片,就想用下百度的api检测一下颜值,哈哈哈。
    先创建个接口文件,用来调用百度api 代码如下:

    from aip import AipFace
    import base64
    
    def face_rg(file_path):#传递文件路径
        '''你的api_id AK SK'''
        api_id = '' #换成你自己的id
        api_key = ''#换成你自己的AK
        secret_key = ''#换成你自己的SK
    
        client = AipFace(api_id, api_key, secret_key)
    
        with open(file_path,'rb') as f:
            data = base64.b64encode(f.read())
    
        image = data.decode()
        
        imageType = "BASE64"
        option = {}
        option["face_field"] = 'beauty'
        '''调用人脸检测'''
        result = client.detect(image=image,image_type=imageType,options=option)
        #print(result)
        return result["result"]["face_list"][0]["beauty"]
    根据api官方文档,因为我们只要颜值检测,就只返回+beauty
    然后再构建文件路径的文件
    
    
    ```java
    在这里插入代码片
    

    import os
    from 接口 import face_rg

    path = ’ '#你想检测图片的上级目录
    #读取目录下所有文件,返回一个列表
    img_list = os.listdir(path)

    这样我们就可以获取./下所有文件了
    然后通过遍历构建图片路径

    for image in img_list:
          name = image.split('.')[0]
          #print(name)
          img_path = path + '/' +image
          #print(img_path)
    

    然后调用api接口下的函数整体如下,因为有可能会检测失败所以我们要异常扑获。

    score_dict = {}
    for image in img_list:
        try:
            name = image.split('.')[0]
            #print(name)
            img_path = path + '/' +image
            #print(img_path)
            face_score = face_rg(img_path)#beauty值
            score_dict[name] = face_score #空字典添加姓名和值
        except Exception as e:
            print('正在检测{} | 检测失败'.format(name))
        else:
            print('正在检测{} | 检测分数:{}'.format(name, face_score))
    

    最后排序

    #score_dict.items()  函数以列表返回可遍历的(键, 值) 元组数组。
    #lambda x:x[1] 取出(0)name:(1)score 的索引[1]分数
    #然后将分进行排序
    change_score = sorted(score_dict.items(), key=lambda x:x[1], reverse=True)#排序
    print(change_score)
    
    for i, j in enumerate(change_score):#i是序号 j是值(name,score)存在
        print("名字是:{} | 第{}名 | 分数:{}".format(change_score[i][0],i+1,change_score[i][1] ))
    

    然后愉快输出啦
    在这里插入图片描述
    排序:
    在这里插入图片描述
    哈哈哈,就到这里啦。

    cs