Shekarss commited on
Commit
29fa984
·
verified ·
1 Parent(s): 10c276d

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +42 -65
utils.py CHANGED
@@ -1,65 +1,42 @@
1
- import os
2
- import numpy as np
3
- import tensorflow as tf
4
- from PIL import Image
5
- import cv2
6
-
7
- IMG_SIZE = (105, 105) # same size you trained on
8
-
9
- # Load the trained Siamese model
10
- def load_model(model_path):
11
- model = tf.keras.models.load_model(model_path, custom_objects={'L1Dist': L1Dist})
12
- return model
13
-
14
- # Custom L1 distance layer (used in Siamese networks)
15
- class L1Dist(tf.keras.layers.Layer):
16
- def __init__(self, **kwargs):
17
- super().__init__()
18
-
19
- def call(self, input_embedding, validation_embedding):
20
- return tf.math.abs(input_embedding - validation_embedding)
21
-
22
- # Preprocess image for model input
23
- def preprocess(image):
24
- # Convert to numpy array if it's PIL
25
- if isinstance(image, Image.Image):
26
- image = np.array(image)
27
-
28
- image = cv2.resize(image, IMG_SIZE)
29
- image = image / 255.0
30
- image = np.expand_dims(image, axis=0) # (1, 105, 105, 3)
31
- return image
32
-
33
- # Verify identity by comparing input image to stored validation images
34
- def verify_identity(model, input_img, users_folder, detection_threshold=0.5):
35
- input_processed = preprocess(input_img)
36
-
37
- highest_score = 0
38
- identity = "Unknown"
39
-
40
- for user in os.listdir(users_folder):
41
- user_path = os.path.join(users_folder, user)
42
- if not os.path.isdir(user_path):
43
- continue
44
-
45
- for img_file in os.listdir(user_path):
46
- img_path = os.path.join(user_path, img_file)
47
-
48
- try:
49
- val_img = Image.open(img_path).convert('RGB')
50
- except:
51
- continue
52
-
53
- val_processed = preprocess(val_img)
54
-
55
- # Predict
56
- result = model.predict([input_processed, val_processed])[0][0]
57
-
58
- if result > highest_score:
59
- highest_score = result
60
- identity = user
61
-
62
- if highest_score < detection_threshold:
63
- return "User not recognized."
64
- else:
65
- return f"Verified: {identity} (Confidence: {highest_score:.2f})"
 
1
+ from facenet_pytorch import MTCNN, InceptionResnetV1
2
+ import torch
3
+ import numpy as np
4
+ from PIL import Image
5
+ import os
6
+
7
+ # Load models once
8
+ mtcnn = MTCNN(image_size=160, margin=20)
9
+ model = InceptionResnetV1(pretrained='vggface2').eval()
10
+
11
+ def preprocess(image):
12
+ face = mtcnn(Image.fromarray(image))
13
+ if face is None:
14
+ return None
15
+ with torch.no_grad():
16
+ embedding = model(face.unsqueeze(0)).squeeze().numpy()
17
+ return embedding
18
+
19
+ def verify_identity(_, input_image, user_dir, threshold=0.7):
20
+ input_embedding = preprocess(input_image)
21
+ if input_embedding is None:
22
+ return "❌ No face detected."
23
+
24
+ best_match = None
25
+ best_score = 0
26
+
27
+ for user in os.listdir(user_dir):
28
+ user_path = os.path.join(user_dir, user)
29
+ for file in os.listdir(user_path):
30
+ img_path = os.path.join(user_path, file)
31
+ registered_img = np.array(Image.open(img_path))
32
+ emb = preprocess(registered_img)
33
+ if emb is None:
34
+ continue
35
+ score = np.dot(input_embedding, emb) / (np.linalg.norm(input_embedding) * np.linalg.norm(emb))
36
+ if score > best_score:
37
+ best_match, best_score = user, score
38
+
39
+ if best_score >= threshold:
40
+ return f"✅ Match: {best_match} (Similarity: {best_score:.2f})"
41
+ else:
42
+ return f"❌ Unknown (Best Similarity: {best_score:.2f})"