AI Free Projects

Face Recognition Attendance System Using Python

Face Detection and Recognition - Face Detection and Recognition

Face Recognition Attendance System Using Python

Managing attendance manually can become time-consuming when the number of students or employees increases. Calling names, maintaining registers, and preparing attendance reports can also introduce unnecessary mistakes. A face recognition attendance system provides a practical way to automate this process with a webcam and computer vision.

In this project, we will build a Face Recognition Attendance System using Python, OpenCV, Tkinter, and CSV. The application captures facial images, trains a recognition model, identifies registered users through a webcam, and records their attendance with the current date and time.

The project is suitable for students who want to understand how computer vision can be connected with a real-world attendance application. The original UPDATEGADH project also includes components such as face registration, LBPH training, automatic attendance, manual attendance, CSV reports, and optional MySQL storage. View the project reference.

Face Recognition Attendance System Using Python
Face Recognition Attendance System Using Python

Project Overview

Project NameFace Recognition Attendance System
Language/s UsedPython
LibrariesOpenCV, Tkinter, Pillow, Pandas
Recognition MethodLBPH Face Recognition
DatabaseCSV, Optional MySQL
Application TypeDesktop Application
DeveloperUPDATEGADH

How the Face Recognition Attendance System Works

The complete application follows three major stages. First, the system collects facial images for a registered person. Next, those images are processed to train the recognition model. Finally, the trained model is used with a webcam to recognize the person and record attendance.

  1. Register: Enter the person’s ID and name.
  2. Capture: The webcam collects multiple face images.
  3. Train: OpenCV’s LBPH recognizer learns from the captured images.
  4. Recognize: The webcam identifies registered faces.
  5. Attendance: The recognized person’s attendance is saved with date and time.

Project Features

  • Student or employee registration
  • Webcam-based face image collection
  • Face detection using Haar Cascade
  • LBPH-based face recognition
  • Real-time attendance marking
  • Automatic date and time recording
  • CSV attendance reports
  • Manual attendance option
  • Tkinter graphical interface
  • Optional MySQL database integration

Technologies Required

The application is developed with Python. OpenCV handles image processing, face detection, and recognition. Tkinter provides the desktop interface, while CSV files provide a simple way to store attendance information.

For the LBPH recognizer, install the OpenCV contrib package rather than relying only on the standard OpenCV package.

Project Folder Structure

FaceRecognitionAttendance/
│
├── main.py
├── capture_faces.py
├── train_model.py
├── attendance.py
├── requirements.txt
├── haarcascade_frontalface_default.xml
│
├── TrainingImage/
├── TrainingImageLabel/
├── StudentDetails/
└── Attendance/

The folders can be created automatically by the program, but keeping them separate makes the project easier to understand and maintain.

Step 1: Install Required Libraries

Create a project folder and open it in VS Code. Then open the terminal and install the required packages.

pip install opencv-contrib-python
pip install pillow
pip install pandas

Tkinter is normally included with standard Python installations on Windows. If your operating system does not include it, install it through the appropriate system package manager.

You can also create a requirements.txt file:

opencv-contrib-python
Pillow
pandas

Then install everything using:

pip install -r requirements.txt

Step 2: Face Image Capture Source Code

The following program opens the webcam and captures face images for a registered user. The images are saved inside the TrainingImage folder.

import cv2
import os

student_id = input("Enter Student ID: ")
name = input("Enter Student Name: ")

os.makedirs("TrainingImage", exist_ok=True)

camera = cv2.VideoCapture(0)
detector = cv2.CascadeClassifier(
    "haarcascade_frontalface_default.xml"
)

count = 0

while True:
    ret, frame = camera.read()

    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = detector.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        count += 1

        filename = f"TrainingImage/User.{student_id}.{count}.jpg"
        cv2.imwrite(filename, gray[y:y+h, x:x+w])

        cv2.rectangle(
            frame, (x, y), (x+w, y+h), (255, 0, 0), 2
        )

    cv2.imshow("Capture Face Images", frame)

    if cv2.waitKey(1) == 27 or count >= 50:
        break

camera.release()
cv2.destroyAllWindows()

print("Face images captured successfully.")

Move your face slightly during registration so that the training set contains different facial positions instead of nearly identical images.

Step 3: Train the Face Recognition Model

After collecting images, the next step is training. OpenCV’s Local Binary Patterns Histograms, commonly called LBPH, can be used for this type of recognition project.

import cv2
import os

recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(
    "haarcascade_frontalface_default.xml"
)

faces = []
ids = []

for filename in os.listdir("TrainingImage"):
    path = os.path.join("TrainingImage", filename)

    image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

    if image is None:
        continue

    parts = filename.split(".")
    user_id = int(parts[1])

    faces.append(image)
    ids.append(user_id)

if faces:
    recognizer.train(faces, __import__("numpy").array(ids))

    os.makedirs("TrainingImageLabel", exist_ok=True)

    recognizer.write(
        "TrainingImageLabel/Trainer.yml"
    )

    print("Training completed successfully.")
else:
    print("No training images found.")

The resulting Trainer.yml file contains the trained recognition data used during the attendance process.

Step 4: Real-Time Face Recognition and Attendance

Once training is complete, the webcam can be used to identify registered users. The recognized ID can then be written into an attendance CSV file.

import cv2
import csv
import os
from datetime import datetime

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("TrainingImageLabel/Trainer.yml")

detector = cv2.CascadeClassifier(
    "haarcascade_frontalface_default.xml"
)

os.makedirs("Attendance", exist_ok=True)

camera = cv2.VideoCapture(0)

marked_ids = set()

