导入库
from aip import AipFace
import base64
import time
from PIL import Image,ImageDraw,ImageFont
from openpyxl import load_workbook
用到百度ai的人脸识别aip
""" 你的 APPID AK SK """
APP_ID = '你的appID'
API_KEY = '你的AK'
SECRET_KEY = '你的SK'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
导入图片
time.sleep(2)
filename='pic.jpg'#你的图片的名字
fo=open(filename,'rb')
image=fo.read()
fo.close()
一些百度ai的参数设置和结果返回值
image = str(base64.b64encode(image), 'utf-8')
image_type = 'BASE64'
options = {}
options['face_field']= "age,gender,beauty,face_shape,emotion,glasses"
options['max_face_num']=10
options["face_type"] = "LIVE"#详情参考百度ai人脸识别的apk文件
result = client.detect(image, image_type,options)
#print(result)"""经过百度ai返回的结果的数组"""
对字体和图片的处理(之后要导入图片,在图片上框选出人脸,还要在图片上显示文字)
img = Image.open(filename)
draw=ImageDraw.Draw(img)
ttfont = ImageFont.truetype("C:/WINDOWS/Fonts/simsun.ttc",23)#字体的路径
对前文返回的百度ai的结果数组“result”进行处理
#性别
for face in result['result']['face_list']:
if face['gender']['type'] == 'male':
gender = "男"
else:
gender = "女"
age = face['age']
location = face['location']
beauty = face['beauty']
#脸型
face_shape = face['face_shape']
if face['face_shape']['type'] == 'square':
face_shape = '正方形'
elif face['face_shape']['type'] == 'triangle':
face_shape = '三角形'
elif face['face_shape']['type'] == 'oval':
face_shape = '椭圆'
elif face['face_shape']['type'] == 'heart':
face_shape = '心形'
else:
face_shape = '圆形'
#是否戴眼镜
if face['glasses']['type'] == 'none':
glasses = "没戴眼镜"
else:
glasses = "戴眼镜"
#情绪
emotion = face['emotion']
if face['emotion']['type'] == 'angry':
emotion = '愤怒'
elif face['emotion']['type'] == 'disgust':
emotion = '厌恶'
elif face['emotion']['type'] == 'fear':
emotion = '恐惧'
elif face['emotion']['type'] == 'sad':
emotion = '伤心'
elif face['emotion']['type'] == 'surprise':
emotion = '惊讶'
elif face['emotion']['type'] == 'happy':
emotion = '高兴'
else:
emotion = '无情绪'
#人脸位置
x1 = face['location']['left']
y1 = face['location']['top']
x2 = x1 + face['location']['width']
y2 = y1 + face['location']['height']
draw.rectangle((x1, y1, x2, y2), outline="yellow")#通过人脸位置的坐标画框
x = x2 + 5 #x2是边框的右坐标
draw.text([x+5, y1+0], "性别:" + gender, "black", font=ttfont)
draw.text([x+5, y1+20], "年龄:" + str(age), "black", font=ttfont)
draw.text([x+5, y1+40], "颜值:" + str(beauty), "black", font=ttfont)
draw.text([x+5, y1+60], "表情:" + str(emotion), "black", font=ttfont)
draw.text([x+5, y1+80], "脸型:" + str(face_shape), "black", font=ttfont)
draw.text([x + 5, y1 + 100], "眼镜:" + str(glasses), "black", font=ttfont)
print("性别:" + gender)
print("年龄:" + str(age))
print("颜值:" + str(beauty) )
print("情绪:" + str(emotion))
print("脸型:" + str(face_shape))
print(glasses+"\n")
img.show()
保存结果到“jieguo.xlsx”没有新建的需要新建一个xlsl的excel文件
wb = load_workbook('jieguo.xlsx')
sheet = wb.active
sheet.append(['性别', '年龄', '颜值', '情绪', '是否戴眼镜', '脸型'])
sheet.append([gender, str(age), str(beauty), str(emotion), glasses, face_shape])
wb.save('jieguo.xlsx')
结果示例如图: