|
@@ -3,6 +3,7 @@ import tempfile
|
|
|
|
|
|
import face_recognition
|
|
|
import requests
|
|
|
+import logging
|
|
|
|
|
|
from flask import Flask, request, jsonify, json
|
|
|
|
|
@@ -59,14 +60,36 @@ def create_app():
|
|
|
results = return_json(find)
|
|
|
return results
|
|
|
return jsonify({'error': 'An error occurred'}), 500
|
|
|
+ return app
|
|
|
|
|
|
|
|
|
|
|
|
+# 调用 setup_logging 函数创建并配置日志记录器
|
|
|
|
|
|
|
|
|
- return app
|
|
|
+def setup_logging():
|
|
|
+ # 创建一个 Logger 对象
|
|
|
+ logger = logging.getLogger('sensitive-face-recognizer_logger')
|
|
|
+ # 设置日志级别,可根据需要调整为 DEBUG、INFO、WARNING、ERROR 或 CRITICAL
|
|
|
+ logger.setLevel(logging.INFO)
|
|
|
+
|
|
|
+ # 创建一个 Handler 对象,这里使用 StreamHandler 输出到控制台
|
|
|
+ console_handler = logging.StreamHandler()
|
|
|
+ # 创建一个文件处理器,输出到文件
|
|
|
+ file_handler = logging.FileHandler('app.log')
|
|
|
+
|
|
|
+ # 创建一个 Formatter 对象,设置日志格式
|
|
|
+ formatter = logging.Formatter('%(levelname)s - %(message)s')
|
|
|
+ console_handler.setFormatter(formatter)
|
|
|
+ file_handler.setFormatter(formatter)
|
|
|
|
|
|
+ # 将 Handler 添加到 Logger 中
|
|
|
+ logger.addHandler(console_handler)
|
|
|
+ logger.addHandler(file_handler)
|
|
|
|
|
|
+ return logger
|
|
|
+
|
|
|
+logger = setup_logging()
|
|
|
|
|
|
def return_json(find):
|
|
|
result = {
|
|
@@ -84,6 +107,7 @@ def return_json(find):
|
|
|
|
|
|
|
|
|
|
|
|
+
|
|
|
# 全局变量存储已知人脸编码和名称
|
|
|
known_face_encodings = []
|
|
|
known_face_names = []
|
|
@@ -102,6 +126,12 @@ def load_known_faces(known_faces_dir):
|
|
|
known_face_encodings.append(face_encoding)
|
|
|
known_face_names.append(os.path.splitext(filename)[0])
|
|
|
|
|
|
+def get_face_similarity(known_face_encoding, face_encoding):
|
|
|
+ # 计算两张脸的面部编码之间的距离
|
|
|
+ face_distances = face_recognition.face_distance([known_face_encoding], face_encoding)
|
|
|
+ # 计算相似度,使用 1 - 距离作为相似度
|
|
|
+ similarity = 1 - face_distances
|
|
|
+ return similarity
|
|
|
|
|
|
def find_faces_in_image(image_path):
|
|
|
image = face_recognition.load_image_file(image_path)
|
|
@@ -111,12 +141,13 @@ def find_faces_in_image(image_path):
|
|
|
found_faces = []
|
|
|
for face_encoding in face_encodings:
|
|
|
matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.35)
|
|
|
-
|
|
|
if True in matches:
|
|
|
first_match_index = matches.index(True)
|
|
|
name = known_face_names[first_match_index]
|
|
|
found_faces.append(name)
|
|
|
-
|
|
|
+ known_face_encoding = known_face_encodings[first_match_index]
|
|
|
+ similarity = get_face_similarity(known_face_encoding, face_encoding)
|
|
|
+ logger.info(f'image_name={name} similarity={similarity}')
|
|
|
if found_faces:
|
|
|
return True
|
|
|
else:
|