while True:
    ret, frame = camera.read()

    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = detector.detectMultiScale(gray, 1.2, 5)

    for (x, y, w, h) in faces:
        user_id, confidence = recognizer.predict(
            gray[y:y+h, x:x+w]
        )

        if confidence < 70 and user_id not in marked_ids:
            now = datetime.now()

            file_name = (
                "Attendance/"
                + now.strftime("%Y-%m-%d")
                + ".csv"
            )

            exists = os.path.exists(file_name)

            with open(
                file_name, "a", newline=""
            ) as file:

                writer = csv.writer(file)

                if not exists:
                    writer.writerow(
                        ["ID", "Date", "Time"]
                    )

                writer.writerow([
                    user_id,
                    now.strftime("%Y-%m-%d"),
                    now.strftime("%H:%M:%S")
                ])

            marked_ids.add(user_id)

        cv2.rectangle(
            frame, (x, y),
            (x+w, y+h),
            (0, 255, 0), 2
        )

        cv2.putText(
            frame,
            f"ID: {user_id}",
            (x, y-10),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.8,
            (0, 255, 0),
            2
        )

    cv2.imshow("Face Recognition Attendance", frame)

    if cv2.waitKey(1) == 27:
        break

camera.release()
cv2.destroyAllWindows()

Step 5: Create a Simple Tkinter Interface

A graphical interface makes the project easier to demonstrate. Instead of running every operation manually from the terminal, buttons can be provided for registration, training, and attendance.

import tkinter as tk
import subprocess

root = tk.Tk()
root.title("Face Recognition Attendance System")
root.geometry("500x350")

tk.Label(
    root,
    text="Face Recognition Attendance",
    font=("Arial", 20)
).pack(pady=25)

tk.Button(
    root,
    text="Capture Face Images",
    width=25,
    command=lambda: subprocess.run(
        ["python", "capture_faces.py"]
    )
).pack(pady=10)

tk.Button(
    root,
    text="Train Face Model",
    width=25,
    command=lambda: subprocess.run(
        ["python", "train_model.py"]
    )
).pack(pady=10)

tk.Button(
    root,
    text="Start Attendance",
    width=25,
    command=lambda: subprocess.run(
        ["python", "attendance.py"]
    )
).pack(pady=10)

root.mainloop()

How to Run the Complete Project

  1. Install Python and VS Code.
  2. Create the project folder.
  3. Install the required libraries.
  4. Place haarcascade_frontalface_default.xml in the project directory.
  5. Run the face capture program.
  6. Enter a unique ID and name.
  7. Capture facial images.
  8. Run the training program.
  9. Start the attendance program.
  10. Look at the camera and allow the system to recognize the registered face.
  11. Check the generated CSV file inside the Attendance folder.

Attendance Record

The generated CSV file can be opened using Microsoft Excel or another spreadsheet application. A typical record contains the person’s ID, attendance date, and attendance time.

ID,Date,Time
101,2026-09-23,10:15:21
102,2026-09-23,10:17:04

Optional MySQL Integration

The project can be extended from CSV storage to MySQL when centralized attendance management is required. The linked UPDATEGADH project describes MySQL as an optional storage layer for attendance records. :contentReference[oaicite:1]{index=1}

With a database, the application can maintain student information and attendance records in separate tables and generate reports based on student, date, subject, or attendance session.

Important Project Considerations

Face recognition systems should be tested under different lighting conditions because image quality can influence recognition results. Camera position, face angle, and training-image quality can also affect performance.

Because facial information is biometric data, real-world deployments should also consider consent, secure storage, access control, retention policies, and applicable privacy requirements. This student project is primarily intended for learning and demonstration.

Conclusion

The Face Recognition Attendance System demonstrates how Python and computer vision can be combined to solve a practical attendance problem. The project covers the complete basic workflow: collecting face images, training an LBPH model, recognizing faces through a webcam, and storing attendance records automatically.

It is also a useful foundation for further development. Students can add a MySQL database, student profiles, attendance reports, login authentication, subject management, monthly summaries, or a more advanced web dashboard as the project grows.

Complete Advance AI Topics: Click Here
SQL Tutorial:
Click Here
YT:- DecodeIT

Project Source and Reference

The project structure and feature set are based on the Face Recognition Based Attendance Management System published on UPDATEGADH, which describes Python, OpenCV, Tkinter, CSV attendance, optional MySQL integration, face capture, LBPH training, and automatic attendance. :contentReference[oaicite:2]{index=2}

View Complete Face Recognition Attendance Project on UPDATEGADH

FAQs

1. Which language is used for this project?

The project is developed using Python with OpenCV and Tkinter.

2. Which algorithm is used for face recognition?

The project uses OpenCV’s LBPH face recognition approach.

3. Can the project work with a webcam?

Yes. A webcam is used to capture training images and perform real-time recognition.

4. Where is attendance stored?

The basic implementation stores attendance in CSV files. MySQL can be added for centralized storage.

5. Why is opencv-contrib-python required?

The LBPH recognizer used in this project is available through OpenCV’s contrib modules.

6. Can new students be added?

Yes. A new ID can be registered and facial images can be captured before retraining the model.

7. Can this project be converted into a web application?

Yes. The recognition logic can be integrated with a Python web framework such as Django or Flask.

8. Is MySQL mandatory?

No. The basic project can use CSV files. MySQL is an optional extension for larger attendance systems.

Keywords: Face Recognition Attendance System Using Python, face recognition attendance with Python, face recognition project, face detection Python, OpenCV attendance system, face recognition source code, Python attendance project, face recognition based attendance system

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us