-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
78 lines (69 loc) · 2.92 KB
/
app.py
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
67
68
69
70
71
72
73
74
75
76
77
78
from flask import Flask, request, jsonify
import os
from PIL import Image
import numpy as np
import sqlite3
from deepface import DeepFace
from sklearn.metrics.pairwise import cosine_similarity
app = Flask(__name__)
# Function to get face encodings using DeepFace
def get_face_encodings_deepface(image_path):
encoding = DeepFace.represent(img_path=image_path, model_name='DeepFace_Encoding_DB', enforce_detection=True)
return encoding[0]['embedding']
# Function to insert face encoding into database
def insert_face_encoding(name, encoding):
conn = sqlite3.connect('face_recognition_25.db')
c = conn.cursor()
encoding_str = ','.join(map(str, encoding))
c.execute("INSERT INTO face_encodings (name, encoding) VALUES (?, ?)", (name, encoding_str))
conn.commit()
conn.close()
# Function to fetch all face encodings from database
def fetch_all_encodings(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT id, name, encoding FROM face_encodings")
rows = cursor.fetchall()
encodings = []
for row in rows:
id, name, encoding_str = row
encoding = np.fromstring(encoding_str, sep=',')
encodings.append((id, name, encoding))
conn.close()
return encodings
# Function to calculate cosine similarity between two face encodings
def calculate_similarity(enco1, enco2):
enco1_array = np.array(enco1) if not isinstance(enco1, np.ndarray) else enco1
enco2_array = np.array(enco2) if not isinstance(enco2, np.ndarray) else enco2
enco1_reshaped = enco1_array.reshape(1, -1)
enco2_reshaped = enco2_array.reshape(1, -1)
similarity_score = cosine_similarity(enco1_reshaped, enco2_reshaped)
return similarity_score
@app.route('/')
def home():
return 'DeepFace Recognition API V1'
# API endpoint for adding a new face encoding
@app.route('/add_face_encoding', methods=['POST'])
def add_face_encoding():
data = request.files['image']
name = request.form['name']
data.save('temp_img.jpg')
encoding = get_face_encodings_deepface('temp_img.jpg')
insert_face_encoding(name, encoding)
return jsonify({'message': 'Face encoding added successfully'})
# API endpoint for recognizing a face
@app.route('/recognize_face', methods=['POST'])
def recognize_face():
data = request.files['image']
name = request.form['name']
data.save('temp_img.jpg')
encoding = get_face_encodings_deepface('temp_img.jpg')
all_encodings = fetch_all_encodings('face_recognition_25.db')
for row in all_encodings:
_, existing_name, existing_encoding = row
similarity = calculate_similarity(encoding, existing_encoding)[0][0]
if similarity >= 0.6:
return jsonify({'message': f'Face recognized as {existing_name}', 'similarity': similarity, 'embedding': existing_encoding.tolist()})
return jsonify({'message': 'Face not recognized', 'embedding': []})
if __name__ == '__main__':
app.run(debug=True)