ani0226 commited on
Commit
4b4f0b9
·
verified ·
1 Parent(s): 7a3eb3f

Create face_recognition.py

Browse files
Files changed (1) hide show
  1. face_recognition.py +67 -0
face_recognition.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from PIL import Image
3
+ import tensorflow as tf # Or import your PyTorch modules
4
+
5
+ # --- Load your trained HTCNN model ---
6
+ try:
7
+ htcnn_model = tf.keras.models.load_model('htcnn_model.h5') # Replace with your model path
8
+ except Exception as e:
9
+ print(f"Error loading HTCNN model: {e}")
10
+ htcnn_model = None
11
+
12
+ def extract_embedding(face_image):
13
+ """
14
+ Extracts the feature embedding from a face image using the HTCNN model.
15
+
16
+ Args:
17
+ face_image (numpy.ndarray): The cropped face image.
18
+
19
+ Returns:
20
+ numpy.ndarray: The feature embedding, or None if an error occurs.
21
+ """
22
+ if htcnn_model is None:
23
+ print("HTCNN model not loaded. Cannot extract embedding.")
24
+ return None
25
+
26
+ # Preprocess the face image (resize, normalize, etc.) as required by your model
27
+ resized_face = cv2.resize(face_image, (160, 160)) # Example size, adjust as needed
28
+ normalized_face = resized_face / 255.0 # Example normalization
29
+
30
+ # Ensure the input has the correct batch dimension
31
+ embedding = htcnn_model.predict(np.expand_dims(normalized_face, axis=0))[0]
32
+ return embedding
33
+
34
+ def recognize_face(face_image, face_embeddings_db, threshold=0.6):
35
+ """
36
+ Recognizes a face by comparing its embedding with the embeddings in the database.
37
+
38
+ Args:
39
+ face_image (numpy.ndarray): The cropped face image.
40
+ face_embeddings_db (dict): Dictionary of known face embeddings (name: embedding).
41
+ threshold (float): The similarity threshold for recognition.
42
+
43
+ Returns:
44
+ str or None: The name of the recognized person, or None if no match is found.
45
+ """
46
+ embedding = extract_embedding(face_image)
47
+ if embedding is None:
48
+ return None
49
+
50
+ min_distance = float('inf')
51
+ recognized_identity = None
52
+
53
+ for name, stored_embedding in face_embeddings_db.items():
54
+ # Calculate the distance (e.g., Euclidean distance) between the embeddings
55
+ distance = np.linalg.norm(embedding - stored_embedding)
56
+ if distance < min_distance:
57
+ min_distance = distance
58
+ recognized_identity = name
59
+
60
+ if min_distance < threshold:
61
+ return recognized_identity
62
+ else:
63
+ return None
64
+
65
+ if __name__ == '__main__':
66
+ # Example usage (requires having a trained HTCNN model and a database)
67
+ pass