face_recognizer.py
1.83 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
#!/usr/bin/env python3
"""
人脸检测脚本
用法:
python3 face_recognizer.py detect <image_path> # 检测人脸,返回 JSON
python3 face_recognizer.py encode <image_path> # 生成人脸 encoding,返回 JSON
依赖:face_recognition(pip install face_recognition)
如果未安装,返回空数组而不是崩溃。
"""
import sys
import json
import os
def detect(image_path):
try:
import face_recognition
img = face_recognition.load_image_file(image_path)
locs = face_recognition.face_locations(img)
encs = face_recognition.face_encodings(img, locs)
result = []
for i, (loc, enc) in enumerate(zip(locs, encs)):
top, right, bottom, left = loc
result.append({
'faceId': i,
'bbox': {'top': top, 'right': right, 'bottom': bottom, 'left': left},
'encoding': enc.tolist()
})
return result
except ImportError:
return [] # face_recognition 未安装时静默失败
except Exception as e:
return {'error': str(e)}
def encode_only(image_path):
try:
import face_recognition
img = face_recognition.load_image_file(image_path)
encs = face_recognition.face_encodings(img)
return [enc.tolist() for enc in encs]
except ImportError:
return []
except Exception as e:
return {'error': str(e)}
if __name__ == '__main__':
if len(sys.argv) < 3:
print(json.dumps([]))
sys.exit(0)
cmd = sys.argv[1]
path = sys.argv[2]
if not os.path.exists(path):
print(json.dumps({'error': f'File not found: {path}'}))
sys.exit(1)
if cmd == 'detect':
print(json.dumps(detect(path)))
elif cmd == 'encode':
print(json.dumps(encode_only(path)))
else:
print(json.dumps([]))