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)
in this currently i am working with a single image containing single person to ckeck for his attendance, what i want is to upload a single image with multiple faces and recognize each if they are present or not
- Assistant
- User
TypeError Traceback (most recent call last) Cell In[31], line 84 76 mark_attendance(recognized_names) 78 # Example usage 79 # Register students (run once for each student) 80 # register_student('Divyesh', r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\compressedddd.jpg") # only once 81 # register_student('Jane_Doe', 'path_to_jane_doe_image.jpg') 82 83 # Recognize and mark attendance ---> 84 recognize_faces(r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\WIN_20240525_12_56_27_Pro.jpg") 85 # recognize_faces(r"C:\Users\divyr\OneDrive\Pictures\SavedPictures\wp2095574-ezgif.com-webp-to-jpg-converter.jpg") 87 print(attendance_records)
Cell In[31], line 56 55 def recognize_faces(img_path): ---> 56 embeddings = get_embeddings(img_path) 57 if not embeddings: 58 print("No face detected. Try another image.")
Cell In[31], line 29 27 embeddings = [] 28 for box in boxes: ---> 29 img_cropped = mtcnn.extract(img, box, save_path=None) 30 embedding = model(img_cropped.unsqueeze(0)).detach().numpy()[0] ... 366 int(min(box[2] + margin[0] / 2, raw_image_size[0])), 367 int(min(box[3] + margin[1] / 2, raw_image_size[1])), 368 ]
TypeError: 'float' object is not subscriptable
- Assistant
- User
design a python program that is given input a image and the program recognizes all the faces and stores their embeddings
- Assistant
- User
TypeError Traceback (most recent call last) Cell In[33], line 52 50 # Example usage 51 image_path = r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\WIN_20240525_12_56_27_Pro.jpg" ---> 52 process_image(image_path) 54 # Any additional image can be processed similarly 55 # process_image(r"path_to_another_image.jpg")
Cell In[33], line 43 42 def process_image(img_path): ---> 43 embeddings = get_embeddings(img_path) 44 if not embeddings: 45 print('No faces detected.')
Cell In[33], line 27 24 for box in boxes: 25 # Convert the box coordinates to integers 26 box = [int(coord) for coord in box] ---> 27 img_cropped = mtcnn.extract(img, box) 28 # Compute the embedding 29 embedding = model(img_cropped.unsqueeze(0)).detach().numpy()[0]
TypeError: MTCNN.extract() missing 1 required positional argument: 'save_path'
- Assistant
- User
name the embeddings starnting from "i0001"
- Assistant