根据照片图库,调用QQAI的人脸识别API,得到每个人的年龄、性别和魅力值并导出到excel

根据照片图库,调用QQAI的人脸识别API,得到每个人的年龄、性别和魅力值并导出到excel
优化了一下代码,使得单条记录的运行压缩到5秒左右,但想再减少就不清楚该怎么办了

import qqai
from os import path
import os
from datetime import datetime
from win32com.client import Dispatch

def file_path():
    global path_father_file
    path_father_file = path.abspath('..') + "\\"
    global path_pic_file
    path_pic_file = path_father_file + '上海电信员工照片\\浦东电信局'
    global path_this_file
    path_this_file = path.abspath('.') + "\\"
    global path_excel
    path_excel = path_this_file + '人脸识别信息.xlsx'

def get_pic_name():
    pic_list = []
    for pic in os.listdir(path_pic_file):
        pic_path = path_pic_file + '\\' + pic
        pic_list.append(pic_path)
    return pic_list

def name_and_id(filename):
    base_filename = path.basename(filename)
    if '-' in base_filename:
        name = base_filename.split('-')[0]
        id = base_filename.split('-')[1].replace('.jpg','')
        return name, id
    else:
        name = base_filename.replace('.jpg','')
        id = ''
        return name, id

def face_detect(filename):
    robot = qqai.vision.face.DetectFace(app_id, app_key)
    with open(filename, 'rb') as image_file:
        result = robot.run(image_file)
        # print(result)
        facelist = result['data']['face_list']
        # print(facelist)
        for value in facelist:
            gender = value['gender']
            if gender == 0:
                gender = '女'
            else:
                gender = '男'
            age = str(value['age']) + '岁'
            beauty = str(value['beauty']) + '分'
            return gender, age , beauty

def excel_pre():
    global xl
    xl = Dispatch("Excel.Application")
    xl.Visible = True  # True是显示, False是隐藏
    xl.DisplayAlerts = 0
    global excel_input
    excel_input = xl.Workbooks.Open(path_excel)
    global  sheet
    sheet = excel_input.Sheets('Sheet1')

def put_into_excel(i, name, id, gender, age, beauty):
    sheet.Cells(i + 2, 1).Value = name
    sheet.Cells(i + 2, 2).Value = id
    sheet.Cells(i + 2, 3).Value = gender
    sheet.Cells(i + 2, 4).Value = age
    sheet.Cells(i + 2, 5).Value = beauty

starttime = datetime.now()
"""腾讯AI开放平台 图片识别"""
app_id = '2110382408'
app_key = '******'
"""app_id , app_key 可以自己去腾讯AI开放平台注册,是免费的"""
file_path()
pic_list = get_pic_name()
excel_pre()
for i in range(len(pic_list)):
    filename = pic_list[i]
    name = name_and_id(filename)[0]
    id = name_and_id(filename)[1]
    gender = face_detect(filename)[0]
    age = face_detect(filename)[1]
    beauty = face_detect(filename)[2]
    put_into_excel(i, name, id, gender, age, beauty)
    print('已录入{}的信息,性别:{},年龄:{},颜值:{}'.format(name, gender, age, beauty))
excel_input.Save()
excel_input.Close()
xl.quit()
endtime = datetime.now()
total_time = (endtime - starttime).seconds
print(">>>成功录入信息{}条,总共耗时{}秒!".format(len(pic_list),total_time))

猜你喜欢

转载自blog.csdn.net/weixin_42029733/article/details/84843123