app.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import os
  2. import tempfile
  3. import face_recognition
  4. from flask import Flask, request, jsonify
  5. def create_app():
  6. app = Flask(__name__)
  7. def init_app():
  8. known_faces_dir = "./known_faces"
  9. print(known_faces_dir)
  10. load_known_faces(known_faces_dir)
  11. init_app()
  12. @app.route('/')
  13. def hello_world(): # put application's code here
  14. return 'Hello World!'
  15. @app.route('/recognize', methods=['POST'])
  16. def recognize():
  17. if 'file' not in request.files:
  18. return jsonify({'error': 'No file part'}), 400
  19. file = request.files['file']
  20. if file.filename == '':
  21. return jsonify({'error': 'No selected file'}), 400
  22. if file:
  23. # 创建一个临时文件保存上传的文件
  24. temp_file = tempfile.NamedTemporaryFile(delete=False)
  25. file.save(temp_file.name)
  26. results = find_faces_in_image(temp_file.name)
  27. os.remove(temp_file.name) # 删除临时文件
  28. return jsonify(results)
  29. return app
  30. # 全局变量存储已知人脸编码和名称
  31. known_face_encodings = []
  32. known_face_names = []
  33. def load_known_faces(known_faces_dir):
  34. global known_face_encodings, known_face_names
  35. known_face_encodings = []
  36. known_face_names = []
  37. for filename in os.listdir(known_faces_dir):
  38. if filename.endswith(".jpg") or filename.endswith(".png"):
  39. image_path = os.path.join(known_faces_dir, filename)
  40. image = face_recognition.load_image_file(image_path)
  41. face_encoding = face_recognition.face_encodings(image)[0]
  42. known_face_encodings.append(face_encoding)
  43. known_face_names.append(os.path.splitext(filename)[0])
  44. def find_faces_in_image(image_path):
  45. image = face_recognition.load_image_file(image_path)
  46. face_locations = face_recognition.face_locations(image)
  47. face_encodings = face_recognition.face_encodings(image, face_locations)
  48. found_faces = []
  49. for face_encoding in face_encodings:
  50. matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.35)
  51. if True in matches:
  52. first_match_index = matches.index(True)
  53. name = known_face_names[first_match_index]
  54. found_faces.append(name)
  55. if found_faces:
  56. return True
  57. else:
  58. return False
  59. if __name__ == '__main__':
  60. app = create_app()
  61. app.run()