Face Recognition Based Attendance System Using Python

I have undertaken the development of a project called “Facial-Recognition-Attendance,” in which we are implementing a real-time attendance system utilizing Python.

You can also check the project on Github:


Face Recognition Based Attendance System Using Python
Face Recognition Based Attendance System Interface

Step 1: Project Introduction

This project implements a real-time attendance system using facial recognition technology. It captures attendance data, including names, current date, and time, and records it in an Excel sheet. The graphical user interface (GUI) allows users to take attendance, view records, register new students, get help, and exit the program.

Step 2: Prerequisites

Before getting started, make sure you have the following prerequisites in place:

  • Python installed on your system (3.7 or higher).
  • Required Python libraries installed: opencv-python, face_recognition, Pillow (PIL), and tkinter.
  • Webcam or camera connected to your computer.

Step 3: Set Up the Project

  1. Clone or download the project from the GitHub repository.
git clone https://github.com/singhAnike/Facial-Recognition-Attendance
Code language: PHP (php)
  1. Navigate to the project directory:
cd Facial-Recognition-Attendance

Step 4: Install Dependencies

Install the required Python libraries using pip:

pip install opencv-python opencv-python-headless face_recognition pillow

Step 5: Run the Program

To run the program, execute the gui.py script:

python gui.pyCode language: CSS (css)

I explained about this file in the overview section.

Step 6: Using the Program

The graphical user interface (GUI) provides several options:

Taking Attendance

  1. Click the “Take Attendance” button.
  2. Wait for the system to start recognizing faces using your camera.
  3. The system will display recognized names on the video feed and record attendance in the Attendance.csv file.
Taking Attendance Window
When we click on ‘take attendance,’ real-time video capturing starts.

Viewing Attendance Records

  1. Click the “View Attendance” button.
When you click on ‘show attendance,’ it opens the Excel file containing the attendance.
  1. This will open the Attendance.csv file, which contains attendance records.
When we click on take attendance
Marked attendance in excel sheet

Registering a New Student

  1. Click the “Click to register a new student” button.
Registering a New Student
  1. Select an image of the new student’s face from your computer.
  2. The system will use this image for future recognition.

Getting Help

  1. Click the “Get Help” button.
  2. A web page with additional information or support will open in your web browser.
 help section

Exiting the Program

  • To exit the program, click the “Exit” button.

Congratulations! You have successfully set up and used the “Facial-Recognition-Attendance” project to take attendance using facial recognition technology.

You can further customize and extend this project as needed for your specific use case.

Overview Of The Code:

Project directory details;

|-- Backg-images/
|   |-- face-recognition.jpg
|-- images/
|   |-- place your known individuals' images here
|-- faceencoding.py
|-- gui.py


Here’s a breakdown of the key functions and what they do:

  1. faceEncodings(images):
    • This function takes a list of images as input.
    • It processes each image to extract facial encodings using the face_recognition library.
    • The computed encodings are returned as a list.
  2. attendance(name):
    • This function takes a person’s name as input.
    • It opens a CSV file named “Attendance.csv” and checks if the name is already present in the file.
    • If the name is not found, it adds a new entry with the current time and date, marking the person as “Present.”
  3. perform_face_recognition(encodeListKnown, personNames):
    • This function performs real-time face recognition using the computer’s webcam.
    • It captures video from the webcam using OpenCV (cv2.VideoCapture) and continuously processes each frame.
    • It detects faces in each frame, encodes them, and compares the encodings with a known list of encodings (encodeListKnown) for registered individuals.
    • If a match is found, it identifies the person’s name and marks their attendance using the attendance function.
    • The recognized face is highlighted with a green rectangle in the video feed, and their name is displayed on top.
  4. take_attendance():
    • This function initiates the attendance-taking process.
    • It first reads a directory of images (presumably containing known faces) from the “images” folder and extracts their encodings.
    • The names of the individuals are derived from the image filenames.
    • The perform_face_recognition function is then called with the list of known encodings and corresponding names.
  5. show_attendance():
    • This function is responsible for opening the “Attendance.csv” file.
    • It uses os.startfile to open the file with the default system program for CSV files.
    • If the file is not found, it displays a message box indicating that the attendance file was not found.

It’s important to note that this code relies on several external libraries, including OpenCV (cv2), face_recognition, and tkinter.messagebox. Additionally, the code assumes the existence of image files in the “images” directory and a CSV file named “Attendance.csv” for storing attendance records.

Here is the Full Code;

import cv2
import csv
import numpy as np
import face_recognition
import os
from datetime import datetime
import tkinter.messagebox

def faceEncodings(images):
    encodeList = []
    for img in images:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[0]
    return encodeList

def attendance(name):
    with open('Attendance.csv', 'r+') as f:
        myDataList = f.readlines()
        nameList = []
        for line in myDataList:
            entry = line.split(',')

        if name not in nameList:
            time_now = datetime.now()
            tStr = time_now.strftime('%H:%M:%S')
            dStr = time_now.strftime('%d/%m/%Y')

def perform_face_recognition(encodeListKnown, personNames):
    cap = cv2.VideoCapture(0)

    def convert_to_rgb(faces):
        faces = cv2.cvtColor(faces, cv2.COLOR_BGR2RGB)
        return faces

    while True:
        ret, frame = cap.read()
        faces = cv2.resize(frame, (0, 0), None, 0.25, 0.25)
        faces = convert_to_rgb(faces)

        facesCurrentFrame = face_recognition.face_locations(faces)
        encodesCurrentFrame = face_recognition.face_encodings(faces, facesCurrentFrame)

        for encodeFace, faceLoc in zip(encodesCurrentFrame, facesCurrentFrame):
            matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
            faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
            matchIndex = np.argmin(faceDis)

            if matches[matchIndex]:
                name = personNames[matchIndex].upper()

                y1, x2, y2, x1 = faceLoc
                y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
                cv2.rectangle(frame, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
                cv2.putText(frame, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)

        cv2.imshow('Webcam', frame)
        if cv2.waitKey(1) == 13:


def take_attendance():
    tkinter.messagebox.showinfo("Encoding Start.", "Please wait a few seconds")
    path = 'images'
    images = []
    personNames = []
    myList = os.listdir(path)

    for cu_img in myList:
        current_Img = cv2.imread(f'{path}/{cu_img}')
    encodeListKnown = faceEncodings(images)
    tkinter.messagebox.showinfo("Encoding Completed.", "All Encodings Complete!!!")
    perform_face_recognition(encodeListKnown, personNames)

def show_attendance():
    except OSError:
        tkinter.messagebox.showinfo("File Error", "Attendance file not found!")Code language: JavaScript (javascript)


  • It creates a tkinter GUI window with a background image and buttons for taking attendance, viewing attendance, registering new students, getting help, and exiting the program.
  • The GUI is responsive and resizes the background image when the window size changes.
  • The buttons are linked to corresponding functions defined in faceencoding.py.

Here’s an explanation of the key parts of the code:

  1. Import Statements:
    • The code begins by importing necessary modules and libraries, including:
      • tkinter (imported as Tk) for GUI components.
      • filedialog from tkinter (imported as fd) for file dialog functionality.
      • PIL for working with images.
      • webbrowser for opening web links.
      • faceencoding (presumably a custom module) for face recognition functions.
  2. Creating the GUI Window:
    • An instance of the main tkinter window is created and stored in the variable win.
    • The window’s size is set to match the screen dimensions.
  3. Setting Background Image:
    • An image file (bg_image_path) is loaded and displayed as the background of the GUI.
  4. resize_image Function:
    • This function is used to resize the background image when the window is resized. It also updates text elements on the canvas.
    • It is bound to the <Configure> event of the window, so it’s called when the window is resized.
  5. Buttons:
    • Several buttons are created using the Button widget, including:
      • “Take Attendance”
      • “View Attendance”
      • “Click to register a new student”
      • “Get Help”
      • “Exit”
    • Each button has its own unique appearance and functionality, which is defined by associated functions.
    • For example, the “Take Attendance” button has a command attribute set to take_attendance, indicating that it should execute the take_attendance function when clicked.
  6. new_registration Function:
    • This function is called when the “Click to register a new student” button is clicked.
    • It opens a file dialog to select a file and presumably performs some registration or processing based on the selected file.
  7. help Function:
    • This function is called when the “Get Help” button is clicked.
    • It opens a web browser with a specified URL for help.
  8. exit_program Function:
    • This function is called when the “Exit” button is clicked.
    • It destroys the main GUI window, effectively exiting the program.
  9. Displaying Elements:
    • The code uses Canvas to display background images and buttons on the GUI.
    • Buttons are placed on the canvas at specific coordinates.
  10. Main Loop:
    • The mainloop function of the Tkinter window (win) is called, starting the GUI’s main event loop, which handles user interactions and updates.

Here is the Full Code;

from tkinter import *
from tkinter import filedialog as fd
from PIL import ImageTk, Image
import webbrowser
from faceencoding import*

# GUI Implementation for Automated Attendance System
win = Tk()

width = win.winfo_screenwidth()
height = win.winfo_screenheight()

# Fix tkinter window size
win.geometry("%dx%d" % (width, height))

# Set Background Image
bg_image_path = "Backg-images/face-recognition.jpg"
bg = ImageTk.PhotoImage(file=bg_image_path)

# Create a Canvas
canvas = Canvas(win, width=750, height=3500)
canvas.pack(fill=BOTH, expand=True)

# Add Image inside the Canvas
canvas.create_image(0, 0, image=bg, anchor='nw')

# Function to resize the window
def resize_image(e):
    global image, resized, image2
    # open image to resize it
    image = Image.open(bg_image_path)
    # resize the image with width and height of root
    resized = image.resize((e.width, e.height), Image.ANTIALIAS)
    image2 = ImageTk.PhotoImage(resized)
    canvas.create_image(0, 0, image=image2, anchor='nw')
    # welcome
    canvas_id = canvas.create_text(100, 250, anchor="nw")
        canvas_id, text="Welcome To The Automated Attendance System\n\nLet's get Started"*1, width=780,)
    canvas.itemconfig(canvas_id, font=("courier", 16), fill='#4343CD')
    canvas.insert(canvas_id, 16, "")
    # heading
    canvas_h = canvas.create_text(300, 50, anchor="nw")
        canvas_h, text="Face-Recognition Automated Attendance System"*1, width=800)
    canvas.itemconfig(canvas_h, font=("Times New Roman bold", 25), fill='#BCBC8F')
    canvas.insert(canvas_h, 16, "")

