Update app.py
Browse files
app.py
CHANGED
|
@@ -1,50 +1,49 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import numpy as np
|
| 3 |
-
import cv2
|
| 4 |
-
import
|
| 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 |
-
predicted_name
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
iface.launch()
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import cv2
|
| 4 |
+
from sklearn.metrics.pairwise import euclidean_distances
|
| 5 |
+
|
| 6 |
+
# Load model files
|
| 7 |
+
mean_face = np.load("model/mean_face.npy")
|
| 8 |
+
eigenfaces = np.load("model/eigenfaces.npy")
|
| 9 |
+
projections = np.load("model/projections.npy")
|
| 10 |
+
labels = np.load("model/labels.npy")
|
| 11 |
+
label_names = np.load("model/label_names.npy")
|
| 12 |
+
with open("model/img_shape.txt", "r") as f:
|
| 13 |
+
img_h, img_w = map(int, f.read().strip().split())
|
| 14 |
+
|
| 15 |
+
# Distance threshold (tune based on performance)
|
| 16 |
+
THRESHOLD = 8000
|
| 17 |
+
|
| 18 |
+
def recognize_face_from_frame(frame):
|
| 19 |
+
# Convert to grayscale
|
| 20 |
+
img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 21 |
+
# Resize to training size
|
| 22 |
+
img = cv2.resize(img, (img_w, img_h))
|
| 23 |
+
# Flatten and normalize
|
| 24 |
+
img_flat = img.flatten()
|
| 25 |
+
img_centered = img_flat - mean_face
|
| 26 |
+
# Project to eigenface space
|
| 27 |
+
projected = np.dot(img_centered, eigenfaces.T)
|
| 28 |
+
|
| 29 |
+
# Compare with stored projections
|
| 30 |
+
dists = euclidean_distances([projected], projections)[0]
|
| 31 |
+
min_dist = np.min(dists)
|
| 32 |
+
min_index = np.argmin(dists)
|
| 33 |
+
|
| 34 |
+
if min_dist < THRESHOLD:
|
| 35 |
+
predicted_name = label_names[labels[min_index]]
|
| 36 |
+
return f"🧠 Predicted: {predicted_name} (distance: {min_dist:.2f})"
|
| 37 |
+
else:
|
| 38 |
+
return "😕 Unknown face"
|
| 39 |
+
|
| 40 |
+
# Web UI
|
| 41 |
+
iface = gr.Interface(
|
| 42 |
+
fn=recognize_face_from_frame,
|
| 43 |
+
inputs=gr.Camera(),
|
| 44 |
+
outputs="text",
|
| 45 |
+
title="🔍 EigenFace Recognition",
|
| 46 |
+
description="Scan your face. If you're in the dataset, the system will recognize you."
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
iface.launch()
|
|
|