from tkinter import filedialog |
import base64 |
import requests |
#图片列表 |
fileList = [] |
#选择图片函数 |
def selectPhoto(): |
file = filedialog.askopenfilename(initialdir = "C:/" , title = 'Choose an image.' ) # 图片路径 |
if len ( file ) > 0 : #判断是否选择图片“0”为取消 |
fileList.append( file ) |
print ( "分析中..." ) |
# 调用百度人脸识别接口,获取token值 |
def getToken(): |
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials' \ |
'&client_id=zZeG8xxXGQ0L6dvz6K4kqywI&client_secret=zlbT0qtEhcmNFQ54p2FAXcFfu1tELGtM' |
response = requests.get(host) |
content = response.json() |
content = content[ 'access_token' ] |
return content |
#获取人脸识别数据 |
def getData(): |
#1.网络请求地址 |
requestUrl = 'https://aip.baidubce.com/rest/2.0/face/v3/detect' |
#2.获取token |
token = getToken() |
params = { 'access_token' : token} |
#3.加密图片 |
for imgUrl in fileList: |
f = open (imgUrl, 'rb' ) |
temp = f.read() |
image = base64.b64encode(temp) |
# 请求的数据 |
data = { |
'image' :image, |
'image_type' : 'BASE64' , |
'face_field' : 'age,gender,face_shape' |
} |
#4.post网络请求 |
response = requests.post(requestUrl, params = params, data = data) |
#print('响应结果:', response) |
content = response.json() |
#print('解析结果:', content) |
age = content[ 'result' ][ 'face_list' ][ 0 ][ 'age' ] # 人脸得分 |
print ( '年龄:' , age) |
gender = content[ 'result' ][ 'face_list' ][ 0 ][ 'gender' ][ 'type' ] |
shape = content[ 'result' ][ 'face_list' ][ 0 ][ 'face_shape' ][ 'type' ] |
if gender = = 'male' : |
gender = '男' |
else : |
gender = '女' |
print ( '性别:' ,gender) |
if shape = = 'square' : |
shape = '国字脸' |
elif shape = = 'triangle' : |
shape = '瓜子脸' |
elif shape = = 'oval' : |
shape = '鹅蛋脸' |
elif shape = = 'heart' : |
shape = '心形脸' |
else : |
shape = '圆形脸' |
print ( '脸型:' ,shape) |
#存储数据 |
tempDict = { 'image' : imgUrl, 'age' : age, 'gender' :gender, 'shape' :shape} # 以key-value的形式存储 |
print ( "欢迎来到人脸识别系统" ) |
x = input ( "按回车选择一张带有人脸的图片:" ) |
if x = = "": |
selectPhoto() |
getData() |
else : |
exit() |
初级程序员
by: vvvv 发表于:2021-12-15 15:01:22 顶(1) | 踩(0) 回复
厉害啊666
网友回复
回复: 3666666666
顶(0) 踩(0) 2022-02-19 12:27:25
回复评论