Overview
In this tutorial, we’ll create a facial recognition-based attendance system using Python. This project combines computer vision, machine learning, and database management to automate attendance tracking for workplaces, schools, or events. By the end, you’ll have a working application that can detect faces, recognize individuals, and log their attendance into a database.
Why Build a Facial Recognition Attendance System?
Traditional attendance systems like manual sign-ins or RFID cards are time-consuming and prone to errors. Facial recognition offers a fast, contactless, and reliable solution.
Step 1: Setting Up the Environment
Install Required Libraries
To get started, install the necessary Python libraries:
pip install opencv-python dlib face-recognition sqlite3
Step 2: Preparing the Dataset
Capture or collect images of individuals whose attendance you want to track. Organize the images in directories named after the individuals for easy labeling.
Example folder structure:
dataset/
John/
img1.jpg
img2.jpg
Sarah/
img1.jpg
img2.jpg
Step 3: Encoding Faces
Use the face_recognition library to encode faces from the dataset. This step creates unique numerical representations for each face.
import os
import face_recognition
import cv2
import pickle
# Path to dataset
DATASET_PATH = "dataset"
ENCODINGS_FILE = "encodings.pickle"
def encode_faces():
known_encodings = []
known_names = []
# Iterate through each person's folder
for person in os.listdir(DATASET_PATH):
person_path = os.path.join(DATASET_PATH, person)
if not os.path.isdir(person_path):
continue
# Process each image
for img_file in os.listdir(person_path):
img_path = os.path.join(person_path, img_file)
image = face_recognition.load_image_file(img_path)
face_encodings = face_recognition.face_encodings(image)
if face_encodings:
known_encodings.append(face_encodings[0])
known_names.append(person)
# Save encodings to a file
with open(ENCODINGS_FILE, "wb") as f:
pickle.dump({"encodings": known_encodings, "names": known_names}, f)
print("Encodings saved!")
encode_faces()
Step 4: Building the Attendance System
Load Encodings and Start the Webcam
Use the saved encodings to identify individuals in real-time.
import cv2
import face_recognition
import pickle
from datetime import datetime
# Load encodings
with open("encodings.pickle", "rb") as f:
data = pickle.load(f)
# Initialize webcam
video_capture = cv2.VideoCapture(0)
# Track attendance
attendance_log = set()
while True:
ret, frame = video_capture.read()
if not ret:
break
# Resize frame for faster processing
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_frame = small_frame[:, :, ::-1]
# Detect faces and compare
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(data["encodings"], face_encoding)
name = "Unknown"
if True in matches:
match_index = matches.index(True)
name = data["names"][match_index]
# Log attendance
if name not in attendance_log:
attendance_log.add(name)
print(f"{name} marked present at {datetime.now()}")
# Display bounding box and name
top, right, bottom, left = [v * 4 for v in face_location]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Show video feed
cv2.imshow("Attendance System", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
video_capture.release()
cv2.destroyAllWindows()
Step 5: Logging Attendance to a Database
Store the attendance data in an SQLite database for record-keeping.
import sqlite3
# Connect to SQLite database
conn = sqlite3.connect("attendance.db")
cursor = conn.cursor()
# Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS attendance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
def log_attendance(name):
cursor.execute("INSERT INTO attendance (name) VALUES (?)", (name,))
conn.commit()
# Update the webcam loop to log attendance
if name not in attendance_log:
attendance_log.add(name)
log_attendance(name)
print(f"{name} marked present in the database!")
Step 6: Scheduling the System
Use schedule to automate the script to run at specific times (e.g., every morning):
import schedule
import time
def start_system():
# Call your main attendance function here
pass
schedule.every().day.at("08:00").do(start_system)
while True:
schedule.run_pending()
time.sleep(1)
Advanced Features
- Email Notifications: Send attendance summaries via email using
smtplib. - Cloud Integration: Sync attendance records with Google Sheets or a cloud database.
- Face Mask Detection: Add a feature to detect whether individuals are wearing masks.
- Multi-Camera Support: Extend the system to support multiple cameras for large setups.