The attendance system we are building utilizes the power of face recognition to automate the process of tracking and recording attendance. This system identifies individuals by analyzing their facial features and matches them with a database of known faces. The process involves collecting data, recognizing faces, and marking attendance.
To get started, we need to install the necessary libraries. Open a terminal or command prompt and run the following command:
pip install opencv-python numpy face_recognition
This will install three libraries:
opencv-python
numpy
face_recognition
First of all, we need to prepare our dataset. The dataset consists of images of individuals whose attendance we wish to track. Create a directory named "Gallery" and place individual images in it. Each image should be named after the person it represents. Each image in the dataset represents a person whose attendance we want to track. Here is the reference "Gallery" that we will be using:
After data collection, we need to load images of individuals, extract their facial encodings, and associate them with their respective names.
def collect_data(data_dir):known_faces = []known_names = []for name in os.listdir(data_dir):img_path = os.path.join(data_dir, name)img = face_recognition.load_image_file(img_path)encodings = face_recognition.face_encodings(img)if len(encodings) > 0:known_faces.append(encodings[0])known_names.append(name)return known_faces, known_names
The collect_data
function takes a directory path as input, iterates through image files, and processes each image to extract facial encodings. Here is a brief description:
Line 2: We initialize a list to store facial encodings of known individuals.
Line 3: We initialize a list to store the corresponding names of known individuals.
Lines 5–6: We iterate through files in the specified directory.
Line 7: We load an image using the face_recognition
library.
Line 8: We extract facial encodings from the loaded image for future matching.
Lines 9–11: We check if any encodings were extracted, then store the first encoding and the associated name in respective lists.
The core functionality of our attendance system lies in the face recognition step. We will define a function that takes a list of known facial encodings, corresponding names, and the path to an image with unknown faces. In this function, we need to identify faces in the image, calculate face distances, and determine the best match to mark attendance.
def recognize_faces(known_faces, known_names, unknown_image_path):unknown_image = face_recognition.load_image_file(unknown_image_path)unknown_face_locations = face_recognition.face_locations(unknown_image)unknown_face_encodings = face_recognition.face_encodings(unknown_image, unknown_face_locations)for (top, right, bottom, left), face_encoding in zip(unknown_face_locations, unknown_face_encodings):match_scores = face_recognition.face_distance(known_faces, face_encoding)best_match_index = np.argmin(match_scores)name = known_names[best_match_index]mark_attendance(name)
Here is a brief description of the code above:
Line 2: We load the image with unknown faces using the face_recognition
library.
Lines 3–4: We identify face locations in the unknown image and then extract facial encodings for the detected locations using face_recognition
library.
Line 5: The code iterates through detected face locations and their encodings.
Lines 6–8: face_recognition.face_distance(known_faces, face_encoding)
calculates the face distances between the unknown face and known faces and np.argmin(match_scores)
identifies the index of the best matching known face.
Lines 9–10: The name associated with the best match is used to mark attendance using the mark_attendance
function.
We used the mark_attendance
function in the previous step. Let's define this function by implementing attendance recording logic. We will record attendance in a
def mark_attendance(name):attendance_file = "attendance.csv"current_datetime = datetime.datetime.now()date_str = current_datetime.strftime("%Y-%m-%d")time_str = current_datetime.strftime("%H:%M:%S")with open(attendance_file, mode='a') as file:fieldnames = ['Name', 'Date', 'Time']writer = csv.DictWriter(file, fieldnames=fieldnames)writer.writerow({'Name': name, 'Date': date_str, 'Time': time_str})print("Name: ",name,"\nDate: ",date_str,"\nTime: ",time_str)
Here is a brief description of the above code:
Line 2: attendance_file
: We initialize the path to the CSV file where attendance records are stored.
Lines 4–6: datetime.datetime.now()
retrieves the current date and time. current_datetime.strftime("%Y-%m-%d")
then formats the date as "YYYY-MM-DD" while current_datetime.strftime("%H:%M:%S")
formats the time as "HH:MM:SS".
Lines 8–11: We open the file in append('a'
) mode and initialize the field names. The csv.DictWriter
is then used to write attendance details to the CSV file.
To run the face recognition attendance system, first, organize your input images in a folder. Carefully name the files in the name of the person. Then you can run the Python code.
Here is a sample implementation using a saved image:
import osimport cv2import csvimport datetimeimport face_recognitionimport numpy as np# Data Collectiondef collect_data(data_dir):known_faces = []known_names = []for name in os.listdir(data_dir):img_path = os.path.join(data_dir, name)img = face_recognition.load_image_file(img_path)encodings = face_recognition.face_encodings(img)if len(encodings) > 0:known_faces.append(encodings[0])known_names.append(name)return known_faces, known_names# Attendance Recordingdef mark_attendance(name):attendance_file = "attendance.csv"current_datetime = datetime.datetime.now()date_str = current_datetime.strftime("%Y-%m-%d")time_str = current_datetime.strftime("%H:%M:%S")file_exists = os.path.isfile(attendance_file)with open(attendance_file, mode='a') as file:fieldnames = ['Name', 'Date', 'Time']writer = csv.DictWriter(file, fieldnames=fieldnames)if not file_exists:writer.writeheader()print("Name: ",name,"\nDate: ",date_str,"\nTime: ",time_str)writer.writerow({'Name': name, 'Date': date_str, 'Time': time_str})# Face Recognitiondef recognize_faces(known_faces, known_names, unknown_image_path):unknown_image = face_recognition.load_image_file(unknown_image_path)unknown_face_locations = face_recognition.face_locations(unknown_image)unknown_face_encodings = face_recognition.face_encodings(unknown_image, unknown_face_locations)for (top, right, bottom, left), face_encoding in zip(unknown_face_locations, unknown_face_encodings):match_scores = face_recognition.face_distance(known_faces, face_encoding)best_match_index = np.argmin(match_scores)name = known_names[best_match_index]mark_attendance(name)dataset_dir = "Gallery"known_faces, known_names = collect_data(dataset_dir)unknown_image_path = "Gallery/Emma.png"recognize_faces(known_faces, known_names, unknown_image_path)
Note: You can replace the image read code with capturing the image through camera by following this.
This project demonstrates the potential of computer vision technology in automating attendance management processes. The implementation of a face recognition attendance system offers numerous benefits in various domains, including educational institutions, workplaces, and events. This system not only saves time but also enhances accuracy and data integrity. By using facial recognition technology, we can identify individuals based on unique facial features, eliminating the need for manual entry and reducing the chances of errors.