Warlord-K commited on
Commit
9178542
1 Parent(s): 7c37b2e

Create face_recognition_system.py

Browse files
Files changed (1) hide show
  1. face_recognition_system.py +129 -0
face_recognition_system.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from ultralytics import YOLO
4
+ from arcface import ArcFace
5
+ import pickle
6
+ import os
7
+ from datetime import datetime
8
+
9
+ class FaceRecognitionSystem:
10
+ def __init__(self, database_path="face_database.pkl", confidence_threshold=0.5, similarity_threshold=2):
11
+ # Initialize YOLO for face detection
12
+ self.yolo_model = YOLO('https://github.com/akanametov/yolo-face/releases/download/v0.0.0/yolov11s-face.pt')
13
+
14
+ # Initialize ArcFace for face recognition
15
+ self.face_rec = ArcFace.ArcFace("model.tflite")
16
+
17
+ # Thresholds
18
+ self.confidence_threshold = confidence_threshold
19
+ self.similarity_threshold = similarity_threshold
20
+
21
+ # Load or create face database
22
+ self.database_path = database_path
23
+ self.face_database = self.load_database()
24
+
25
+ def load_database(self):
26
+ if os.path.exists(self.database_path):
27
+ with open(self.database_path, 'rb') as f:
28
+ return pickle.load(f)
29
+ return {}
30
+
31
+ def save_database(self):
32
+ with open(self.database_path, 'wb') as f:
33
+ pickle.dump(self.face_database, f)
34
+
35
+ def add_face_to_database(self, name, frame):
36
+ """Add a new face to the database"""
37
+ try:
38
+ embedding = self.face_rec.calc_emb(frame)
39
+ self.face_database[name] = embedding
40
+ self.save_database()
41
+ return True
42
+ except Exception as e:
43
+ print(f"Error adding face to database: {e}")
44
+ return False
45
+
46
+ def find_closest_match(self, embedding):
47
+ """Find the closest matching face in the database"""
48
+ if not self.face_database:
49
+ return "Unknown", 1.0
50
+
51
+ min_distance = 10000
52
+ closest_name = "Unknown"
53
+
54
+ for name, stored_embedding in self.face_database.items():
55
+ distance = self.face_rec.get_distance_embeddings(embedding, stored_embedding)
56
+ if distance < min_distance:
57
+ min_distance = distance
58
+ closest_name = name
59
+
60
+ return closest_name, min_distance
61
+
62
+ def process_frame(self, frame):
63
+ """Process a single frame"""
64
+ # Run YOLO detection
65
+ results = self.yolo_model(frame, verbose=False)[0]
66
+
67
+ # Process each detected face
68
+ for detection in results.boxes.data:
69
+ x1, y1, x2, y2, conf, _ = detection
70
+
71
+ if conf < self.confidence_threshold:
72
+ continue
73
+
74
+ # Convert coordinates to integers
75
+ x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
76
+
77
+ # Extract face region
78
+ face_region = frame[y1:y2, x1:x2]
79
+
80
+ try:
81
+ # Calculate face embedding
82
+ embedding = self.face_rec.calc_emb(face_region)
83
+
84
+ # Find closest match
85
+ name, distance = self.find_closest_match(embedding)
86
+
87
+ # Determine if match is close enough
88
+ if distance > self.similarity_threshold:
89
+ name = "Unknown"
90
+
91
+ # Draw rectangle and name
92
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
93
+ cv2.putText(frame, f"{name} ({conf:.2f})",
94
+ (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
95
+ 0.5, (0, 255, 0), 2)
96
+
97
+ except Exception as e:
98
+ print(f"Error processing face: {e}")
99
+
100
+ return frame
101
+
102
+ def run(self):
103
+ """Run the face recognition system on webcam feed"""
104
+ cap = cv2.VideoCapture(0)
105
+
106
+ while True:
107
+ ret, frame = cap.read()
108
+ if not ret:
109
+ break
110
+
111
+ # Process the frame
112
+ processed_frame = self.process_frame(frame)
113
+
114
+ # Display the result
115
+ cv2.imshow('Face Recognition', processed_frame)
116
+
117
+ key = cv2.waitKey(1)
118
+ if key == ord('q'):
119
+ break
120
+ elif key == ord('a'):
121
+ # Add new face to database
122
+ name = input("Enter name for new face: ")
123
+ if self.add_face_to_database(name, frame):
124
+ print(f"Successfully added {name} to database")
125
+ else:
126
+ print("Failed to add face to database")
127
+
128
+ cap.release()
129
+ cv2.destroyAllWindows()