Finaltheasis
Finaltheasis
(USING OPENCV)
By
NAWAZ FAQIR
SYED SAQIB AHAMD
BS - Computer Science
Session 2020-2024
Affiliated With
UNIVERSITY OF MALAKAND
I
FACE RECOGNITION ATTENDANCE SYSTEM
(USING OPENCV)
Submitted By:
NAWAZ FAQIR
SYED SAQIB AHAMD
BS - Computer Science
Session 2020-2024
Supervised by:
Mr. Muhammad Tawab Khan
Affiliated With
UNIVERSITY OF MALAKAND
II
AUTHORS DECLARATION
We, Nawaz Faqir and Syed Saqib Ahmad, hereby declare that our BS-CS final year project
report titled " Face Recognition Attendance System" is our own work and has not been
submitted previously by us for obtaining any degree from this University, Department of
Computer Science, University of Malakand, or any other institution.
At any time, if our statement is found to be incorrect, even after graduation, the University
has the right to withdraw our BSc-CS degree.
Nawaz Faqir:
Signature: ____________________
Date: ________________________
Syed Saqib Ahmad:
Signature: ____________________
Date: ________________________
III
CERTIFICATE OF APPROVAL
It is certified that the content and form of the report titled " Face Recognition Attendance
System" submitted by Nawaz Faqir and Syed Saqib Ahmad have been found satisfactory for
the requirements of the degree of Bachelor in Computer Science.
Supervisor
Signature:
Name:
Designation:
External Examiner
Signature:
Name: ______________________
Designation:
Institute:
IV
DEDICATIONS
With profound gratitude and heartfelt appreciation, we dedicate our report work to the
Almighty Creator Allah. His boundless wisdom, inspiration, knowledge, and understanding
have guided us throughout this journey. In equal measure, we extend this dedication to our
parents, who have served as constant wellsprings of motivation and encouragement since our
earliest days. Their unwavering support has been the driving force behind our endeavors. To
our esteemed supervisor, Muhammad Tawab Khan, a beacon of knowledge and guidance, we
express our sincere thanks. His mentorship has been instrumental in shaping our work.
Additionally, we extend our dedication to the remarkable lecturers and teachers who have
enriched our learning journey. Their insights and wisdom have profoundly impacted us.
Lastly, to our cherished classmates, whose camaraderie has made our academic journey a
delight, we hold deep appreciation. The joy of learning with you all will forever remain a
cherished memory.
V
ACKNOWLEDGEMENT
We sincerely thank our supervisor, Muhammad Tawab Khan whose unwavering guidance and
valuable insights were instrumental in guiding our project to fruition. His consistent support,
insightful advice, and encouragement played a vital role in overcoming challenges and
achieving success. His dedication to our growth and progress is deeply appreciated. We also
sincerely thank our esteemed teachers, whose expertise and generosity in sharing knowledge
have equipped us with the tools needed for this endeavor. Their guidance illuminated our path
and enriched our understanding, making this project possible.
We thank our families and friends for their constant encouragement and belief in us. Their
unwavering support has been a constant source of strength throughout this journey.
Last but not least, we would like to thank everyone who contributed in various ways, be it with
help, motivation, or encouragement. Your joint efforts have left an indelible mark on the
outcome of our project.
VI
ABSTRACT
The Face Recognition Attendance System project, developed by Nawaz Faqir and Syed Saqib
Ahmad, students of BS Computer Science at Gul Abad Degree College affiliated with the
University of Malakand, aims to revolutionize the attendance marking process in educational
institutions. Supervised by Muhammad Tawab Khan, this system utilizes advanced face
recognition technology to automate attendance recording, thereby enhancing accuracy and
efficiency. The system integrates OpenCV for face detection and recognition, Tkinter for the
graphical user interface (GUI), and MySQL for database management, ensuring a seamless and
user-friendly experience.
VII
ABBREVIATIONS AND TERMS
Terms Definitions
/Abbreviations
GUI Graphical User Interface - A visual way of interacting with a
computer program.
OpenCV Open Source Computer Vision Library - An open-source computer
vision and machine learning software library.
Tkinter A standard GUI toolkit for Python.
VIII
Table Of Contents
AUTHORS DECLARATION ........................................................................................................... II
DEDICATIONS .............................................................................................................................V
ACKNOWLEDGEMENT ...............................................................................................................VI
ABSTRACT .................................................................................................................................VII
CHAPTER 1.................................................................................................................................. 1
INTRODUCTION ...................................................................................................................... 1
CHAPTER 2.................................................................................................................................. 5
CHAPTER 3................................................................................................................................ 10
IX
3.1 Overview ..................................................................................................................... 10
CHAPTER 4................................................................................................................................ 30
IMPLEMENTATION ............................................................................................................... 30
CHAPTER 5................................................................................................................................ 45
CHAPTER 6................................................................................................................................ 48
6.1 Results......................................................................................................................... 48
X
6.4 Summary ..................................................................................................................... 49
CHAPTER 7................................................................................................................................ 51
CHAPTER 8................................................................................................................................ 53
REFERENCES ......................................................................................................................... 53
XI
LIST OF FIGURES
Figure 1:Process Flow of the Facial Recognition Attendance System ...................................... 6
Figure 5:System Architecture of the Face Recognition Attendance Management System ..... 17
Figure 8:User Login Interface of the Face Recognition Attendance System .......................... 33
Figure 9:User Registration Interface of the Face Recognition Attendance System ................ 34
Figure 10:Daily Report Interface of the Face Recognition Attendance System ...................... 35
XII
CHAPTER 1
INTRODUCTION
1.1 Background
Attendance management is essential for maintaining accurate records in educational
institutions, businesses, and other organizations. Traditional attendance tracking methods, such
as manual registers or card-based systems, are often fraught with challenges. These methods
can lead to errors, opportunities for fraudulent entries, and inefficiencies in handling large
amounts of data. As technology advances, facial recognition systems have emerged as a
promising solution to these problems. This project focuses on developing an attendance
management system that uses facial recognition technology to streamline and improve the
process of tracking attendance in real time.
1
To Improve Accuracy: Ensure the system accurately identifies individuals and records
their attendance without errors, enhancing the reliability of attendance data.
To Enhance Efficiency: Reduce the time and effort required to manage attendance
records, allowing administrators and users to focus on more critical tasks.
To Prevent Fraud: Implement measures to eliminate the possibility of proxy
attendance, ensuring that only the rightful individual is marked present.
2
1.5 Significance of the project This project makes significant contributions to the field of
attendance management by introducing a robust, automated system that addresses the limitations of
traditional methods. The significance of this project includes:
Improved Efficiency: Automating the attendance process saves time for both
administrators and users. It eliminates the need for manual entry, reducing
administrative workload and allowing staff to focus on more critical tasks.
Enhanced Accuracy: The use of facial recognition technology significantly reduces
errors associated with manual attendance marking. This ensures that attendance records
are accurate and reliable.
Increased Security: The system’s ability to prevent proxy attendance ensures the
integrity of the attendance records. Only the rightful individual is marked present,
thereby maintaining the trustworthiness of the data. By addressing these key areas, the
study highlights the potential of facial recognition technology to revolutionize
attendance management, making it more efficient, accurate,
and secure. This ultimately leads to a more effective and trustworthy system for tracking
and managing attendance
3
Chapter 7: Conclusion and Future Work - Summarizes the work, highlights the
contributions, and suggests areas for future research and development.
References - Lists the sources and references used in the study.
4
CHAPTER 2
LITERATURE REVIEW AND TECHNOLOGICAL
BACKGROUND
5
Face Detection: Algorithms detect and locate the face within the captured image.
Techniques such as Haar Cascades and Histogram of Oriented Gradients (HOG) are
commonly used.
Feature Extraction: Key facial features are extracted and encoded into a numerical
format. Methods like Local Binary Patterns Histogram (LBPH), Principal Component
Analysis (PCA), and Convolutional Neural Networks (CNNs) are utilized for this
purpose.
Face Matching: The extracted feature are compared a database of known face to
identify the
individual. The LBPH algorithm, used in this project, is particularly effective for
handling variations in lighting and facial expressions.
The following diagram illustrates the process flow of the facial recognition attendance system:
6
Non-Intrusive and Hygienic: Unlike fingerprint or iris scanning, facial recognition
does not require physical contact, making it more hygienic and suitable for post-
pandemic scenarios.
Speed and Efficiency: Facial recognition can process and verify multiple faces
simultaneously, significantly reducing the time required for attendance marking.
High Accuracy and Reliability: Modern algorithms achieve high accuracy rates even
in diverse conditions, ensuring reliable attendance tracking.
Enhanced Security: Facial recognition reduces the risk of proxy attendance and
enhances overall security by accurately identifying individuals.
7
User-Friendly Interface: The graphical user interface (GUI) developed using Tkinter
provides an easy-to-use platform for both administrators and users. Teachers can
monitor attendance in real-time, and students can verify their attendance records.
This implementation not only enhances the accuracy and efficiency of attendance tracking in
educational institutions but also reduces the administrative burden on staff, allowing them to
focus more on educational activities.
Despite its numerous advantages, facial recognition technology faces several challenges:
Privacy Concerns: The collection and storage of biometric data raise significant
privacy issues. It is crucial to implement stringent security measures to protect this data
and ensure compliance with data protection regulations.
Accuracy Variability: Factors such as lighting, facial expressions, and occlusions
(e.g., glasses, masks) can impact the accuracy of facial recognition. Continuous
improvements in algorithms are needed to address these challenges.
Ethical and Legal Issues: The deployment of facial recognition systems must adhere
to ethical guidelines and legal frameworks to ensure responsible use.
The attendance management system in this project involves several technological components:
Software: Python is used for developing the application, leveraging libraries such as
OpenCV for computer vision tasks, Tkinter for the graphical user interface, and
MySQL for database management.
Hardware: A camera is used for capturing images, and a computer system is required
for processing and storing data.
Database Integration: The system integrates with a MySQL database to store
attendance records.
Data is managed and queried efficiently, allowing for the generation of daily, monthly, and
individual reports.
8
University Implementation: A university in China implemented a facial recognition
system across its campus, leading to a significant reduction in absenteeism and
improved class attendance.
Corporate Office: A corporate office adopted facial recognition for employee
attendance, resulting in streamlined payroll processing and enhanced security.
9
CHAPTER 3
SYSTEM DESIGN AND IMPLEMENTATION
3.1 Overview
10
3.2.1 Entity-Relationship Diagram (ERD)
The Entity-Relationship Diagram (ERD) is a crucial tool used to design the database structure
of the Face Recognition Attendance System. It illustrates the relationships between the
entities within the system, ensuring that data is organized and managed effectively.
Teacher:
o Id: Unique identifier for each teacher.
o First_Name, Last_Name: Personal details of the teacher.
o Email_Id: Contact information.
o Username, Password: Credentials for system access.
Student:
o First_Name, Last_Name: Personal details of the student.
o Image Name: The image used for face recognition.
o Mobile_No, Email_Id: Contact information.
o Roll_No: Unique identifier for each student.
o Capture Image: Action to capture the student’s image.
o Attendance: Linked to the Attendance entity.
o Semester, Classroom: Details related to the student’s academic status.
o Folder_Name: Used for storing images or records.
Attendance:
o Date: The date on which attendance is taken.
o Subject: The subject for which attendance is recorded.
o Classroom: The location where the class is held.
o Folder_Name: Related to the storage of attendance data.
o Teacher_Name: The teacher who takes the attendance.
o Roll_No: Associated with the student for whom attendance is marked.
Relationships:
11
o The Teacher entity is related to the Student entity through the action of adding
students. This relationship indicates that a teacher can add students to the
system, likely as part of the enrollment process.
Student and Attendance:
o The Student entity is linked to the Attendance entity, which means that
attendance records are created for each student. The attributes in the
Attendance entity, such as Date, Subject, and Classroom, are used to record
specific attendance details.
Take Attendance:
o This process connects the Teacher and Attendance entities, indicating that
teachers are responsible for taking attendance, which is then recorded in the
system.
This ERD provides a clear visual representation of the system’s data structure, illustrating
how teachers, students, and attendance records interact within the system. The design ensures
data integrity, supports the functional requirements of the system, and aligns with the
objectives of accurate and efficient attendance tracking
12
3.2.1 User Interface (UI)
The User Interface (UI) of the system is developed using Tkinter, a standard Python library
for creating graphical user interfaces. The UI is designed to be intuitive and user-friendly,
allowing users to interact with the system effortlessly. Key screens in the UI include:
Login and Registration Screen: Provides a secure gateway for users to access the
system. Registered users can log in using their credentials, while new users can register
through a simple form.
Main Dashboard: Acts as the central hub for navigating different functionalities of the
system, including accessing the attendance marking module, viewing reports, and
managing user data.
Face Recognition Panel: This is where the real-time face detection and recognition
take place. The panel is connected to the system’s camera, capturing live images for
processing.
Report Generation Panel: Allows users to generate detailed attendance reports,
which can be exported as PDF or CSV files for external use.
At the heart of the system’s functionality is the Face Detection and Recognition module,
powered by OpenCV. This module is responsible for identifying and verifying the identity of
individuals using facial recognition technology. The system employs the Local Binary
Patterns Histogram (LBPH) algorithm for face recognition, which is known for its robustness
and accuracy even under varying lighting conditions.
Face Detection: The system first detects faces in the captured image using Haar
cascades, a popular method for object detection that is efficient and effective. Face
Recognition Once a face is detected, the system proceeds to the Face Recognition
step. This is where the actual identification of the individual takes place.
LBPH (Local Binary Patterns Histogram):
o The LBPH algorithm is chosen for face recognition due to its robustness in
various conditions, including different lighting environments.
13
o Unlike other algorithms that rely on high-dimensional data, LBPH operates
by summarizing local facial features into a histogram, making it efficient
and effective even with low-resolution images.
How LBPH Works:
o Local Binary Patterns (LBP):
LBP is a simple yet powerful texture operator that labels the pixels of an
image by thresholding the neighborhood of each pixel and considering
the result as a binary number.
In the context of face recognition, LBP is applied to the face region to
generate a set of binary patterns that describe the texture of the face.
o Histogram Construction:
The LBP binary patterns are converted into a histogram that represents the
frequency of each pattern within the face image.
This histogram effectively encodes the unique facial features of the
individual.
14
3.2.3 Database Management
The system’s data is managed using a MySQL database, which provides a structured and
reliable way to store and retrieve data. The database is designed to handle various types of data,
including user credentials, facial recognition data, and attendance records. Key tables in the
database include:
student: Stores personal and academic information of students, such as student ID,
name, department, course, and contact details.
regteach: Contains details about teachers and administrators, including their login
credentials and contact information.
attendance_summary: Summarizes attendance data for each student, including dates
of attendance, overall attendance percentage, and any fines imposed for absenteeism.
stdattendance: Records individual attendance events with details such as the date,
time, and status (present/absent/leave).
These tables are interconnected, ensuring data consistency and integrity across the system.
Record Keeping: The reports can be exported in PDF or CSV formats, making it easy
to maintain accurate records for future reference.
Compliance: The system ensures that attendance records meet institutional or
organizational requirements for record-keeping and reporting.
The different components of the system are tightly integrated to ensure seamless
communication and data flow. The UI interacts with the face recognition module to capture
and process images, while the database management system stores and retrieves the necessary
15
data. The report generation module pulls data from the database and formats it according to the
user’s specifications
Data Flow Diagrams (DFDs) are used to visually represent the flow of data within a system.
They show how information moves from one process to another and how it interacts with
different system components. In context of the Attendance Management System, DFDs help
in understanding how data such as user information, facial recognition data, and attendance
records are processed and managed.
Data Flow:
Login Info: The user provides login credentials, which are sent to the User
Authentication process.
16
Face Data: The captured facial data is sent to the Face Recognition process for
matching.
Attendance Records: Once attendance is marked, the data is stored in the database.
Reports: Users can request reports, which are generated and retrieved from the
database.
The Level 1 DFD breaks down the main processes from the Level 0 DFD into more detailed
sub-processes. It provides a more granular view of how data is processed within the system.
Entities:
Processes:
Data Stores:
User Data: Stores user-specific information, such as credentials and facial data.
17
Data Flow:
Login Info: Flows from the Student to the User Authentication process.
Face Data: Sent from the Face Recognition process to identify the user.
Recognition Data: Flows from the Face Recognition process to update user
data.
Store Attendance: The process updates the Attendance Records data store with
the new attendance data.
18
3.4 System Setup
The System Setup section is crucial for understanding how to prepare and configure the
Attendance Management System to ensure it operates smoothly. This section will cover the
hardware and software requirements, the installation process, and the configuration steps
needed to get the system up and running.
To deploy the Attendance Management System, you will need the following hardware
components:
o RAM: 8 GB or more
2. Camera: A high-definition (HD) camera is essential for capturing clear images for
face detection and recognition. The camera should support at least 720p resolution
with a good frame rate (30 FPS or higher).
The system relies on various software components, which need to be installed and configured
correctly:
1. Operating System:
19
2. Python: The system is built using Python. You will need Python 3.7 or later installed
on your machine. You can download it from Python's official website.
4. MySQL Database: The system uses a MySQL database to store user data, facial
recognition data, and attendance records. You can download and install MySQL from
MySQL's official website.
5. Text Editor/IDE: A text editor like Visual Studio Code, PyCharm, or any other IDE
that supports Python development.
1. Installing Python:
During installation, make sure to check the option "Add Python to PATH."
2. Installing MySQL:
Download MySQL .
Follow the installation wizard to set up MySQL. During setup, configure the
root user and password, which will be used later for database connections.
Open MySQL Workbench or use the command line to create the necessary
database and tables.
Run the provided SQL script (if available) to set up the database schema as
described in the Database Design section.
20
Use a virtual environment to manage dependencies. Set it up by running:
Once everything is set up, you can run the system by executing the main Python
script. For example:
python main.py
The system’s GUI should appear, and you can start interacting with it, such as
registering users, capturing images for facial recognition, marking attendance,
and generating reports.
You may need to adjust the camera settings in the Python script (e.g., resolution,
frame rate) to optimize performance.
3.4.4 Troubleshooting
Here are some common issues you might encounter during setup, along with possible solutions:
Python Version Issues: Ensure that you're using Python 3.7 or higher. Run python --
version to check your Python version.
Library Installation Failures: If pip fails to install any library, ensure your internet
connection is stable, and try updating pip using pip install --upgrade pip.
Database Connection Errors: Verify that MySQL is running, and double-check the
username, password, and database name in your Python script.
21
Camera Not Recognized: Check that your camera is properly connected and
recognized by your operating system. You may also need to install specific drivers.
The Database Design section is crucial for understanding how data is structured, stored, and
managed within the Attendance Management System. A well-designed database ensures data
integrity, efficiency, and scalability. This section will cover the database schema, the
relationships between tables, and how the data supports the overall functionality of the system.
The database schema for the Attendance Management System is designed to store various types
of data, including user credentials, facial recognition data, attendance records, and reporting
information. The database is implemented using MySQL, which provides robust support for
relational data and ensures data consistency.
The database consists of several key tables, each with specific roles in the system. The
relationships between these tables are designed to ensure data integrity and support the
functionality of the system.
22
Database Schema:
Student Table
The `student` table stores personal and academic information for each student.
Column Name Data Type Description
student_ID VARCHAR(45) Unique identifier for each
student
Name VARCHAR(45) Full name of the student
Department VARCHAR(45) Department to which the
student belongs
Course VARCHAR(45) Course the student is
enrolled in
Year VARCHAR(45) Year of study
Semester VARCHAR(45) Current semester
Division VARCHAR(45) Division or section of the
student
Gender VARCHAR(45) Gender of the student
23
DOB VARCHAR(45) Date of birth
Mobile_No VARCHAR(45) Contact number
Address VARCHAR(45) Residential address
Roll_No VARCHAR(45) Roll number assigned by the
institution
Email VARCHAR(45) Email address
Teacher_Name VARCHAR(45) Name of the assigned
teacher
PhotoSample VARCHAR(45) Path to the photo sample
used for facial recognition
regteach Table
The `regteach` table contains details about the teachers or administrators who manage the
system.
Column Name Data Type Description
fname VARCHAR(255) First name of the
teacher/administrator
lname VARCHAR(255) Last name of the
teacher/administrator
cnum VARCHAR(255) Contact number
email VARCHAR(255) Email address
ssq VARCHAR(255) Security question for
password recovery
sa VARCHAR(255) Security answer for
password recovery
pwd VARCHAR(255) Encrypted password
student_student_ID VARCHAR(45) Foreign key linking to the
student table (if applicable)
attendance_summary Table
The `attendance_summary` table summarizes the attendance data for each student.
Column Name Data Type Description
Student_ID VARCHAR(255) Foreign key linking to the
student table
Name VARCHAR(255) Name of the student
Roll_No VARCHAR(255) Roll number of the student
Fine INT Fine imposed for
absenteeism
24
Attendance_Average FLOAT Average attendance
percentage
Overall_Attendance_Average FLOAT Overall attendance
percentage
Dates_Present TEXT List of dates the student
was present
Attendance_Statuses TEXT List of attendance statuses
(Present/Absent/Leave)
Total_Attendance INT Total number of days the
student was present
Total_Absent INT Total number of days the
student was absent
Total_Leave_Days INT Total number of leave days
taken by the student
stdattendance Table
The `stdattendance` table records individual attendance events with specific details for each
occurrence.
Column Name Data Type Description
std_id VARCHAR(45) Unique identifier for the
attendance record
std_roll_no VARCHAR(45) Roll number of the student
std_name VARCHAR(45) Name of the student
std_time VARCHAR(45) Time of attendance entry
std_date VARCHAR(45) Date of attendance entry
std_attendance VARCHAR(2000) Attendance status
(Present/Absent/Leave)
std_fine DECIMAL(10,2) Fine for absenteeism (if
applicable)
attendance_summary_Student_ID VARCHAR(255) Foreign key linking to the
attendance_summary table
25
critical modules such as face detection, face recognition, attendance marking, and report
generation.
Programming Language: The system is developed using Python, which is chosen for
its simplicity, extensive libraries, and strong support for image processing and machine
learning tasks.
OpenCV: Used for image processing and face detection. OpenCV provides
efficient algorithms for detecting faces in images and videos.
Tkinter: A standard Python interface to the Tk GUI toolkit, used for creating
the graphical user interface (GUI) of the system.
The system follows a modular architecture where different components interact with each other
to perform specific tasks. The main modules include:
1. User Interface Module: This module is responsible for interacting with the users
(students and administrators). It is implemented using Tkinter and provides forms for
login, registration, and accessing attendance records.
26
2. Face Detection and Recognition Module: This module handles the capture of images,
detection of faces, and recognition of individuals. It utilizes OpenCV for face detection
and the LBPH algorithm for face recognition.
3. Attendance Marking Module: Once a face is recognized, this module marks the
attendance of the individual in the database. It also handles the logic for checking
whether the individual is already present or absent.
4. Database Interaction Module: This module manages all interactions with the MySQL
database, including storing and retrieving data. It ensures that data is consistently stored
and retrieved efficiently.
5. Report Generation Module: This module generates attendance reports based on the
data stored in the database. It uses Pandas for data manipulation and allows exporting
reports in various formats (e.g., CSV, PDF).
Face Detection:
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def detect_faces(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
return faces
Face Recognition:
27
The LBPH (Local Binary Patterns Histogram) algorithm is used for face recognition.
LBPH is chosen for its simplicity and effectiveness, particularly in varying lighting
conditions.
The system is first trained with images of known individuals. For each image, the
algorithm computes a histogram of local binary patterns, which is then stored in the
system.
During recognition, the system compares the histogram of the captured face with the
stored histograms to find the closest match.recognizer =
cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer.yml') # Loading the trained model
def recognize_face(face_image):
gray = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)
id, confidence = recognizer.predict(gray)
return id, confidence
2. Attendance Marking
The attendance marking module interacts with the database to update the attendance records.
Here’s how it works:
Mark Attendance:
After a successful face recognition, the system checks whether the recognized
individual’s attendance has already been marked for the day.
If not, it inserts a new record into the stdattendance table, indicating the
individual was present.
import mysql.connector
def mark_attendance(student_id):
conn = mysql.connector.connect(user='root', password='password',
host='127.0.0.1', database='attendance_db')
cursor = conn.cursor()
# Check if attendance is already marked
query = "SELECT * FROM stdattendance WHERE student_id=%s AND
date=CURRENT_DATE"
28
cursor.execute(query, (student_id,))
if cursor.fetchone() is None:
# Insert attendance record
insert_query = "INSERT INTO stdattendance (student_id, date, status)
VALUES (%s, CURRENT_DATE, 'Present')"
cursor.execute(insert_query, (student_id,))
conn.commit()
cursor.close()
conn.close()
3. Report Generation
The report generation module allows administrators to generate various types of attendance
reports:
Generate Report:
Pandas is used to manipulate the data and generate reports in different formats.
Unit Testing: Each module is individually tested using unit tests to ensure they
function correctly.
Integration Testing: After the individual modules are tested, they are integrated, and
the system is tested as a whole to ensure all components work together seamlessly.
Debugging Tools: Python’s built-in logging module and debugging tools within IDEs
like PyCharm or Visual Studio Code are used to trace and fix issues during
development.
29
CHAPTER 4
IMPLEMENTATION
4.1 Development Environment
The development environment for the Face Recognition Attendance System includes the
following tools and technologies:
Programming Language: Python, known for its simplicity and extensive libraries.
Integrated Development Environment (IDE): Visual Studio Code, chosen for its
robust features and extensions.
Libraries:
OpenCV: Used for image and video processing, crucial for face detection and
recognition.
Tkinter: Used for creating the graphical user interface (GUI).
MySQL Connector: Used for database connectivity and operations.
Database: MySQL, selected for its reliability and ease of use.
Operating System: Windows 10, providing a stable platform for development and
testing.
Registration Code
import tkinter as tk
from tkinter import messagebox
import mysql.connector
def register_user():
first_name = entry_first_name.get()
last_name = entry_last_name.get()
contact_no = entry_contact.get()
email = entry_email.get()
password = entry_password.get()
30
confirm_password = entry_confirm_password.get()
if password == confirm_password:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="attendance_system")
cursor = connection.cursor()
cursor.execute("INSERT INTO users (first_name, last_name, contact_no, email,
password) VALUES (%s, %s, %s, %s, %s)",
(first_name, last_name, contact_no, email, password))
connection.commit()
cursor.close()
connection.close()
messagebox.showinfo("Success", "Registration Successful")
else
messagebox.showerror("Error", "Passwords do not match")
app = tk.Tk()
app.title("Registration")
tk.Label(app, text="First Name").grid(row=0)
tk.Label(app, text="Last Name").grid(row=1)
tk.Label(app, text="Contact No").grid(row=2)
tk.Label(app, text="Email").grid(row=3)
tk.Label(app, text="Password").grid(row=4)
tk.Label(app, text="Confirm Password").grid(row=5)
entry_first_name = tk.Entry(app)
entry_last_name = tk.Entry(app)
entry_contact = tk.Entry(app)
entry_email = tk.Entry(app)
entry_password = tk.Entry(app, show='*')
entry_confirm_password = tk.Entry(app, show='*')
entry_first_name.grid(row=0, column=1)
entry_last_name.grid(row=1, column=1)
31
entry_contact.grid(row=2, column=1)
entry_email.grid(row=3, column=1)
entry_password.grid(row=4, column=1)
entry_confirm_password.grid(row=5, column=1)
tk.Button(app, text='Register', command=register_user).grid(row=6, column=1, pady=4)
app.mainloop()
Login Code
import tkinter as tk
from tkinter import messagebox
import mysql.connector
def login_user():
email = entry_email.get()
password = entry_password.get()
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="attendance_system"
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users WHERE email=%s AND password=%s", (email,
password))
result = cursor.fetchone()
if result:
messagebox.showinfo("Success", "Login Successful")
else:
messagebox.showerror("Error", "Invalid Credentials"
cursor.close()
connection.close()
app = tk.Tk()
app.title("Login")
tk.Label(app, text="Email").grid(row=0)
32
tk.Label(app, text="Password").grid(row=1)
entry_email = tk.Entry(app)
entry_password = tk.Entry(app, show='*')
entry_email.grid(row=0, column=1)
entry_password.grid(row=1, column=1)
tk.Button(app, text='Login', command=login_user).grid(row=2, column=1, pady=4)
app.mainloop()
Screenshots:
33
Figure 8:User Registration Interface of the Face Recognition Attendance System
34
(student_id,))
connection.commit()
cursor.close()
connection.close()
Screenshots:
35
Monthly Attendance code
def get_monthly_attendance(student_id, month, year):
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="attendance_system")
cursor = connection.cursor()
cursor.execute("SELECT * FROM attendance WHERE student_id=%s AND
MONTH(date)=%s AND YEAR(date)=%s", (student_id, month, year))
records = cursor.fetchall()
cursor.close()
connection.close()
36
4.3.3 Individual Attendance
The Individual Attendance sub-module provides detailed attendance records for each student.
This feature is particularly useful for monitoring the attendance history of individual students,
def get_individual_attendance(student_id):
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="attendance_system"
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM attendance WHERE student_id=%s", (student_id,))
records = cursor.fetchall()
cursor.close()
connection.close()
return records
Screenshots
37
Figure 13:Individual Attendance Report Interface
38
recognizer.read('trainer.yml')
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
id, confidence = recognizer.predict(gray[y:y+h, x:x+w])
if confidence < 50:
cv2.putText(frame, str(id), (x+5, y-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,
255, 255), 2)
else:
cv2.putText(frame, "Unknown", (x+5, y-5), cv2.FONT_HERSHEY_SIMPLEX, 1,
(255, 255, 255), 2)
cv2.imshow('Face Recognition', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Once a face is recognized, the Attendance Marking component automatically records the
attendance of the identified student. This automated process ensures accuracy and efficiency,
minimizing manual intervention.
def mark_attendance(student_id):
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="attendance_system"
39
)
cursor = connection.cursor()
cursor.execute("INSERT INTO attendance (student_id, date, status) VALUES (%s,
CURDATE(), 'Present')", (student_id,))
connection.commit()
cursor.close()
connection.close()
Screenshots:
40
Figure 15:Training Panel Interface of the Face Recognition System
41
4.5 Implementation of Report Generation Module
The Report Generation Module enables the creation of detailed attendance reports. These reports can
be generated in various formats, such as PDF and CSV, providing flexibility in reviewing and
analyzing attendance data. The module supports generating daily, monthly, and individual attendance
def generate_pdf_report(student_id):
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="attendance_system"
cursor = connection.cursor()
records = cursor.fetchall()
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.output("attendance_report.pdf")
cursor.close()
connection.close()
42
Screenshots
Screenshots:
43
Figure 18:Monthly Attendance Data in Excel Sheet
4.6 Summary
In this chapter, we have detailed the implementation of the Face Recognition Attendance
System. We covered the setup of the development environment, the implementation of the
login and registration module, the attendance module, the face recognition module, and the
report generation module. Each section included the necessary code and explanations to help
44
CHAPTER 5
TESTING AND EVALUATION
5.1 Testing Strategy
The testing strategy for the Face Recognition Attendance System is designed to ensure the
system's robustness, accuracy, and user-friendliness. The strategy includes the following
stages:
1. Unit Testing: Individual components and modules such as the login, registration,
attendance, face recognition, and report generation modules are tested in isolation to
verify their correctness.
2. Integration Testing: The interactions between integrated modules are tested to ensure
that they work together as expected. This includes testing the integration of the face
recognition module with the attendance marking system and the database.
3. System Testing: The entire system is tested as a whole to verify that it meets the
specified requirements. This includes testing the system’s performance under different
conditions, such as varying lighting and camera quality.
4. User Acceptance Testing (UAT): End-users test the system to ensure it meets their
needs and expectations. Feedback from users is used to make final adjustments and
improvements.
45
Test Case 2: User Login
Objective: Verify that registered users can log in.
Preconditions: User is registered, and the login form is displayed.
Steps:
1. Enter registered email and password.
Status: Pass
46
5.3 Performance Evaluation
The performance of the Face Recognition Attendance System was evaluated based on several
criteria:
1. Accuracy: The accuracy of face recognition was tested under various conditions,
including different lighting and camera quality.
o Result: The system achieved an accuracy rate of 95% under optimal conditions.
Accuracy decreased to 85% under poor lighting and low-resolution cameras but
remained within acceptable limits.
2. Speed: The time taken to recognize a face and mark attendance was measured.
o Result: The average recognition and marking time was 2 seconds, which is
within the acceptable range for real-time attendance marking.
3. Reliability: The system’s reliability was tested by running it continuously for extended
periods and under different conditions.
Result: The system remained stable and functional during prolonged use, with no
significant crashes or errors.
47
CHAPTER 6
RESULTS AND DISCUSSION
6.1 Results
The Face Recognition Attendance System was successfully developed and tested, yielding
the following results:
1. User Registration and Login: The system allowed new users to register and existing
users to log in successfully. The registration and login modules performed accurately,
storing and validating user credentials as expected.
2. Daily Attendance Marking: The system accurately recognized students' faces and
marked their attendance. Under optimal conditions, the recognition accuracy was 95%.
The attendance records were stored in the database without errors, and the system
handled multiple students efficiently.
3. Monthly and Individual Attendance Reports: The system generated comprehensive
attendance reports in both PDF and CSV formats. The reports included detailed
information on daily, monthly, and individual attendance records, aiding in analysis and
decision-making.
48
recognition for attendance marking, which significantly reduced the time and effort
compared to traditional methods.
4. Reliability: The system's stability during prolonged use underscores its reliability.
Continuous operation without significant crashes or errors is vital for an attendance
system expected to run daily.
6.3 Discussion
The Face Recognition Attendance System has demonstrated its potential to revolutionize
attendance management by addressing the limitations of traditional methods. The following
points discuss the implications and potential improvements:
1. Impact on Attendance Management: The system automates attendance tracking,
reducing administrative workload and minimizing human errors. Its ability to prevent
proxy attendance enhances the integrity of attendance records, making it a valuable tool
for educational institutions and businesses.
2. Challenges and Limitations:
Lighting Conditions: The system's performance under varying lighting
conditions highlights the need for better preprocessing techniques or hardware
improvements (e.g., using infrared cameras) to maintain high accuracy.
Changes in Appearance: The system might struggle to recognize individuals
with significant changes in appearance (e.g., new hairstyles, facial hair, masks).
Incorporating adaptive learning algorithms could help the system adjust to such
changes.
3. Future Enhancements:
Advanced Algorithms: Exploring advanced machine learning techniques, such
as deep learning models, could further improve recognition accuracy and
robustness.
User Feedback Integration: Continuously collecting and integrating user
feedback can help refine the system, making it more user-friendly and efficient.
Scalability: Ensuring the system can handle an increasing number of users and
data without performance degradation is essential for large-scale deployments.
6.4 Summary
This chapter presented the results and discussion of the Face Recognition Attendance System
project. The system successfully achieved high accuracy and efficiency in real-time attendance
tracking, with positive user feedback on its ease of use. The analysis highlighted the system's
49
strengths and identified areas for potential improvement. Overall, the project demonstrated the
feasibility and benefits of using facial recognition technology for attendance management,
paving the way for future enhancements and broader applications
50
CHAPTER 7
CONCLUSION AND FUTURE WORK
7.1 Conclusion
The Face Recognition Attendance System project aimed to develop an automated, efficient,
and accurate system for managing attendance using facial recognition technology. The project
successfully integrated OpenCV for face detection and recognition, Tkinter for the graphical
user interface, and MySQL for database management. Through rigorous testing and evaluation,
the system demonstrated high accuracy, reliability, and user satisfaction. The results validate
the system's potential to address the challenges of traditional attendance management methods,
such as manual errors, inefficiency, and fraudulent entries.
51
3. Scalability: Optimizing the system to handle larger datasets and more users without
compromising performance will be crucial for broader adoption.
4. Real-Time Data Synchronization: Implementing real-time synchronization with
cloud-based databases can enable seamless access and management of attendance
records across multiple locations.
5. Multi-Platform Support: Extending the system to support mobile platforms can
increase its accessibility and convenience for users.
6. Continuous Learning: Integrating adaptive learning capabilities to allow the system
to update its recognition models based on new data can enhance long-term accuracy
and reliability.
7.4 Summary
In conclusion, the Face Recognition Attendance System project has successfully demonstrated
the feasibility and advantages of using facial recognition technology for attendance
management. The system addresses key challenges associated with traditional methods,
offering a reliable, efficient, and user-friendly solution. The study's contributions provide a
solid foundation for future research and development in this area. By exploring the
recommended areas for future work, the system can be further improved to meet the evolving
needs of educational institutions, businesses, and other organizations.
52
CHAPTER 8
REFERENCES
In this chapter, we list all the sources, articles, books, and other references that were consulted
and referenced during the development of the Face Recognition Attendance System project.
Proper referencing ensures the credibility and academic integrity of the study.
References
1. Books and Articles:
o Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.
o Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer.
Websites and Online Resources:
o OpenCV Documentation. Retrieved from https://docs.opencv.org
o Tkinter Documentation. Retrieved from
https://docs.python.org/3/library/tkinter.html
o MySQL Documentation. Retrieved from https://dev.mysql.com/doc/
2. Tools and Libraries:
o Bradski, G. (2000). The OpenCV Library. Dr. Dobb's Journal of Software
Tools.
o Python Software Foundation. Python Language Reference, version 3.8.
Available at https://www.python.org.
These references provided the foundational knowledge and technical guidance necessary to
develop the Face Recognition Attendance System.
53