# Bind the function to configure the parent window
win.bind("<Configure>", resize_image)
# Title of this application
win.title("Automated Attendance System")

# Creating buttons
# Creating The Button For Taking Attendance
button1 = Button(win, text="Take Attendance",
                 bg='DodgerBlue4', fg='white', height='2', width='15', border='5', font=("Times New Roman", 11), command=take_attendance)

# Creating The Button To show Attendance
button2 = Button(win, bg="DodgerBlue4", fg="white", text="View Attendance",
                 height='2', width='15', border='5', font=("Times New Roman", 11), command=show_attendance)

# New student registration function
def new_registration():
    file = fd.askopenfilename(initialdir="C:/Users/immra/OneDrive/Pictures")
    fob = open(file, 'r')

# Button for Add new student
button3 = Button(win, bg="DodgerBlue4", fg="white", text="Click to register a new student",
                 border='5', height='2', width='25', font=("Times New Roman", 11), command=new_registration)

# Function definition
def help():

# Button for Help
button4 = Button(win, bg="DodgerBlue4", fg="white", text="Get Help",
                 height='2', width='8', border='5', font=("Times New Roman", 11), command=help)

def exit_program():

# Button for Exit From window
button5 = Button(win, bg="DodgerBlue4", fg="white", text="Exit", height='2',
                 width='8', border='5', command=exit_program, font=("Times New Roman", 11))

# Display image
canvas.create_image(0, 0, image=bg, anchor="nw")

# Display Buttons
button1_canvas = canvas.create_window(100, 550, anchor="nw", window=button1)
button2_canvas = canvas.create_window(300, 550, anchor="nw", window=button2)
button3_canvas = canvas.create_window(680, 550, anchor="nw", window=button3)
button4_canvas = canvas.create_window(950, 550, anchor="nw", window=button4)
button5_canvas = canvas.create_window(1100, 550, anchor="nw", window=button5)

# Run the main loop
win.mainloop()Code language: PHP (php)

What You Learn From This Project?

From the provided code for creating an Automated Attendance System with Face Recognition and the tutorial on how to set up and use it, here are some key takeaways:

  1. Integration of Libraries: The code demonstrates the integration of various Python libraries, including OpenCV, face_recognition, Pillow (PIL), and tkinter. These libraries are essential for building a face recognition-based attendance system and creating a graphical user interface.
  2. Face Recognition: The code utilizes the face_recognition library to detect and recognize faces in images captured by a webcam. It demonstrates how to encode known faces and compare them to the faces detected in real-time video frames.
  3. Graphical User Interface (GUI): The tkinter library is used to create a user-friendly GUI for the attendance system. It includes buttons for taking attendance, viewing attendance records, registering new students, getting help, and exiting the program.
  4. File Handling: The code involves file handling, particularly reading and writing to CSV files. It maintains an “Attendance.csv” file to keep track of attendance records.
  5. Responsive Design: The GUI design is responsive, adjusting to changes in the window size. This makes the application visually appealing and user-friendly on different screen sizes.
  6. Modularity: The code is organized into separate Python scripts (faceencoding.py and gui.py) to promote modularity and maintainability. This separation allows for easier maintenance and future enhancements.
  7. User Interaction: The tutorial guides users through the process of setting up the project, running the application, and performing various tasks like taking attendance and viewing records.
  8. Prerequisites and Dependencies: The tutorial emphasizes the importance of having the necessary prerequisites (Python and required libraries) and how to install them using pip. This ensures a smooth setup process.
  9. Project Structure: It provides guidance on organizing the project directory with subdirectories for images and background images, making it easier to manage project assets.

Overall, this code and tutorial serve as a practical example of how to create an attendance system with face recognition technology, making it accessible for educational institutions, businesses, or other organizations that require automated attendance tracking. It also highlights the importance of using existing libraries and frameworks to streamline the development process.

Read More;

  • Aniket Singh

    Aniket Singh holds a B.Tech in Computer Science & Engineering from Oriental University. He is a skilled programmer with a strong coding background, having hands-on experience in developing advanced projects, particularly in Python and the Django framework. Aniket has worked on various real-world industry projects and has a solid command of Python, Django, REST API, PostgreSQL, as well as proficiency in C and C++. He is eager to collaborate with experienced professionals to further enhance his skills.

Leave a Comment