123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import os
- import tempfile
- import face_recognition
- from flask import Flask, request, jsonify
- def create_app():
- app = Flask(__name__)
- def init_app():
- known_faces_dir = "./known_faces"
- print(known_faces_dir)
- load_known_faces(known_faces_dir)
- init_app()
- @app.route('/')
- def hello_world(): # put application's code here
- return 'Hello World!'
- @app.route('/recognize', methods=['POST'])
- def recognize():
- if 'file' not in request.files:
- return jsonify({'error': 'No file part'}), 400
- file = request.files['file']
- if file.filename == '':
- return jsonify({'error': 'No selected file'}), 400
- if file:
- # 创建一个临时文件保存上传的文件
- temp_file = tempfile.NamedTemporaryFile(delete=False)
- file.save(temp_file.name)
- results = find_faces_in_image(temp_file.name)
- os.remove(temp_file.name) # 删除临时文件
- return jsonify(results)
- return app
- # 全局变量存储已知人脸编码和名称
- known_face_encodings = []
- known_face_names = []
- def load_known_faces(known_faces_dir):
- global known_face_encodings, known_face_names
- known_face_encodings = []
- known_face_names = []
- for filename in os.listdir(known_faces_dir):
- if filename.endswith(".jpg") or filename.endswith(".png"):
- image_path = os.path.join(known_faces_dir, filename)
- image = face_recognition.load_image_file(image_path)
- face_encoding = face_recognition.face_encodings(image)[0]
- known_face_encodings.append(face_encoding)
- known_face_names.append(os.path.splitext(filename)[0])
- def find_faces_in_image(image_path):
- image = face_recognition.load_image_file(image_path)
- face_locations = face_recognition.face_locations(image)
- face_encodings = face_recognition.face_encodings(image, face_locations)
- 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)
- if found_faces:
- return True
- else:
- return False
- if __name__ == '__main__':
- app = create_app()
- app.run()
|