-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFaceAI.py
More file actions
99 lines (87 loc) · 3.16 KB
/
Copy pathFaceAI.py
File metadata and controls
99 lines (87 loc) · 3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import os
import glob
import base64
from aip import face
import os
import shutil
class FaceAI:
APP_ID = '119428005'
API_KEY = 'Ufc63J3mACpNHO4GxlvfHwYp'
S_KEY = '8TTnuOqOFqQnwnUzQTN7Q6rQOF2Qvk3E'
client = face.AipFace(APP_ID, API_KEY, S_KEY)
def get_file_content(file_path):
with open(file_path, 'rb') as f:
return base64.b64encode(f.read()).decode('utf-8')
def detect_face(client, img_base64):
options = {
'face_field': 'age,gender,beauty,angle',
'max_face_num': 1
}
return client.detect(img_base64, 'BASE64', options)
def getdata(idx, resp_json):
face = resp_json['result']['face_list'][0]
beauty = face['beauty']
angle = face['angle']
yaw = angle['yaw']
pitch = angle['pitch']
roll = angle['roll']
rec = [idx, beauty, yaw, pitch, roll]
print(f"{idx}: beauty={beauty}, yaw={yaw}, pitch={pitch}, roll={roll}")
return rec
def process_directory(self, loc):
patterns = [os.path.join(loc, '*.jpg'),
os.path.join(loc, '*.jpeg'),
os.path.join(loc, '*.png')]
# 收集所有匹配的文件
files = []
for p in patterns:
files.extend(glob.glob(p))
files.sort()
results = []
for idx, img_path in enumerate(files, start=1):
try:
b64 = self.get_file_content(img_path)
resp = self.detect_face(self.client, b64)
rec = self.getdata(idx, resp)
results.append(rec)
except Exception as e:
print(f"第 {idx} 张 ({img_path}) 处理失败:{e}")
return results
def parse_json(json):
"""
解析服务器返回的JSON数据
:param json:
:return: 解析出的颜值,如果监测失败返回-1
"""
# 判断是否成功
code = json['error_code']
if code == 0:
# 成功检测到人脸,返回研颜值分数(十分制)
beauty = int(json['result']['face_list'][0]['beauty'] / 10) + 1
face_shape = json['result']['face_list'][0]['face_shape']
landmark = json['result']['face_list'][0]['landmark']
glasses = json['result']['face_list'][0]['glasses']
eyes_instance = landmark[1]['x'] - landmark[0]['x']
mouth_instance = landmark[3]['y'] - landmark[2]['y']
proportion = eyes_instance / mouth_instance
else:
beauty = -1
face_shape = 'null'
landmark = 'null'
glasses = 'null'
eyes_instance = 'null'
mouth_instance = 'null'
result = (beauty, face_shape, proportion, glasses)
return result
if __name__ == '__main__':
imgpath = 'imgs'
keyword = input("请输入关键词: ")
loc = os.path.join(imgpath, 'test', keyword)
# if os.path.exists(loc):
# shutil.rmtree(loc)
os.makedirs(loc, exist_ok=True)
ai = FaceAI()
stats = ai.process_directory(loc)
print("批量处理完成,统计结果:")
for rec in stats:
print(rec)