import os import cv2 import torch import numpy as np import pandas as pd from…
- User
import os import cv2 import torch import numpy as np import pandas as pd from facenet_pytorch import InceptionResnetV1, MTCNN from datetime import datetime from PIL import Image from datetime import datetime
Initialize models
mtcnn = MTCNN(image_size=160, margin=0) model = InceptionResnetV1(pretrained='vggface2').eval() attendance_records = []
Create a folder to store face embeddings
if not os.path.exists('embeddings'): os.makedirs('embeddings')
Function to extract face embedding
def get_embedding(img_path): img = Image.open(img_path) img_cropped = mtcnn(img) if img_cropped is None: return None embedding = model(img_cropped.unsqueeze(0)).detach().numpy()[0] return embedding
Function to save embeddings
def register_student(name, img_path): embedding = get_embedding(img_path) if embedding is None: print("No face detected. Try another image.") return np.save(f'embeddings/{name}.npy', embedding) print(f'Registered {name}.')
Function to mark attendance
def mark_attendance(name): temp = [] timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') temp.append({'Name': name, 'Timestamp': timestamp}) print(f'Attendance marked for {name}.') print(temp) # Print current attendance records for debugging attendance_records.append(temp)
Function to recognize face
def recognize_face(img_path): embedding = get_embedding(img_path) if embedding is None: print("No face detected. Try another image.") return min_dist = float('inf') recognized_name = None for file in os.listdir('embeddings'): if file.endswith('.npy'): name = file.split('.')[0] stored_embedding = np.load(f'embeddings/{file}') dist = np.linalg.norm(stored_embedding - embedding) if dist < min_dist: min_dist = dist recognized_name = name if min_dist < 0.6: # Threshold for face recognition mark_attendance(recognized_name) else: print("Face not recognized. Try registering first.")
Example usage
Register students (run once for each student)
register_student('Divyesh', r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\compressedddd.jpg") # only once
register_student('Jane_Doe', 'path_to_jane_doe_image.jpg')
Recognize and mark attendance
recognize_face(r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\WIN_20240525_12_56_27_Pro.jpg")
recognize_face(r"C:\Users\divyr\OneDrive\Pictures\SavedPictures\wp2095574-ezgif.com-webp-to-jpg-converter.jpg")
print(attendance_records)
is this right
- Assistant
- User
where can i see the bench marks of the face authentication models
- Assistant
- User
i want a functionality i which the image has multiple faces, each face is identified and recognized and the attendance is done for present students
- Assistant