Project Book
Project Book
Date: Date:
Date:
1
FACE RECOGNITION ATTENDANCE
SYSTEM
A Project Report
Submitted in partial fulfillment of the
Requirements for the award of the
Degree of
2024-2025
DNYAN GANGA EDUCATION TRUST’S
DEGREE COLLEGE OF ARTS, COMMERCE & SCIENCE
Affiliated to University of Mumbai
THANE-MAHARASHTRA-400615
CERTIFICATE
External Examiner
A Face Recognition Attendance System (FRAS) offers automated reliable, efficient, and
convenient way to record and track attendance in numerous places such as schools, workplaces,
and events. This system works by capturing facial images of individuals and comparing them
with a pre-registered database to identify and record attendance
The main objective of this system is to automate the attendance technique, eliminate methods
which include paper-based registers and decrease the probabilities of errors or fraud. By
utilizing the strength of machine learning algorithms and facial recognition technology, and
FRAS guarantees accurate, actual-time attendance monitoring and generating desired result by
utilizing analytics technique
This abstract provides an overview of the advantages and capability of a Face Recognition
Attendance System, demonstrating how it can streamline attendance manipulates methods and
provides protection and overall performance in various environments.
ACKNOWLEDGEMENT
The goal is best achieved by treading the path of excellence with discipline and deep
insight. We would never have succeeded in completing our task without the cooperation,
encouragement and help provided to us by various teachers and guides.
With a deep sense of gratitude, we express our sincere thanks to our esteemed and
worthy guide, Mrs. Awantika Deshpande, for her valuable guidance in carrying out this
project under her effective supervision, encouragement, enlightenment and cooperation.
We feel indebted to express our deep sense of gratitude towards Dr. Bhavika R.
Karkera (I/C Principal) who has been a constant source of inspiration for us throughout this
project.
We would also like to thank all faculty members and non-teaching staff for their kind
support without vacillation.
The acknowledgement would be incomplete if we did not mention the emotional
support and blessings provided by our parents and friends. We had a pleasant enjoyable and
fruitful company with them. Last but not the least we would like to thank all the people who
directly or indirectly helped us with this project.
DECLARATION
I hereby declare that the project entitled, “Face Recognition Attendance System”
done at Dnyan Ganga College, has not been in any case duplicated to submit to any other
university for the award of any degree. To the best of my knowledge other than me, no one
has submitted to any other university.
The project is done in partial fulfillment of the requirements for the award of degree of
BACHELOR OF SCIENCE (INFORMATION TECHNOLOGY) to be submitted
as final semester project as part of our curriculum
Yash Jaiswar
TABLE OF CONTENTS
SR. NO. PAGE NO.
CHAPTER 1: INTRODUCTION
1.1 Background……………………………………………………………………………2
1.2 Objectives…………………………………………………………………………….3
1.3 Purpose, Scope, and Applicability…………………………………………………….4
1.3.1 Purpose……………………………………………………………………...4
1.3.2 Scope…………………………………………………………………….…4
1.3.3 Applicability……………………………………………………….……….4
1.4 Achievements…………………………………………………………………………5
1.5 Organization of Report……………………………………………………………….6
CHAPTER 2: SURVEY OF TECHNOLOGIES
2.1 System Requirement……………………………………………………………….…8
2.1.1 Front-End Technologies…………………………………………….………8
2.1.2 Back-End Technologies…………………………………………………….9
2.1.3 Database Management…………………………………………………….11
2.1.4 Software Requirements………………………………………….…………15
2.1.5 Hardware Requirements……………………………………………………16
CHAPTER 3: REQUIREMENTS AND ANALYSIS
3.1 Problem Definition………………………………………………………………….19
3.2 Requirements Specification………………………………………………………….20
3.3 Planning and Scheduling…………………………………………………………….21
3.4 Software and Hardware Requirements………………………………………………23
3.5 Preliminary Product Description…………………………………………………….24
3.6 Conceptual Models………………………………………………………………….24
CHAPTER 4: SYSTEM DESIGN
4.1 Basic Modules……………………………………………………………………….25
4.2 Data Design………………………………………………………………………….37
4.2.1 Schema Design…………………………………………………………….40
4.2.2 Data Integrity and Constraints…………………………………………….41
4.3 Procedural Design……………………………………………………………………42
4.3.1 Logic Diagrams…………………………………………………………….42
4.3.2 Data Structures…………………………………………………………….43
1
4.3.3 Algorithms Design………………………………………………….………44
4.4 User interface design…………………………………………………………….……47
4.5 Security Issues………………………………………………………………….…. ….50
4.6 Test Cases Design…………………………………………………………….….…….52
CHAPTER 5: IMPLEMENTATION AND TESTING
5.1 Coding Details………………………………………………………………………....55
5.2 Testing Approach………………………………………………………………………92
5.2.1 Unit Testing………………………………………………………………….92
5.2.2 Integrated testing…………………………………………………………….95
5.3 Modifications and Improvements…………………………………………….……….95
5.4 Test Cases……………………………………………………………………….….…95
CHAPTER 6: RESULTS AND DISCUSSION
6.1 Test Reports……………………………………………………………………………98
6.2 User Documentation………………………………………………………………….98
CHAPTER 7: CONCLUSIONS
7.1 Conclusion……………………………………………………………………………104
7.1.1 Significance of the System………………………………………………….104
7.2 Limitations of the System…………………………………………………………….104
7.3 Future Scope of the Project…………………………………………………………...106
REFERENCES
2
LIST OF TABLES
SR.NO. PAGE.NO.
Table 1: Users Table……………………………………………………………………….37
Table 2: Attendance Table……………………………………………............................................38
Table 3: Settings Table…………………………………………………………………………….38
Table 4: Face Recognition Table...………………………………………………...........................39
3
4
CHAPTER 1
INTRODUCTION
1
1.1 Background
A face recognition attendance system is designed to automate the process of
recording attendance using facial recognition technology. This approach has gained popularity
due to its efficiency and accuracy, addressing many limitations found in traditional attendance
methods like roll calls or manual sign-ins.
Automated facial recognition was pioneered in the 1960s by Woody Bledsoe, Helen Chan
Wolf, and Charles Bisson, whose work focused on teaching computers to recognize human
faces. Their early facial recognition project in facial recognition was called "man- machine"
because a human was required first to locate in an image the coordinates of facial features before
their use in computerized recognition.
In 1993, DARPA and the Army Research Laboratory began a face recognition technology
program called FERET to develop "automatic face recognition capabilities" that could be used
in the real world for "helping security, intelligence and law enforcement personnel perform
their duties more effectively and efficiently." Face recognition systems that had been tested in
research labs were evaluated and the FERET tests found that while the performance of
existing automated facial recognition systems varied, a handful of existing methods could
viably be used to recognize faces in still images taken in a controlled environment.
The late 1990s and early 2000s saw a rise in biometric authentication systems for security
applications. As these technologies matured, they began to be adopted in various fields,
including security, banking, and later, in educational settings.
2
1.2 Objectives
The Face Recognition Attendance System is designed with a host of key goals in mind:
to enhance efficiency and accuracy on attendance recording, for security, education, and
banking fields. One of the main objectives of the system is the reduce amounts of efforts and
hours spent by humans in tracking attendance, which reduces errors to a minimum and saves
user time. Here are the primary objectives:
3
1.3 Purpose, Scope, and Applicability
1.3.1 Purpose
The purpose of a face recognition attendance system It includes a number of key objectives
that contribute to making the attendance tracking more effective and accurate. Here are the
key purposes of this project: Automation of Attendance Tracking, Increased Accuracy, Real-
Time Updates, Real-Time Updates, Improved Data Management, Efficiency in
Administrative Processes, providing User-Friendly Experience, Support for Analytics and
Insights and Adaptability and Versatility. Overall, face recognition attendance can be
developed to ensure efficiency, accuracy, and safety for attendance tracking, hence this tool
is much needed in any organization that wants to upgrade its procedural operations.
1.3.2 Scope
The scope of a face recognition attendance system encompasses a robust integration of
advanced biometric technology aimed at simplifying attendee tracking across businesses. This
system will provide user the help which enabling real-time attendance recording and reporting
presences of other in various fields. It is designed to be very user-friendly, with the user
interface accessible on both mobile and desktop for convenience to the administrator and
employee. Furthermore, the scope includes scalability to support a range of organizational
sizes, from small businesses to large enterprises, while also providing data analytics features
to discern attendance trends and patterns that aid in decision-making.
1.3.3 Applicability
A face recognition attendance system is highly applicable across various sectors,
enhancing operational efficiency and accuracy. In educational institutions, it automates
attendance tracking, saving time and reducing administrative tasks. The technology also
benefits event management by simplifying guest check-ins and enhancing security.
Additionally, it aids healthcare by tracking patient visits while ensuring compliance with
regulations. Overall, these systems improve accountability, security, and resource
management, making them essential tools for modern organizations while adhering to ethical
standards regarding biometric data use.
4
1.4 Achievements
The implementation of a face recognition attendance system and significantly
transforming traditional attendance tracking methods across various sectors. First and
foremost, these systems have drastically reduced the time and effort spent on manual
attendance processes, allowing for real-time recording and instant reporting. This automation
minimizes human error and enhances accuracy, leading to better data integrity for both payroll
and performance evaluation.
Another key achievement is the enhanced resource management provided by the application.
By allowing for real-time recording and instant reporting this system provide protection against
unauthorized access in organization.
5
1.5 Organization of Report
The report is structured as follows:
6
CHAPTER 2
SURVEY OF TECHNOLOGIES
7
In building the "Face Recognition Attendance" system, the following technologies and
tools are employed to ensure smooth functionality, efficiency, and a good user experience.
These technologies are grouped into front-end, back-end, database, software, and hardware
requirements.
A survey of technologies for a face recognition attendance system involves exploring various
components and methodologies that enable the implementation of such systems. Here’s an
overview of key technologies and considerations:
The development of the Face Recognition Attendance System involves several critical
technologies that contribute to its functionality, speed, and user experience. This chapter
outlines the key components utilized in the project, including front-end GUI tools, face
detection and recognition libraries, back-end programming languages, and database systems.
The integration of these technologies ensures the system can accurately recognize individuals,
log attendance data securely, and offer a user-friendly interface for administrators and users
alike.
CustomTkinter builds on Tkinter to give your apps a more modern look. With pre-built hemes
(dark, light, system) and sleek widgets, CustomTkinter helps you break away from the dated
feel of default Tkinter interfaces.
8
2.1.2 Back-End Technologies
The back end is the backbone of the application, responsible for business logic, server-side
operations, and database management.
PYTHON
Python is a popular high-level general purpose programming language kw readability and
versatility. It was created by Guido van Rossum and first released in 1991 here are some
key points about Python
9
5. Dynamically Typed: With dynamic typing, Python allows developers to assign
values to variables without explicitly declaring their types. This feature simplifies
coding, but it also requires careful management of variable types to avoid runtime
errors. The flexibility of dynamic typing can speed up the development process,
especially during prototyping and iterative development.
development process, especially during prototyping and iterativedevelopment.
10
Data Integrity: SQL ensures data consistency and integrity, especially with features like
foreign key constraints, which help maintain relationships between different tables (e.g.,
users and borrowed books).
Database
SQLite
What is SQLite?
SQLite is an open-source, embedded database engine that’s totally different from traditional
client– server models like MySQL, SQL Server, or Oracle Database. Instead of running as a
separate service, the SQLite engine gets embedded right into your application. This means no
server setup, no configuration hassles—just a simple, single file that holds your entire database.
It’s super popular for mobile apps, small to medium websites, and even in desktop applications,
thanks to its speed and simplicity.
11
Key Features of SQLite
2. Database Operations
SQLite supports all the essential operations on tables, rows, columns, and indexes. This
means it’s straightforward to create, read, update, and delete data without needing a full-
blown server infrastructure.
3. Relational Structure
Just like other relational databases, SQLite lets you define relationships between tables
(i.e., rows and columns). This setup keeps your data well-organized and ensures
everything remains meaningful and easy to query.
4 Referential Integrity
SQLite supports foreign keys and referential integrity to keep table relationships
consistent—though you might need to enable this feature in your database settings. This is
crucial for maintaining data accuracy in multi-table setups.
5 Automatic Indexing
While SQLite doesn’t automatically update indexes as aggressively as some server-based
systems, it does offer robust tools for creating and managing indexes. This approach helps
keep your queries snappy and your data retrieval efficient.
6 SQL Support
SQLite allows you to run a broad range of SQL queries for fetching and manipulating data.
You can even combine multiple tables in a single query to produce dynamic, powerful
results, all within a self-contained environment.
12
How Does SQLite Work?
SQLite is unlike traditional databases such as MySQL, which rely on a client–server model.
Instead, SQLite operates as a serverless, embedded system, meaning it runs within your
application rather than as a separate service. Below is a breakdown of its core components
and workflow.
1 Database Creation:
SQLite creates a single database file on disk, containing all tables, indexes, and data. This
single-file design makes it exceptionally portable and easy to integrate into various
environments, from mobile apps to desktop software.
2 Application Integration:
Because SQLite is embedded, your application interacts directly with the SQLite library. Whether
you’re using a graphical user interface (GUI), a command line, or a specific programming language, all
SQL queries are executed within the same process as your application. This setup removes the need for
separate network communication and simplifies deployment.
3 Data Processing:
The SQLite engine processes all SQL instructions internally. When your
application sends a query, SQLite reads from or writes to the database file and
then returns the results—no external server required. This direct
communication reduces latency and keeps performance high, especially for
smaller-scale or single-user applications.
5 Lightweight Architecture:
SQLite’s design philosophy prioritizes minimal overhead without
sacrificing essential database functionality. Because it doesn’t require a
dedicated server or additional services, it’s well-suited for devices with
limited resources, such as mobile phones and IoT devices. Its small
footprint also streamlines development, since you don’t have to configure
or maintain a separate server environment.
13
14
2.1.4 Software Requirements:
To develop, test, and run the "Face Recognition Attendance" system, the following
software tools are essential:
Operating System:
The development environment is built on Windows 10 Home Single Language,
which provides a stable platform for coding and testing.
Visual Studio Code:
This is the primary code editor used for writing HTML, CSS, JavaScript, and PHP. It
supports numerous extensions and offers debugging, version control, and
customization features, making it an ideal environment for application development
15
Excel:
Microsoft Excel is a powerful spreadsheet program that is part of the Microsoft Office suite.
It is widely used for data analysis, financial modelling, and various business applications.
With its robust features, Excel allows users to organize, format, and calculate data
effective
16
2.1.5 Hardware Requirements:
The hardware specifications ensure that the development environment can handle the
application’s requirements and run smoothly.
Device name: DESKTOP-3GJCSNE.
The device used for development is a desktop computer with sufficient processing power
and memory to manage the application’s demands.
Name of Processor:
The system is powered by the Intel(R) Core (TM) i5-10400F CPU @ 2.90GHz
2.90 GHz, providing adequate performance for running developmenttools, virtual
environments, and local servers.
RAM:
With 8 GB of RAM, the system can handle multitasking, allowing the development
environment, database server, and web server to run simultaneously without performance
degradation.
System type:
Hardware Components
Cameras: High-resolution cameras are essential for capturing clear images. Options
include:
Processing Units: Powerful CPUs or GPUs are needed for real-time processing,
especially when using deep learning models
17
CHAPTER 3
REQUIREMENTS AND ANALYSIS
18
3.1 Problem Definition
A face recognition attendance system aims to automate attendance tracking in work field like
schools and workplaces by using face recognition technology to its maximum, but they face
several operational challenges.
Key Problems:
Accuracy and Reliability: Achieving high levels of accuracy in facial recognition can be
challenging. Factors such as lighting conditions, varying angles, age, and temporary changes
in appearance (like facial hair or glasses) can lead to false positives or negatives, undermining
the trustworthiness of the system.
Privacy and Data Security: The use of biometric data raises significant privacy concerns.
Ensuring that the system complies with data protection regulations, such as GDPR, is crucial.
Users may be wary of how their facial data is collected, stored, and used, necessitating
transparent policies and robust security measures to protect this sensitive information.
Integration with Existing Systems: Integration of the facial recognition attendance system
with current institutional or organizational infrastructure, like learning management systems
or HR tools, can be complex. This requires ensuring compatibility and smooth data flow
between different platforms, which can be technically challenging.
19
3.2 Requirements Specification
To address the challenges outlined in the problem definition, the "Face
Recognition Attendance System” must meet the following functional
and non- functional requirements:
1. Functional Requirements
User Authentication: The system must allow users to register by capturing multiple facial
images under diverse conditions (varied lighting, angles, and expressions) to enhance
recognition accuracy.
Real-Time Attendance Marking: The system must provide real-time attendance
marking by instantly comparing the captured facial data with the registered users during
check-in.
Error Handling: The system must handle recognition errors gracefully, offering options
for manual attendance marking in case of failure to identify a user.
Reporting and Analytics: He system must generate customizable and downloadable
attendance reports, including features like absenteeism trends, average attendance rates,
and user statistics.
User Management: The system should provide functionalities for administrators to
manage user profiles, including adding, updating, or deleting user records.
Integration: The system must integrate with existing attendance management systems
or databases to allow seamless data exchange and storage.
2. Non-Functional Requirements
Performance: The system must process facial recognition within 2 seconds per individual
under normal operating conditions to ensure efficient attendance marking.
Accuracy: The system should achieve a recognition accuracy rate of at least 95% to
minimize errors in attendance marking.
Scalability: The system must be able to scale to support at least 1,000 concurrent users
without degradation in performance Non-Functional Requirements
Performance: The system must process facial recognition within 2 seconds per
individual under normal operating conditions to ensure efficient attendance marking.
20
Accuracy: The system should achieve a recognition accuracy rate of at least 95% to
minimize errors in attendance marking.
Scalability: The system must be able to scale to support at least 1,000 concurrent
users without degradation in performance.
Security: Biometric data must be encrypted during transmission and storage to prevent
unauthorized access. The system should also implement user access controls to protect
sensitive information.
Usability: The user interface must be intuitive and accessible, allowing users of
varying technical proficiency to navigate and operate the system easily.
Security: User data, including borrowing history and personal information, must be
securely stored and protected against unauthorized access. The system should also
implement secure login mechanisms.
Speed: The LMS should process requests quickly, such as searching for books,
generating reports, or managing inventory. Delays could negatively impact user
satisfaction.
Reliability: The system must always be reliable and available, ensuring that users and
administrators can access it without downtime or significant disruptions.
Project Phases:
3. Requirement Analysis (Duration: 2 weeks):
21
4. System Design(Duration: 3 weeks):
o Execute user acceptance testing (UAT) with a select group of end users.
7. Deployment (Duration: 2 weeks):
6 Post-Deployment Support:
22
3.4 Software and Hardware Requirements
The following software and hardware are required to support the
development and operation of the " Face Recognition Attendance” System:
Hardware Requirements:
Software Requirements:
Python: Popular choice for computer vision tasks due to its extensive libraries like
OpenCV and face recognition.
MySQL: For storing user data, attendance records, and other relevant information.
Version Control: Git for tracking changes and collaboration among different team
members.
Cloud Services (optional): AWS, Google Cloud, or Azure for hosting the application
and Datab
23
3.5 Preliminary Product Description
Face Track is an advanced Face Recognition Attendance System designed to streamline
attendance tracking in educational institutions, corporate environments, and events. Using
state-of-the-art computer vision and artificial intelligence technology, Face Track automates
attendance, eliminating the need for manual registration and form-based processes.
1. Automatic Face Recognition:
The system processes incoming facial information in real time, marking attendance as
soon as a person enters a specified location, and ensures that meeting records are instantly
updated
3 User-Friendly Interface:
Face Track ensures data security through encrypted data transmission and secure storage
methods, complying with relevant data protection regulations.
5 Integration Capabilities:
The system can easily integrate with existing management systems (like LMS or
HRMS) to facilitate seamless data sharing and attendance reconciliation.
7 Scalability:
24
3.6 Conceptual Models
Conceptual models represent the overall structure and relationships between key
components of the " Face Recognition Attendance " System. These models guide the
design of the system and help visualize how different parts of this system interact
25
3.6.2 First Level DFD:
26
3.6.3 Entity-Relationship Diagram:
27
3.6.4 State Chart Diagram:
28
3.6.5 Use Case Diagram:
29
3.6.6 Activity Diagram:
30
3.6.7 Component Diagram
31
3.6.7 Class Diagram:
32
3.6.8 Sequence Diagram:
33
CHAPTER 4
SYSTEM DESIGN
34
1. 4.1 Basic Modules
1. Capture Module
Camera Integration: Interfaces with webcams or IP cameras to capture real-time
video or images of individuals.
Face Localization: Identifies and locates faces in the captured images using
techniques like Haar Cascades, Local Binary Patterns (LBP), or deep learning models
(e.g., MTCNN).
Multiple Face Detection: Handles scenarios where multiple faces are in the frame.
Feature Extraction: Converts detected faces into feature vectors using algorithms
like Eigenfaces, Fisherfaces, or modern deep learning approaches (e.g., CNNs).
Matching Algorithm: Matches the extracted features against a database of known
faces to identify individuals.
Data Management: Handles CRUD operations (Create, Read, Update, Delete) for
user data.
35
6. Report Generation:
Alerts and Notifications: Sends notifications for absent users or any discrepancies
in attendance.
7. Security Module
Authentication: Verifies user access to the system, ensuring that only authorized
personnel can manage data.
Alerts and Notifications: Sends notifications for absent users or any discrepancies
in attendance.
9 Security Module
36
4.2 Data Design
This section focuses on structuring the data to support LMS functionality.
Table 1: Users Table
37
Table 2: Attendance Table
38
Table Name: Setting table
39
4.2.1 Schema Design:
The schema design is a blueprint for how the data is structured in the LMS. Based on the
provided tables, we can represent the relationships between the entities.
40
1.1 4.2.2Data Integrity and Constraints:
• Primary Key Constraints
o Ensure that each table has a unique identifier for its rows (e.g., user_id,
attendance_id, recognition_id, setting_id).
• Foreign Key Constraints
o Maintain referential integrity between related tables (e.g., user_id).
• Unique Constraints
o To maintain the uniqueness of certain fields (e.g., Profile Image)
• Not Null Constraints
o Fields that must always contain a value should have a NOT NULL constraint
(First_name, Last_name, capture_image, user_id, check_in_time, date, and
status, etc).
• Default Values
o Setting default values can help maintain data integrity by providing a fallback
for certain fields (e.g., Status).
• Check Constraints
o Check constraints can enforce specific business rules directly at the database level
(status, check_out_time, check_in_time, confidence_score)
• Cascade Updates and Deletes
o Define cascading actions on foreign keys if appropriate (remove or nullify
related records).
41
4.3 Procedural Design
This focuses on how the system will operate functionally.
Activity Diagram
42
4.3.2 Data Structures:
Data structures are critical for managing data in the Face Recognition Attendance
System (FRAS). The following will be utilized:
1. Arrays:
o Store collections of User, Attendance, FaceRecognition, and Settings records
for quick, indexed access.
o Example: Array of User objects with attributes user_id, first_name, last_name,
email, phone, capture_image, and roll_no.
2. Linked Lists:
o Manage dynamic attendance records in strict chronological order.
o Example: Linked list of AttendanceRecord nodes, each containing user_id,
check_in_time, check_out_time, status, and date, allowing O(1) insertion of
new events.
3. Hash Tables:
o Enable O(1) lookups by unique identifiers.
o Example:
Hash table mapping user_id → User details for instant profile retrieval.
Hash table mapping recognition_id → FaceRecognition details
(user_id, recognition_time, confidence_score, image_data,
error_message).
Hash table mapping setting_name → setting_value for config access.
4. Trees:
o Organize hierarchical or sorted data, e.g. configuration settings or decision
logic.
o Example: Binary search tree of Settings entries for efficient retrieval by
setting_name.
5. Graphs:
o Represent relationships or state-transitions, such as attendance flows or
recognition pipelines.
o Example: Directed graph modelling transitions between attendance statuses
(e.g. Present → Absent, Absent → Late).
43
6. Queues:
o Handle incoming face-recognition jobs and pending attendance check-ins in
FIFO order.
o Example: Queue of recognition tasks, each with recognition_id, user_id, and
image_data, ensuring orderly processing.
Steps:
1.Input: User details (first name, last name, email, phone number, profile image).
2.Validate Input:
44
• Attendance Tracking Algorithm
3.Face Detection:
Use a face detection model (e.g., Haar Cascade or DNN) to identify faces.
4.Feature Extraction:
Compare extracted features with the data in the Face Recognition table.
Insert data into the FaceRecognition table with the user ID, recognition time,
confidence score, and any error message if applicable.
7.Output: Confirm attendance status (Present or Absent) along with a recognition success
message
45
• Attendance Reporting Algorithm
Retrieve records from the Attendance table based on the user ID and specified
date range.
3. Process Data:
2.Update or Insert:
3.Output: Return a success message confirming the setting was updated or cerate.
46
4.4 User Interface Design
The user interface (UI) design for a Face Recognition Attendance System should focus on
simplicity, clarity, and ease of use. The following key UI components are included in the
"Face Recognition Attendance" system:
1. Login Screen
o Email/Username Field: Input box for entering the user's email or username.
o Facial Recognition Option: For admins who wish to use facial login instead
of typing in credentials.
2. Admin Dashboard
Purpose: Central control panel for administrators to view attendance, manage users,
and configure settings.
Elements:
47
3. User Management Screen
48
5 Attendance Records Screen
o Date Range Selector: Choose the period for the attendance report.
6 Settings Screen
o Setting Name: Text field for setting name (e.g., recognition threshold).
o Setting Value: Input field for the value (e.g., 85% confidence score).
49
4.5 Security Issues
Security is a critical aspect of the system, particularly when dealing with user data such as
their E-mail, Phone_no, and etc. The "Face Recognition Attendance System” addresses the
following security issues:
1. Biometric Data Security:
o Ensure proper access controls and restrict access to sensitive biometric data to
authorized personnel only.
2. Data Breaches and Hacking:
o Regularly update the system with security patches and protect against common
vulnerabilities (e.g., SQL injection, cross-site scripting).
o Implement firewalls and intrusion detection systems (IDS) to monitor for suspicious
activity.
o Encrypt sensitive data both in transit and at rest, and ensure secure API
communication using HTTPS and TLS.
3. Privacy Concerns:
o Ensure compliance with data protection laws by clearly outlining data collection,
storage, and usage policies.
o Obtain explicit consent from users before capturing and using their facial data.
o Provide users with the ability to request deletion of their biometric data when they
leave the organization.
o Continuously improve and update face recognition algorithms with diverse and large
datasets to reduce error rates.
o Combine face recognition with additional authentication methods to minimize the risk
of incorrect identification.
o Set an appropriate confidence threshold for face recognition to reduce false positives
50
5. User Authentication:
51
4.6 Test Cases Design
Testing ensures that the "Face Recognition Attendance System " works as expected and
is free from bugs. Some of the core test cases include:
1. User Authentication and Login Testing
Test Scenario: Verify user authentication via face recognition.
Expected Result: The system correctly identifies the user and logs them in if the
face is recognized with sufficient confidence.
2. Check-in and Check-out Attendance Testing
Test Scenario: Verify the attendance check-in and check-out process.
Expected Result: The system should log the check-in and check-out times
accurately for the recognized user.
Test Scenario: Verify that the system processes face recognition attempts
based on confidence score thresholds.
Expected Result: If the confidence score falls below the threshold, the
system should reject the recognition attempt.
Test Scenario: Test system performance when multiple users try to check in
simultaneously.
Expected Result: The system should handle multiple check-ins without
slowing down or crashing.
Expected Result: The system should prevent unauthorized access to facial data
and ensure logs cannot be altered without proper permissions.
52
7. Data Logging and Audit Trail Testing
• Test Scenario: Verify that all system actions are logged.
• Expected Result: The system should log all actions, including successful and failed
recognition attempts, with timestamps.
53
CHAPTER 5
IMPLEMENTATION AND TESTING
54
5.1 CODE
# ---------------------------
# AUTHENTICATION APPLICATION
# ---------------------------
class AuthApp(ctk.CTk):
def __init__(self):
super().__init__()
self.title("Login / Signup")
self.geometry("500x600")
self.resizable(True, True)
self.configure(fg_color="#1a2a6c")
self.conn = get_db_connection()
self.cursor = self.conn.cursor()
self.profile_img_path = None
# Create the form background with width and height in the constructor
self.form_bg = ctk.CTkFrame(self, fg_color="white", corner_radius=20, width=420,
height=540)
self.form_bg.place(relx=0.5, rely=0.5, anchor="center")
def clear_frame(self):
for widget in self.container.winfo_children():
widget.destroy()
def show_login(self):
self.clear_frame()
self.profile_img = create_circular_image(None)
self.profile_label = ctk.CTkLabel(self.container, image=self.profile_img, text="")
self.profile_label.pack(pady=(20, 10))
self.login_input = ctk.CTkEntry(self.container, placeholder_text="Username or Email",
width=300, height=40)
self.login_input.pack(pady=10)
self.login_input.bind("<KeyRelease>", self.update_profile_image)
self.password = ctk.CTkEntry(self.container, placeholder_text="Password", show="*",
width=300, height=40)
self.password.pack(pady=10)
self.login_error = ctk.CTkLabel(self.container, text="", text_color="red")
self.login_error.pack()
self.login_btn = ctk.CTkButton(self.container, text="LOGIN", width=300, height=40,
fg_color="black", command=self.login)
self.login_btn.pack(pady=20)
ctk.CTkLabel(self.container, text="Don't have an account? ").pack()
self.signup_link = ctk.CTkButton(self.container, text="Sign Up",
command=self.show_signup, fg_color="black", hover_color="#1a2a6c")
self.signup_link.pack()
55
def update_profile_image(self, event=None):
login_cred = self.login_input.get().strip()
if login_cred:
self.cursor.execute("SELECT profile_image FROM users WHERE username = ? OR
email = ?", (login_cred, login_cred))
result = self.cursor.fetchone()
img_path = result[0] if result else None
self.profile_img = create_circular_image(img_path)
self.profile_label.configure(image=self.profile_img)
def show_signup(self):
self.clear_frame()
self.profile_img_path = None
self.profile_img = create_circular_image(None)
self.profile_label = ctk.CTkLabel(self.container, image=self.profile_img, text="")
self.profile_label.pack(pady=(20, 10))
self.profile_label.bind("<Button-1>", lambda e: self.upload_image())
self.username_entry = ctk.CTkEntry(self.container, placeholder_text="Username",
width=300, height=40)
self.username_entry.pack(pady=10)
self.email_entry = ctk.CTkEntry(self.container, placeholder_text="Email", width=300,
height=40)
self.email_entry.pack(pady=10)
self.password_entry = ctk.CTkEntry(self.container, placeholder_text="Password",
show="*", width=300, height=40)
self.password_entry.pack(pady=10)
self.confirm_password_entry = ctk.CTkEntry(self.container, placeholder_text="Confirm
Password", show="*", width=300, height=40)
self.confirm_password_entry.pack(pady=10)
self.signup_error = ctk.CTkLabel(self.container, text="", text_color="red")
self.signup_error.pack()
self.signup_btn = ctk.CTkButton(self.container, text="SIGN UP", width=300,
height=40, command=self.signup)
self.signup_btn.pack(pady=20)
ctk.CTkLabel(self.container, text="Already have an account? ").pack()
self.login_link = ctk.CTkButton(self.container, text="Login",
command=self.show_login, fg_color="black", hover_color="#1a2a6c")
self.login_link.pack()
def upload_image(self):
file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg")])
if file_path:
try:
os.makedirs(PROFILE_IMAGES_DIR, exist_ok=True)
filename = f"user_{int(time.time())}.jpg"
save_path = os.path.join(PROFILE_IMAGES_DIR, filename)
Image.open(file_path).convert("RGB").save(save_path)
self.profile_img_path = save_path
self.profile_img = create_circular_image(save_path)
self.profile_label.configure(image=self.profile_img)
56
except Exception as e:
messagebox.showerror("Error", f"Failed to load image: {e}")
def login(self):
self.conn = get_db_connection()
self.cursor = self.conn.cursor()
login_cred = self.login_input.get().strip()
password = self.password.get().strip()
self.cursor.execute("SELECT rowid as id, username, profile_image, role FROM users
WHERE (username = ? OR email = ?) AND password = ?",
(login_cred, login_cred, hash_password(password)))
result = self.cursor.fetchone()
if result:
save_session(result["username"], result["profile_image"] or "")
self.destroy()
if result["role"] == "admin":
AdminPanel(result["id"], result["username"], result["role"]).mainloop()
else:
FaceRecognitionApp().mainloop()
else:
self.login_error.configure(text="Invalid credentials")
def signup(self):
self.conn = get_db_connection()
self.cursor = self.conn.cursor()
username = self.username_entry.get().strip()
email = self.email_entry.get().strip()
password = self.password_entry.get().strip()
confirm_password = self.confirm_password_entry.get().strip()
if not username:
self.signup_error.configure(text="Username cannot be empty")
return
if not re.match(r"^\S+$", username):
self.signup_error.configure(text="Username cannot contain spaces")
return
if not email:
self.signup_error.configure(text="Email cannot be empty")
return
if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
self.signup_error.configure(text="Invalid email format")
return
if not password:
self.signup_error.configure(text="Password cannot be empty")
return
if password != confirm_password:
self.signup_error.configure(text="Passwords do not match")
return
try:
role = "admin" if username.lower() == "admin" else "user"
57
self.cursor.execute("INSERT INTO users (username, email, password, role,
profile_image, created_at) VALUES (?, ?, ?, ?, ?, ?)",
(username, email, hash_password(password), role, self.profile_img_path,
datetime.datetime.now().isoformat()))
self.conn.commit()
messagebox.showinfo("Success", "Account created successfully!")
self.show_login()
except sqlite3.IntegrityError:
self.signup_error.configure(text="Username or email already exists")
def mainloop(self):
super().mainloop()
# ---------------------------
# FACE RECOGNITION INTERFACE
# ---------------------------
class FaceRecognitionApp(ctk.CTk):
def __init__(self):
super().__init__()
self.geometry('1200x700+100+50')
self.title('Face Recognition Attendance System')
self.main_frame = ctk.CTkFrame(self)
self.main_frame.pack(fill="both", expand=True)
self.add_menu_items()
self.load_background()
self.add_title_text()
self.update_background()
self.bind("<Configure>", self.on_resize)
def get_logged_in_user(self):
return get_session_user()
def load_background(self):
bg_path = os.path.join(IMAGES_DIR, "interface.jpg")
if os.path.exists(bg_path):
self.bg_image = Image.open(bg_path)
else:
self.bg_image = Image.new("RGB", (100, 100), "gray")
self.bg_photo = None
self.bg_label = ctk.CTkLabel(self.main_frame, text="")
self.bg_label.pack(fill="both", expand=True)
58
subprocess.Popen(["xdg-open", folder_path])
except Exception as e:
messagebox.showerror("Error", f"Failed to open folder: {e}")
def student_registration(self):
subprocess.Popen(["python", "student_registration_form.py"])
def student_detail(self):
subprocess.Popen(["python", "show_info_window.py"])
def Helpdesk(self):
subprocess.Popen(["python", "helpdesk.py"])
def trian(self):
subprocess.Popen(["python", "train_model.py"])
def Attendance(self):
subprocess.Popen(["python", "Attendance.py"])
def add_menu_items(self):
self.menu_frame = ctk.CTkFrame(self.main_frame, width=250, corner_radius=0,
fg_color="#060d1f")
self.menu_frame.pack(side="left", fill="y", padx=10, pady=10)
username, profile_img = self.get_logged_in_user()
self.add_user_status(username or "Admin", "User", profile_img)
menu_items = [
("Face Recognition", self.Attendance),
("Train Data", self.trian),
("Student Registration", self.student_registration),
("Student Detail", self.student_detail),
("Attendance Record", show_attendance_grid),
("Face Data", lambda: self.open_folder(os.path.join(os.getcwd(),
FACE_IMAGES_DIR))),
("Help Desk", self.Helpdesk),
("Exit", self.logout)
]
for text, command in menu_items:
ctk.CTkButton(
self.menu_frame,
text=text,
font=("Helvetica", 14),
fg_color="black",
hover_color="#000080",
corner_radius=10,
height=40,
width=250,
border_width=2,
border_color="white",
command=command
).pack(fill="x", padx=10, pady=5)
59
def add_user_status(self, username, role, image_path=None, online=True):
self.user_frame = ctk.CTkFrame(self.menu_frame, fg_color="gray", corner_radius=10)
self.user_frame.pack(fill="x", padx=10, pady=10)
self.profile_img = create_circular_image(image_path)
self.user_photo_label = ctk.CTkLabel(self.user_frame, image=self.profile_img, text="",
width=80, height=80)
self.user_photo_label.pack(side="left", padx=5, pady=5)
status_text = "Online" if online else "Offline"
status_color = "lightgreen" if online else "red"
self.user_info = ctk.CTkLabel(
self.user_frame,
text=f"{username}\n({role}) {status_text}",
font=("Helvetica", 12, "bold"),
text_color=status_color,
anchor="w"
)
self.user_info.pack(side="left", padx=5, fill="both", expand=True)
self.dots_label = ctk.CTkLabel(self.user_frame, text="⋮", font=("Helvetica", 20, "bold"),
text_color="white")
self.dots_label.pack(side="right", padx=5)
self.dots_label.bind("<Button-1>", self.toggle_menu)
60
def update_user_status_image(self, image_path):
self.profile_img = create_circular_image(image_path)
self.user_photo_label.configure(image=self.profile_img)
def open_profile_panel(self):
profile_panel = ProfilePanel(self)
profile_panel.attributes("-topmost", True)
profile_panel.grab_set()
def open_admin_panel(self):
username, _ = get_session_user()
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT rowid as id, role FROM users WHERE username = ?",
(username,))
result = cur.fetchone()
conn.close()
if result and result["role"].lower() == "admin":
self.destroy()
AdminPanel(result["id"], username, result["role"]).mainloop()
else:
messagebox.showerror("Access Denied", "You are not authorized to access the Admin
Panel.")
def update_background(self):
try:
width = self.winfo_width()
height = self.winfo_height()
resized = self.bg_image.resize((width, height), Image.Resampling.LANCZOS)
self.bg_photo = ctk.CTkImage(light_image=resized, dark_image=resized,
size=(width, height))
self.bg_label.configure(image=self.bg_photo)
except Exception:
pass
def add_title_text(self):
self.title_label = ctk.CTkLabel(
self.main_frame,
text="Face Recognition Attendance System",
font=("Helvetica", 30, "bold"),
text_color="black",
bg_color="#ffffff"
)
self.title_label.place(relx=0.5, rely=0.1, anchor="center")
def logout(self):
61
if os.path.exists(SESSION_FILE):
os.remove(SESSION_FILE)
self.destroy()
os.execl(sys.executable, sys.executable, *sys.argv)
def mainloop(self):
super().mainloop()
62
return False
try:
email_exists, phone_exists = check_unique_email_phone(fields["Email"],
fields["Phone"])
if email_exists:
messagebox.showerror("Error", "Email already registered!")
return False
if phone_exists:
messagebox.showerror("Error", "Phone number already registered!")
return False
except Exception as e:
messagebox.showerror("Database Error", f"Could not verify uniqueness: {e}")
return False
return True
def clear():
global face_data, face_counter
student_id_entry.delete(0, ctk.END)
first_name_entry.delete(0, ctk.END)
last_name_entry.delete(0, ctk.END)
email_entry.delete(0, ctk.END)
phone_entry.delete(0, ctk.END)
age_entry.delete(0, ctk.END)
dob_entry.delete(0, ctk.END)
department_entry.set("Select Department..")
semester_entry.set("Select Semester..")
year_entry.delete(0, ctk.END)
gender_entry.set("Male")
for key in error_labels:
error_labels[key].configure(text="")
face_data = []
face_counter = 0
counter_label.configure(text=f"Captured: {face_counter}/100")
def save_student():
if len(face_data) < 100:
messagebox.showerror("Error", "Face data insufficient! Capture at least 100 images
before saving.")
return
if not validate_fields():
return
student_data = {
"student_id": student_id_entry.get().strip(),
"first_name": first_name_entry.get().strip(),
"last_name": last_name_entry.get().strip(),
"email": email_entry.get().strip(),
"phone": phone_entry.get().strip(),
"gender": gender_entry.get(),
"Age": age_entry.get().strip(),
"dob": dob_entry.get().strip(),
63
"department": department_entry.get(),
"semester": semester_entry.get(),
"year": year_entry.get().strip(),
"created_at": datetime.datetime.now()
}
sanitized_id = re.sub(r"[^\w\-]", "_", student_data["student_id"])
student_folder = os.path.join("face_images", sanitized_id)
try:
os.makedirs(student_folder, exist_ok=True)
for idx, img in enumerate(face_data[:100]):
img_filename = os.path.join(student_folder, f"{sanitized_id}_face_{idx+1:03d}.jpg")
Image.fromarray(img, 'L').save(img_filename, quality=95, optimize=True)
face_array = np.array([img.flatten() for img in face_data[:100]])
np.save(os.path.join(student_folder, f"face_data_{sanitized_id}.npy"), face_array)
insert_student(
student_data["student_id"], student_data["first_name"], student_data["last_name"],
student_data["email"], student_data["phone"], student_data["gender"],
student_data["Age"],
student_data["dob"], student_data["department"], student_data["semester"],
student_data["year"], student_data["created_at"], student_folder
)
messagebox.showinfo("Success", "Student details saved successfully!")
clear()
except Exception as e:
messagebox.showerror("Error", f"Failed to save student: {e}")
if os.path.exists(student_folder):
for filename in os.listdir(student_folder):
file_path = os.path.join(student_folder, filename)
try:
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as cleanup_error:
print(f"Error deleting {file_path}: {cleanup_error}")
def toggle_face_capture():
global cap, face_counter, last_capture_time, capturing_active, face_data
if not validate_fields():
return
student_id = student_id_entry.get().strip()
sanitized_id = re.sub(r"[^\w\-]", "_", student_id)
if not sanitized_id:
messagebox.showerror("Error", "Invalid Student ID format!")
return
if cap is None or not cap.isOpened():
try:
face_counter = 0
face_data.clear()
last_capture_time = cv2.getTickCount() / cv2.getTickFrequency()
capturing_active = True
for attempt in range(3):
64
cap = cv2.VideoCapture(attempt % 2, cv2.CAP_DSHOW)
if cap.isOpened():
break
if attempt == 2:
raise RuntimeError("Could not initialize camera after multiple attempts")
cv2.waitKey(500)
capture_button_widget.configure(text="Stop Capture")
counter_label.configure(text=f"Captured: {face_counter}/100")
update_frame()
except Exception as e:
if cap and cap.isOpened():
cap.release()
capturing_active = False
messagebox.showerror("Camera Error", f"Failed to initialize camera: {e}")
else:
capturing_active = False
cap.release()
cap = None
capture_button_widget.configure(text="Start Face Capture")
if face_counter >= 100:
messagebox.showinfo("Capture Complete", "Successfully captured 100 face
images!")
else:
messagebox.showwarning("Capture Incomplete", f"Captured {face_counter} images.
Need at least 100.")
def update_frame():
global cap, face_counter, last_capture_time, capturing_active, face_data
if not capturing_active or cap is None or not cap.isOpened():
return
try:
ret, frame = cap.read()
if not ret:
raise RuntimeError("Failed to read camera frame")
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5,
minSize=(100, 100))
if len(faces) > 0:
(x, y, w, h) = max(faces, key=lambda f: f[2] * f[3])
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 4)
current_time = cv2.getTickCount() / cv2.getTickFrequency()
if face_counter < 100 and (current_time - last_capture_time) > 0.5 and w > 100 and h
> 100:
face_img = cv2.resize(cv2.cvtColor(frame[y:y+h, x:x+w],
cv2.COLOR_BGR2GRAY), (500, 400))
face_data.append(face_img)
face_counter += 1
last_capture_time = current_time
counter_label.configure(text=f"Captured: {face_counter}/100")
display_frame = cv2.resize(frame, (500, 400))
65
display_frame = cv2.cvtColor(display_frame, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(display_frame)
ctk_img = CTkImage(light_image=pil_img, dark_image=pil_img, size=(500, 400))
face_label.configure(image=ctk_img)
face_label.image = ctk_img
if capturing_active and face_counter < 100:
face_label.after(50, update_frame)
else:
toggle_face_capture()
except Exception as e:
capturing_active = False
messagebox.showerror("Capture Error", f"Error during capture: {e}")
if cap:
cap.release()
cap = None
def open_calendar():
def set_date():
dob_entry.delete(0, ctk.END)
dob_entry.insert(0, cal.get_date())
top.destroy()
top = tk.Toplevel(root)
top.title("Select Date of Birth")
cal = Calendar(top, selectmode='day', date_pattern='y-mm-dd')
cal.pack(padx=10, pady=10)
tk.Button(top, text="OK", command=set_date).pack(pady=10)
def show_detail():
try:
subprocess.Popen(["python", "show_info_window.py"])
except FileNotFoundError:
messagebox.showerror("Error", "Student details window not found!")
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=2)
root.grid_rowconfigure(0, weight=1)
66
("Gender:", ctk.CTkComboBox(form_frame, values=["Male", "Female", "Other"],
width=220)),
("Age:", ctk.CTkEntry(form_frame, width=220)),
("Date of Birth:", ctk.CTkEntry(form_frame, width=170)),
("Department:", ctk.CTkComboBox(form_frame, values=['Select Department..', 'BSc IT',
'BSc CS', 'B.ed', 'Bcom', 'Baff', 'BSc'], width=220)),
("Semester:", ctk.CTkComboBox(form_frame, values=["Select Semester..", "Semester
1(FY)", "Semester 2(FY)", "Semester 3(SY)", "Semester 4(SY)", "Semester 5(TY)",
"Semester 6(TY)", "Semester 7(FY4)", "Semester 8(FY4)"], width=220)),
("Graduation Year:", ctk.CTkEntry(form_frame, width=220))
]
ordered_entries = []
gender_entry.set("Male")
department_entry.set("Select Department..")
semester_entry.set("Select Semester..")
67
# Bind key release events for real time validation
student_id_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Student
ID", validate_student_id))
# Added focus out binding for Student ID to ensure error message appears when leaving the
field
student_id_entry.bind("<FocusOut>", lambda event: real_time_validate(event, "Student ID",
validate_student_id))
first_name_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "First
Name", validate_first_name))
last_name_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Last
Name", validate_last_name))
email_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Email",
validate_email))
phone_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Phone",
validate_phone))
gender_entry.bind("<<ComboboxSelected>>", lambda event: update_error("Gender",
validate_gender(gender_entry.get())))
age_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Age",
validate_age))
dob_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Date of Birth",
validate_dob))
year_entry.bind("<KeyRelease>", lambda event: real_time_validate(event, "Graduation
Year", validate_year))
department_entry.bind("<<ComboboxSelected>>", lambda event:
update_error("Department", validate_department(department_entry.get())))
semester_entry.bind("<<ComboboxSelected>>", lambda event: update_error("Semester",
validate_semester(semester_entry.get())))
68
counter_label = ctk.CTkLabel(button_frame, text="Captured: 0/100", font=("Arial", 12),
text_color="black")
counter_label.grid(row=0, column=4, padx=10, pady=5, sticky="e")
def on_closing():
global cap
if cap:
cap.release()
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
69
import customtkinter as ctk
from tkinter import ttk, messagebox
from students_db import get_all_students, delete_student_from_db, get_student_by_id,
update_student_in_db
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")
class StudentInfoWindow(ctk.CTk):
def __init__(self):
super().__init__()
self.title("Student Information System")
self.geometry("1500x700")
self.resizable(False, False)
self.all_students = []
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(1, weight=1)
self.create_widgets()
self.load_students()
self.protocol("WM_DELETE_WINDOW", self.on_closing)
def create_widgets(self):
self.search_frame = ctk.CTkFrame(self)
self.search_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
self.search_var = ctk.StringVar()
self.search_entry = ctk.CTkEntry(self.search_frame, textvariable=self.search_var,
placeholder_text="Search by any field...", width=300)
self.search_entry.pack(side="left", fill="x", expand=True, padx=5, pady=5)
self.search_var.trace_add("write", self.filter_students)
70
self.update_btn.pack(side="left", padx=5, pady=5)
self.tree_frame = ctk.CTkFrame(self)
self.tree_frame.grid(row=1, column=0, padx=10, pady=(0, 10), sticky="nsew")
self.tree_frame.grid_columnconfigure(0, weight=1)
self.tree_frame.grid_rowconfigure(0, weight=1)
self.columns = (
"ID", "Student ID", "First Name", "Last Name", "Email", "Phone",
"Gender", "Age", "Date of Birth", "Department", "Semester", "Graduation Year",
"Created At", "Photo Path"
)
self.tree = ttk.Treeview(self.tree_frame, columns=self.columns, show="headings",
selectmode="browse")
self.vsb = ttk.Scrollbar(self.tree_frame, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=self.vsb.set)
self.tree.grid(row=0, column=0, sticky="nsew")
self.vsb.grid(row=0, column=1, sticky="ns")
def load_students(self):
try:
self.all_students = get_all_students()
self.tree.delete(*self.tree.get_children())
for student in self.all_students:
self.tree.insert("", "end", values=student)
except Exception as e:
71
import sqlite3
from utils import get_db_connection, ensure_directories
def initialize_db():
ensure_directories()
conn = get_db_connection('students.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id TEXT UNIQUE NOT NULL,
first_name TEXT,
last_name TEXT,
email TEXT UNIQUE NOT NULL,
phone TEXT UNIQUE NOT NULL,
gender TEXT,
age INTEGER,
date_of_birth TEXT,
department TEXT,
semester TEXT,
year TEXT,
created_at TEXT,
photo_path TEXT
)
72
"""
)
conn.commit()
conn.close()
print("Students database initialized successfully!")
def initialize_attendance_table():
ensure_directories()
conn = get_db_connection('students.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS attendance (
attendance_id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id TEXT NOT NULL,
name TEXT,
department TEXT,
timestamp TEXT,
status TEXT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
)
"""
)
conn.commit()
conn.close()
print("Attendance table initialized successfully!")
73
gender, age, date_of_birth, department, semester, year, created_at, photo_path
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (student_id, first_name, last_name, email, phone,
gender, age, date_of_birth, department, semester, year, str(created_at), photo_path))
conn.commit()
conn.close()
print("Student saved successfully!")
except sqlite3.Error as e:
print("Failed to save student:", e)
import cv2
import os
import numpy as np
import customtkinter as ctk
from tkinter import messagebox, filedialog
from PIL import Image
import time
import sqlite3
import json
from utils import get_db_path, get_image_path, get_db_connection, ensure_directories
74
if not os.path.exists(CHOSEN_DB):
messagebox.showerror("DB Error", "No database file found (students.db).")
raise SystemExit("No DB file found.")
def load_label_map():
"""Load existing label_map.json if it exists; otherwise return empty dict."""
if os.path.exists(LABEL_MAP_PATH):
75
with open(LABEL_MAP_PATH, "r") as f:
return json.load(f) # e.g. { "TYIT24053": 0, "JohnDoe": 1, ... }
return {}
def save_label_map(label_map):
"""Save label_map to disk as JSON."""
with open(LABEL_MAP_PATH, "w") as f:
json.dump(label_map, f, indent=2)
if image_files:
folder_name = os.path.basename(image_directory)
if not folder_in_db(folder_name):
print(f"[DEBUG] Skipping folder '{folder_name}' - not in DB.")
else:
76
if folder_name not in label_map:
label_map[folder_name] = next_label
assigned_label = label_map[folder_name]
student_list.append(folder_name)
for file in image_files:
img_path = os.path.join(image_directory, file)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
if img is not None:
images.append(img)
labels.append(assigned_label)
else:
# Assume folder contains subfolders for each person
for folder_name in os.listdir(image_directory):
person_dir = os.path.join(image_directory, folder_name)
if not os.path.isdir(person_dir):
continue
if not folder_in_db(folder_name):
print(f"[DEBUG] Skipping folder '{folder_name}' - not in DB.")
continue
if folder_name not in label_map:
label_map[folder_name] = next_label
next_label += 1
assigned_label = label_map[folder_name]
student_list.append(folder_name)
for file in os.listdir(person_dir):
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
img_path = os.path.join(person_dir, file)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
if img is not None:
images.append(img)
labels.append(assigned_label)
return images, labels, label_map, student_list
def show_images_during_training(images):
77
"""Briefly display each training image in a window called 'Training Image'."""
for img in images:
cv2.imshow("Training Image", img)
# Wait 50 ms, and allow breaking if a key is pressed
if cv2.waitKey(50) & 0xFF != 255:
break
cv2.destroyWindow("Training Image")
def train_or_update_face_recognizer():
"""
Incrementally train (or update) an LBPH model using images from the chosen dataset
folder.
Loads existing model and label_map if available, trains or updates, and then saves them.
"""
train_button.configure(state="disabled")
status_label.configure(text="Gathering images...")
app.update_idletasks()
# Collect images and labels (this will update label_map if new folders are found)
images, labels, label_map, student_list = load_images_and_labels(IMAGE_DIRECTORY,
label_map)
if not images:
train_button.configure(state="normal")
messagebox.showerror("Error", "No images found for training! Check your dataset
folder.")
return
78
show_images_during_training(images)
# Train or update
status_label.configure(text="Training in progress...")
app.update_idletasks()
start_time = time.time()
try:
if model_exists:
face_recognizer.update(images, np.array(labels))
print("[INFO] Updated existing LBPH model with new images.")
else:
face_recognizer.train(images, np.array(labels))
print("[INFO] Trained new LBPH model from scratch.")
except Exception as e:
messagebox.showerror("Training Error", f"An error occurred during training: {e}")
train_button.configure(state="normal")
return
def show_dataset_info():
79
"""
Quickly load images (without training) to see dataset info.
"""
label_map = load_label_map()
images, labels, label_map, student_list = load_images_and_labels(IMAGE_DIRECTORY,
label_map)
if not images:
messagebox.showinfo("Dataset Info", "No images found in the current dataset folder.")
else:
info_text = (
f"Total Images: {len(images)}\n"
f"Unique Student Folders: {len(student_list)}\n"
f"Folder Names (IDs): {', '.join(student_list)}"
)
messagebox.showinfo("Dataset Info", info_text)
def select_dataset():
"""
Allow the user to choose either the main dataset folder (with subfolders)
or a specific person's folder for training.
"""
global IMAGE_DIRECTORY
folder_selected = filedialog.askdirectory(initialdir=IMAGE_DIRECTORY)
if folder_selected:
IMAGE_DIRECTORY = folder_selected
dataset_label.configure(text=f"Dataset: {IMAGE_DIRECTORY}")
def toggle_theme():
current_mode = ctk.get_appearance_mode()
new_mode = "light" if current_mode == "dark" else "dark"
ctk.set_appearance_mode(new_mode)
def open_settings():
80
messagebox.showinfo("Settings", "Settings dialog placeholder.")
def exit_app():
app.quit()
81
model_label = ctk.CTkLabel(main_frame, text="Model Selection:")
model_label.grid(row=3, column=0, sticky="e", padx=5)
model_var = ctk.StringVar(value="LBPH")
model_dropdown = ctk.CTkComboBox(main_frame, values=["LBPH", "EigenFace",
"FisherFace"], variable=model_var)
model_dropdown.grid(row=3, column=1, sticky="w", padx=(0, 10))
progress_frame = ctk.CTkFrame(main_frame)
progress_frame.grid(row=5, column=0, columnspan=3, pady=10, sticky="ew")
progress_var = ctk.DoubleVar(value=0)
progress_bar = ctk.CTkProgressBar(progress_frame, variable=progress_var,
orientation="horizontal")
progress_bar.pack(fill="x", expand=True, padx=10, pady=5)
bottom_frame = ctk.CTkFrame(main_frame)
bottom_frame.grid(row=6, column=0, columnspan=3, sticky="nsew", pady=(10,0))
main_frame.grid_rowconfigure(6, weight=1)
for col in range(3):
main_frame.grid_columnconfigure(col, weight=1)
82
# ---------------------- Main Loop ----------------------
if __name__ == "__main__":
app.mainloop()
def save_attendance_to_db():
try:
finalize_attendance()
conn = sqlite3.connect(STUDENTS_DB)
cursor = conn.cursor()
today = datetime.date.today().strftime("%Y-%m-%d")
cursor.execute("DELETE FROM attendance WHERE date(timestamp) = ?", (today,))
for record in attendance.values():
cursor.execute(
"""
INSERT INTO attendance (student_id, name, department, timestamp, status)
VALUES (?, ?, ?, ?, ?)
""",
(
record["student_id"],
record["name"],
record["department"],
record["timestamp"],
record["status"],
),
)
conn.commit()
conn.close()
messagebox.showinfo("Success", "Attendance saved to database!")
except Exception as e:
messagebox.showerror("Error", f"Database save failed: {str(e)}")
def export_attendance_csv():
finalize_attendance()
try:
with open(ATTENDANCE_CSV, "w", newline="") as f:
83
writer = csv.DictWriter(f, fieldnames=["student_id", "name", "department",
"timestamp", "status"])
writer.writeheader()
for record in attendance.values():
writer.writerow(record)
messagebox.showinfo("Success", f"Attendance exported to:\n{ATTENDANCE_CSV}")
except Exception as e:
messagebox.showerror("Error", f"CSV export failed: {str(e)}")
self.cap = None
self.is_running = False
self.after_id = None
self.auto_save = ctk.BooleanVar(value=True)
self.logged_today = set()
self.current_date = datetime.date.today()
initialize_globals()
self.create_widgets()
84
def create_widgets(self):
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
# Sidebar
self.sidebar = ctk.CTkFrame(self, width=300, corner_radius=0)
self.sidebar.grid(row=0, column=0, rowspan=4, sticky="nsew")
ctk.CTkLabel(self.sidebar, text="Attendance System", font=("Arial",
16)).pack(pady=20)
ctk.CTkButton(self.sidebar, text="Start", command=self.start_camera).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Stop", command=self.stop_camera).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Save to DB",
command=save_attendance_to_db).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Export CSV",
command=export_attendance_csv).pack(pady=10)
ctk.CTkButton(self.sidebar, text="Train Model",
command=self.train_model).pack(pady=10)
85
# Video frame
self.video_frame = ctk.CTkFrame(self, corner_radius=10)
self.video_frame.grid(row=0, column=1, padx=20, pady=20, sticky="nsew")
self.video_label = ctk.CTkLabel(self.video_frame, text="")
self.video_label.pack(fill="both", expand=True, padx=10, pady=10)
# Log frame
self.log_frame = ctk.CTkFrame(self, corner_radius=10)
self.log_frame.grid(row=1, column=1, padx=20, pady=20, sticky="nsew")
self.log_text = ctk.CTkTextbox(self.log_frame, wrap="word")
self.log_text.pack(fill="both", expand=True, padx=10, pady=10)
self.log_text.insert("0.0", "Attendance Log:\n")
def open_time_settings(self):
top = ctk.CTkToplevel(self)
top.title("Set Custom Time Slot")
top.geometry("350x300")
86
present_entry.insert(0, "08:35")
present_entry.pack(pady=5)
def save_times():
global PRESENT_CUTOFF_TIME, LATE_CUTOFF_TIME,
CURRENT_TIME_SLOT
try:
new_present = datetime.datetime.strptime(present_entry.get(), "%H:%M").time()
new_late = datetime.datetime.strptime(late_entry.get(), "%H:%M").time()
if new_present > new_late:
messagebox.showerror("Error", "On Time cutoff must be earlier than Late
cutoff.")
return
PRESENT_CUTOFF_TIME = new_present
LATE_CUTOFF_TIME = new_late
CURRENT_TIME_SLOT = "Custom"
self.time_slot_var.set("Custom")
messagebox.showinfo("Success", "Custom time slot set!")
top.destroy()
except Exception as e:
messagebox.showerror("Error", f"Invalid time format. Please use
HH:MM.\n{str(e)}")
def train_model(self):
try:
from train_model import train_or_update_face_recognizer as train_main
train_main()
87
initialize_globals()
messagebox.showinfo("Success", "Model retrained successfully!")
except Exception as e:
messagebox.showerror("Error", f"Training failed: {str(e)}")
def start_camera(self):
if not self.is_running:
self.cap = cv2.VideoCapture(0)
if not self.cap.isOpened():
messagebox.showerror("Error", "Failed to access camera")
return
self.is_running = True
self.update_frame()
def stop_camera(self):
if self.is_running:
self.is_running = False
if self.cap:
self.cap.release()
self.cap = None
if self.auto_save.get():
save_attendance_to_db()
if self.after_id is not None:
try:
self.after_cancel(self.after_id)
except TclError:
pass
self.after_id = None
def update_frame(self):
if not self.winfo_exists():
return
if self.is_running and self.cap:
ret, frame = self.cap.read()
88
if ret:
processed_frame = self.process_frame(frame)
img = Image.fromarray(cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB))
ctk_image = ctk.CTkImage(light_image=img, size=img.size)
self.video_label.configure(image=ctk_image)
self.video_label.image = ctk_image
try:
self.after_id = self.after(30, self.update_frame)
except TclError:
pass
if label != self.last_label:
self.same_label_count = 0
self.last_label = label
else:
self.same_label_count += 1
89
cv2.putText(frame, "Unknown", (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
continue
student_id = label_map_inverse.get(label)
if student_id:
details = get_student_details(student_id)
if details:
sid, fname, lname, dept = details
status, timestamp = determine_attendance_status()
text_color = (0, 255, 0)
if status == "Late Present":
text_color = (0, 255, 255)
elif status == "Absent":
text_color = (0, 0, 255)
y_start = y + h + 20
line_height = 25
cv2.rectangle(frame, (x - 10, y_start - 10),
(x + 300, y_start + (4 * line_height) + 10),
(0, 0, 0), -1)
cv2.putText(frame, f"ID: {sid}", (x, y_start),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1)
cv2.putText(frame, f"Name: {fname} {lname}", (x, y_start + line_height),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)
cv2.putText(frame, f"Dept: {dept}", (x, y_start + 2 * line_height),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)
cv2.putText(frame, f"Status: {status}", (x, y_start + 3 * line_height),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)
90
mark_attendance(sid, status, timestamp)
return frame
91
5.2 TESTING APPROACH
5.2.1 UNIT TESTING
Unit testing was a crucial part of the development process to ensure that each individual
function or module of the Face Recognition System worked as expected before integrating it
with other components. Testing was done manually by simulating real-world input and
observing outputs.
Tested Components
1. Login System
Admin Login Test: Entered correct and incorrect credentials to verify that only valid
users could log in.
Student Login Test: Confirmed session redirection for invalid users and successful
login for registered students.
Session Handling: Checked if session states are correctly set and unauthorized access
redirects to login screen.
Add New User: Tested both addition with valid and missing fields. Verified
insertion into SQLite database and visibility in system.
Duplicate Email Check: Checked whether duplicate email IDs are detected
and blocked.
Delete User: Verified that user accounts are deleted properly and no longer
appear in UI or DB on refresh.
User Display: Verified that profile picture, name, and user type
(admin/student) render accurately in the main dashboard.
Face Capture: Tested webcam live feed and ensured face detection boxes
appear for real human faces.
Face Encoding Storage: Verified that face encodings are stored with correct
user mapping.
92
Recognition Logic: Tested with known and unknown faces. Verified system
correctly recognizes or denies access.
Multiple Face Handling: Ensured the app either prompts or handles multiple
faces smartly.
Entered blank fields, invalid data types, and SQL-sensitive inputs to confirm
proper error handling and prevention of injection.
Checked application responses to camera failures, DB disconnection, or
corrupted face image files.
6. UI Feedback
Verified if success/error alerts and modal messages appear appropriately after actions.
Tested responsiveness of all GUI elements on various screen resolutions.
Issue Book: Tested borrowing flow to ensure dates are stored correctly.
2. Fine Calculation
Verified that the system correctly computes the fine based on the number
of overdue days.
93
3. Validation and Error Handling
4. UI Feedback
94
5.2.2 INTEGRATION TESTING
Once unit testing is completed, components are combined to verify full workflows like user
management, book issue-return cycle, and admin controls.
Testing Methodology:
Combine multiple modules (login → search → issue book → return book) to ensure
seamless operation.
Test interactions between the admin panel and the user dashboard.
Manual testing conducted through browser sessions simulating real user behavior.
Deployed the app on a local Apache/MySQL setup with seeded edge-case data.
Simulated full user workflow: register → login → search → issue → return.
Exercised issue/return endpoints in Postman to verify JSON responses and HTTP
codes.
Tested concurrent issuance of the last copy and deletion of users with active
loans.
Reran integration tests after each bug fix to prevent regression
95
Sample Integration Test Plan:
96
CHAPTER 6
RESULTS AND DISCUSSION
97
Login/Signup page
Admin Home Page
Main Window:-
98
Face Recognition interface:
99
Model Training Interface:
100
Student Registration window:
101
Record View Window: -
102
CHAPTER 7
CONCLUSIONS
103
7.1 CONCLUSION
In wrapping up the project, our Face Recognition Attendance System stands out as a robust
blend of computer vision, database management, and user authentication. We built the system
using Python, OpenCV for face detection and recognition, and CustomTkinter for a sleek GUI
interface. The project integrates attendance marking by automatically detecting faces via a
trained LBPH model, fetching student details from an SQLite database, and recording
attendance status based on predefined timing thresholds. While the core functionalities—such
as real-time recognition, data export (to CSV and database), and model training—are
operational, the project also paves the way for more streamlined user management and robust
security measures as demonstrated in the integrated authentication module.
7.2 LIMITATIONS
The Face Recognition System brings a modern, secure, and efficient approach to identity
verification and user management, replacing traditional authentication methods such as
manual logins and ID cards. This system leverages computer vision and machine learning to
detect and recognize human faces in real-time using a webcam and compares them with pre-
registered data for access control.
1. Enhanced Security
The system ensures only authorized individuals gain access, reducing the risk of
impersonation or password theft. Face recognition provides a biometric layer of security that’s
difficult to forge.
104
2. User Convenience
Eliminates the need for remembering passwords or carrying ID cards. Users can authenticate
themselves simply by facing the camera.
Automates the authentication process, reducing manual effort in attendance systems, log
maintenance, or admin approvals—especially useful in institutions or offices.
4. Real-Time Processing
The system processes facial data in real-time, making it suitable for time-sensitive scenarios
like check-ins, surveillance, or access control gates.
With minor modifications, the system can be adapted for applications such as:
Library systems
The use of SQLite allows centralized storage of user data, face encodings, and log entries for
monitoring or analytics.
6. Educational Value
From a development standpoint, this system provides hands-on experience with technologies
such as OpenCV, SQLite, Tkinter GUI, and Python scripting—making it a valuable learning
project.
105
7.3 FUTURE SCOPE OF THE PROJECT
Looking ahead, we can upgrade to deep learning, add mobile support, move to cloud for
scalability, and boost security and UX.
Enhanced Accuracy:
Bringing the attendance system to mobile devices could make on-the-go attendance
tracking and remote learning management super accessible.
Cloud Integration and Data Analytics:
Migrating the backend to cloud-based services would not only enhance scalability but
also allow real-time analytics and machine learning integration for attendance trends
and predictive insights.
Security Enhancements:
The system could be adapted for broader applications like event management,
workplace attendance, and even integration with Learning Management Systems
(LMS) for holistic academic tracking.
106
REFERENCES
107
Content
108