-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
116 lines (87 loc) · 3.78 KB
/
app.py
File metadata and controls
116 lines (87 loc) · 3.78 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import os
import pickle
import numpy as np
import face_recognition
import cv2
from flask import Flask, request, render_template, send_from_directory
from werkzeug.utils import secure_filename
# Initialize Flask app
app = Flask(__name__)
# Paths
UPLOAD_FOLDER = "uploads"
DATASET_FOLDER = "dataset"
ENCODING_FILE = "encodings.pkl"
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg","webp","jfif","pjp","svg","avif"}
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Load face encodings from the dataset
def load_encodings():
"""Loads precomputed face encodings from the file."""
if not os.path.exists(ENCODING_FILE):
raise FileNotFoundError(f"Encoding file '{ENCODING_FILE}' not found.")
with open(ENCODING_FILE, "rb") as f:
return pickle.load(f)
try:
dataset_encodings, dataset_filenames = load_encodings()
except FileNotFoundError as e:
print(f"[ERROR] {e}")
dataset_encodings, dataset_filenames = None, None
def allowed_file(filename):
"""Check if the uploaded file has a valid image extension."""
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def recognize_face(query_image_path, threshold=0.5):
"""Finds matching faces with strict distance filtering."""
try:
# Ensure encodings are loaded
if dataset_encodings is None or dataset_filenames is None:
return [], "Face encodings not available."
# Load query image
query_image = cv2.imread(query_image_path)
if query_image is None:
return [], "Error: Could not load image."
query_image = cv2.cvtColor(query_image, cv2.COLOR_BGR2RGB)
# Detect and encode face
query_face_locations = face_recognition.face_locations(query_image, model="hog")
if not query_face_locations:
return [], "No face detected in uploaded image."
query_encodings = face_recognition.face_encodings(query_image, query_face_locations)
if not query_encodings:
return [], "No encoding found in query image."
query_encoding = query_encodings[0]
# Compute distances
distances = np.linalg.norm(dataset_encodings - query_encoding, axis=1)
# Get closest matches
matches = [(dataset_filenames[i], d) for i, d in enumerate(distances) if d < threshold]
# Sort matches by best similarity
matches.sort(key=lambda x: x[1])
return matches, None # Return matches and no error
except Exception as e:
return [], str(e)
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
if "file" not in request.files:
return render_template("index.html", error="No file uploaded.")
file = request.files["file"]
if file.filename == "":
return render_template("index.html", error="No file selected.")
if not allowed_file(file.filename):
return render_template("index.html", error="Invalid file type. Only JPG, JPEG, and PNG are allowed.")
# Secure filename and save file
filename = secure_filename(file.filename)
file_path = os.path.join(UPLOAD_FOLDER, filename)
file.save(file_path)
# Perform face recognition
matches, error = recognize_face(file_path)
if error:
return render_template("index.html", error=error)
return render_template("index.html", matches=matches, query_image=filename)
return render_template("index.html", matches=None, query_image=None)
@app.route("/uploads/<filename>")
def uploaded_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
@app.route("/dataset/<filename>")
def dataset_file(filename):
return send_from_directory(DATASET_FOLDER, filename)
if __name__ == "__main__":
app.run(debug=True)