stm32-fmt-code/access_control_python_server/app.py

65 lines
2.0 KiB
Python
Raw Normal View History

2023-09-22 18:37:02 +00:00
from flask import Flask, request
import json
import cv2
import base64
import numpy as np
2023-09-22 19:08:10 +00:00
from deepface import DeepFace
2023-09-24 18:30:29 +00:00
import face_recognition as face
import os
2023-09-22 18:37:02 +00:00
app = Flask(__name__)
2023-09-24 18:30:29 +00:00
face_encodings: list = []
face_names: list = []
def init_face() -> None:
for file in os.scandir("faces"):
face_name = file.name.split('.')
face_name = '.'.join(face_name[0:len(face_name)-1])
face_names.append(face_name)
face_image = face.load_image_file(file.path)
face_encodings.append(face.face_encodings(face_image)[0])
2023-09-22 18:37:02 +00:00
2023-09-24 18:47:30 +00:00
init_face()
2023-09-22 18:37:02 +00:00
@app.route('/')
2023-09-24 18:30:29 +00:00
def home() -> str:
2023-09-22 18:37:02 +00:00
return '<h1>Ching Chong Bing Bong Ding Dong!!</h1>'
@app.route('/process_image', methods=['POST'])
2023-09-24 18:30:29 +00:00
def process_image() -> str:
2023-09-22 18:37:02 +00:00
print(request.data)
request_data = json.loads(request.data.decode("utf-8"))
img_nparr = np.frombuffer(base64.b64decode(request_data['image']), np.uint8)
img = cv2.imdecode(img_nparr,cv2.IMREAD_COLOR)
2023-09-22 19:39:07 +00:00
try:
racist_detector = DeepFace.analyze(img)
return racist_detector
except:
return []
2023-09-22 18:37:02 +00:00
2023-09-24 18:30:29 +00:00
@app.route('/identify_face', methods=['POST'])
def identify_face() -> str:
request_data = json.loads(request.data.decode("utf-8"))
target_confidence: float = request_data['target_confidence']
img_nparr = np.frombuffer(base64.b64decode(request_data['image']), np.uint8)
img = cv2.imdecode(img_nparr,cv2.IMREAD_COLOR)
img = cv2.resize(img, (0,0), fx=0.5,fy=0.5)
img = np.ascontiguousarray(img[:, :, ::-1])
face_locations = face.face_locations(img)
face_encodings_img = face.face_encodings(img, face_locations)
response: list = []
for face_encoding in face_encodings_img:
face_distances = face.face_distance(face_encodings, face_encoding)
index = np.argmin(face_distances)
confidence = 1-face_distances[index]
if confidence >= target_confidence:
response.append({'name':face_names[index],'confidence': confidence})
return response
2023-09-22 18:37:02 +00:00
if __name__ == '__main__':
app.run()