0% found this document useful (0 votes)
36 views34 pages

Project File Ai Based Attendence

Uploaded by

dimplesahuu06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views34 pages

Project File Ai Based Attendence

Uploaded by

dimplesahuu06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

GURU GHASIDAS VISHWAVIDYALAYA,

BILASPUR (C.G.)

Department of Computer Science &


Information Technology
Session: 2021-2024
Project Report On
FACIAL RECOGNITION USING PYTHON
(Minor Project)

GUIDED BY: SUBMITTED BY:


Dr. SHRABANTI MANDAL DHANANJAY SAHU
B.Sc. C.S 6th SEM
ROLL NO - 21070115
PROJECT ON
FACIAL RECOGNITION USING
PYTHON
DECLARATION
In this undersigned project I solemnly declare that the report of the
project work entitled “FACIAL RECOGNITION USING
PYTHON” is the actual work carried out during the course of my
study under the Dr. SHRABANTI MANDAL,
supervision
Department of Computer Science and Information
Technology
I assert that the statements made and conclusions drawn are an
outcome of the project work.
I further declare that to the best of my knowledge and belief that the
report does not contain any part of any work which has been
submitted for the award of any other degree/diploma/certificate in
this University/deemed University of India or any other country. All
help received used for the preparation of the project have been duly
acknowledged.

(Signature of the Candidate)


Name: DHANANJAY SAHU
Roll No.: 21070115
Enrolment No.: GGV/21/05115
CERTIFICATE
This is to clarify that this Project entitled “FACIAL
RECOGNITION USING PYTHON” is submitted by
DHANANJAY SAHU in fulfilment of the requirements
for minor project. This was an authentic work done by
her under my supervision and guidance.

Signature of Project Guide Signature of HOD

ACKNOWLEDGEMENT
I owe a great thanks to many people who helped me during writing this paper.

First of all, I want to thanks Dr A.K. Saxena ,HOD of Department of Computer


Science and Information Technology, GGU, for allowing me to carry out this
project as a part of my course B.Sc. Computer Science at his department.
I am extremely indebted to Dr. SHRABANTI
MANDAL, Assistant Professor of GGV, Bilaspur without whose kind of
guidance and support, I would not have completed my semester project
successfully. He was instrumental in assigning me this work. He provided all
required resources and ensured by all means that I come up with valid results.

I would like to acknowledge that this project was


completed entirely by me and not by someone else.

DHANANJAY SAHU
Department of Computer Science & Information Technology
Guru Ghasidas Vishwavidyalaya,
Bilaspur (C.G.), 495009

ABSTRACT

The FACIAL RECOGNITION USING PYTHON (FRAS)


utilizes advanced facial recognition algorithms to automate
attendance tracking. By comparing real-time facial images
with an enrolled database, it eliminates the need for physical
identifiers, reduces fraud, and enhances security. FRAS
streamlines administrative tasks, providing real-time
monitoring and generating comprehensive attendance reports.
Challenges include ensuring accuracy across diverse
conditions and addressing privacy concerns. Despite these
challenges, FRAS offers a cutting-edge solution for efficient
attendance management in educational and organizational
settings.

Table of Contents
1. Introduction
2. Overview
3. Key Components
- 3.1 Face Detection
- 3.2 Feature Extraction
- 3.3 Face Matching
4. Functionalities
- 4.1 Automatic Attendance Tracking
- 4.2 Fraud Prevention
- 4.3 User Interface
- 4.4 Reporting and Analytics
5. Implementation Details
- 5.1 Hardware Requirements
- 5.2 Software Development
- 5.3 Integration
- 5.4 Testing and Validation
6. Applications
- 6.1 Educational Institutions
- 6.2 Workplaces
- 6.3 Security and Surveillance
7. Code and Working
-7.1 Code
-7.2 Directory Structure
-7.3 Working
8. Conclusion
9. Future Enhancements
10. References
Chapter – 1

INTRODUCTION
INTRODUCTION
In today's fast-paced world, the need for efficient and
accurate attendance tracking systems is paramount,
especially in educational institutions, workplaces, and
various organizational settings. Traditional methods of
attendance tracking, such as manual sign-in sheets or
swipe cards, are not only time-consuming but also
susceptible to errors and fraudulent practices like buddy
punching.

The FACIAL RECOGNITION USING PYTHON (FRAS)


emerges as a cutting-edge solution to address these
challenges. FRAS leverages advanced facial recognition
algorithms to automate the attendance tracking
process, offering a seamless and reliable alternative to
conventional methods.

Facial recognition technology has witnessed significant


advancements in recent years, making it increasingly
reliable and accurate. By analysing unique facial
features, such as landmarks and textures, FRAS can
identify individuals with a high degree of precision,
eliminating the need for physical identifiers and
reducing the risk of fraud.

This documentation aims to provide a comprehensive


guide for the development and implementation of FRAS
as a final year project. It will delve into the key
components, functionalities, implementation details,
potential applications, and future enhancements of
FRAS, offering insights into its significance and practical
implications in various real-world scenarios.

By exploring the capabilities and benefits of FRAS, this


documentation aims to equip readers with the
knowledge and understanding necessary to embark on
their final year project with confidence, paving the way
for the creation of an innovative and impactful
attendance tracking solution.

Chapter – 2

OVERVIEW
OVERVIEW
The project aims to develop a facial recognition-based
attendance management system using computer vision
techniques and web technologies. Traditional attendance
tracking methods often suffer from inefficiencies and
inaccuracies, leading to time-consuming processes and
potential errors. This system offers a modern solution to
streamline the attendance management process in various
settings such as educational institutions, workplaces, and
security systems.

Key Objectives:
1. Efficiency: Automate the attendance tracking
process to save time and resources for both
administrators and attendees.
2. Accuracy: Utilize facial recognition technology to
ensure precise attendance records without manual
intervention.
3. Security: Enhance security measures by verifying
the identity of individuals through biometric
authentication.
4. User-Friendly Interface: Provide an intuitive and
easy-to-use interface for administrators and end-users.

Key Components:
The system comprises several key components working
together seamlessly to achieve its objectives:

- Face Detection: Utilizes computer vision algorithms


to detect faces in images or video streams.
- Feature Extraction: Extracts unique facial features
from detected faces for identification purposes.
- Face Matching: Compares extracted features with
pre-registered templates to recognize individuals.
- Database Management: Manages a database of
registered users and their associated facial templates
for recognition.
The integration of these components enables the system to
accurately identify individuals and track their attendance
automatically.

Chapter – 4

FUNCTIONALITIES
FUNCTIONALITIES
4.1 Automatic Attendance Tracking
-Real-time Recognition: Utilizes facial recognition technology
to automatically detect and identify individuals present in a
given environment.
- Attendance Logging: Records attendance data in a
structured format, including timestamps and individual
identification.
- Efficient Tracking: Eliminates the need for manual
attendance taking, reducing administrative burden and
potential errors.
- Instant Feedback: Provides immediate feedback to users
regarding their attendance status upon recognition.

4.2 Fraud Prevention


- Biometric Authentication: Ensures the integrity of
attendance records by verifying the identity of individuals
through biometric characteristics.
- Fraud Detection: Detects and prevents fraudulent activities
such as impersonation or proxy attendance.
- Security Measures: Enhances security measures by
requiring physical presence for attendance logging, minimizing
the risk of unauthorized access.

4.3 User Interface


-Intuitive Interface: Offers a user-friendly interface for
administrators to manage attendance data and system
settings.
-Registration Module: Allows users to register their faces for
attendance tracking, with straightforward instructions and
feedback.
-Feedback Mechanism: Provides feedback to users during the
registration process to ensure accurate face capture.
-Accessibility: Supports access from various devices and
platforms, including web browsers and mobile devices.

4.4 Reporting and Analytics


-Comprehensive Reports: Generates detailed reports on
attendance statistics, including attendance rates, late arrivals,
and absences.
-Analytics Tools: Provides analytical tools to visualize
attendance trends and patterns over time.
-Customization Options: Allows administrators to customize
reports and analytics based on specific requirements or
parameters.
-Data Export: Facilitates data export functionality for further
analysis or integration with external systems.

Chapter – 5

IMPLEMENTATION DETAILS
IMPLEMENTATION DETAILS
5.1 Hardware Requirements
- Camera: Requires a camera or webcam capable of capturing
high-quality images for facial recognition.
- Processing Unit: Needs a computing device (e.g., laptop,
desktop, or server) with sufficient processing power to perform
real-time facial recognition tasks.
- Storage: Sufficient storage space to store captured images,
facial templates, and attendance data.

5.2 Software Development


- Programming Languages: Utilizes Python for backend
development and HTML/CSS/JavaScript for frontend web
development.
- Libraries and Frameworks: Relies on OpenCV for face
detection and recognition tasks, Flask for web application
development, and scikit-learn for machine learning-based
classification..
- User Interface Design: Designs an intuitive user interface
using HTML, CSS, and JavaScript to facilitate user interactions
and system management.

5.3 Integration
- Face Detection and Recognition: Integrates face detection
and recognition algorithms into the system using OpenCV
libraries and custom machine learning models.
- Web Application Development: Develops a web-based
interface using Flask framework to interact with the attendance
management system.
- Database Integration: Integrates database management
systems to store and retrieve user information, attendance
records, and system configurations.
- Testing and Debugging: Conducts thorough testing and
debugging to ensure the reliability and accuracy of the
system's functionality.

5.4 Testing and Validation


- Unit Testing: Performs unit testing of individual components
(e.g., face detection, recognition, database management) to
validate their functionality.
- Integration Testing: Conducts integration testing to verify
the seamless integration of different system components.
-User Acceptance Testing: Involves end-users
(administrators, attendees) in user acceptance testing to
evaluate the usability and effectiveness of the system.
- Validation: Validates the system's performance against
predefined criteria, including accuracy, speed, and user
satisfaction.

Chapter – 6

APPLICATIONS
APPLICATIONS
6.1 Educational Institutions
- Automated Attendance Tracking: Streamlines
attendance management processes for students and
faculty members, reducing administrative workload
and potential errors.
- Efficient Monitoring: Enables real-time monitoring
of attendance records, allowing educators to identify
patterns and trends in student attendance.
- Enhanced Security: Improves campus security by
accurately tracking individuals' presence and
identifying unauthorized access attempts.

6.2 Workplaces
- Time and Attendance Management: Facilitates
automated time and attendance tracking for
employees, optimizing workforce management and
payroll processes.
- Remote Work Support: Supports remote or flexible
work arrangements by providing a secure and reliable
attendance tracking solution accessible from
anywhere.
- Compliance Monitoring: Helps organizations
ensure compliance with labour regulations and policies
by maintaining accurate attendance records.

6.3 Security and Surveillance


- Access Control: Integrates with access control
systems to enhance security measures by verifying
individuals' identities before granting access to
restricted areas.
- Visitor Management: Improves visitor management
processes by accurately identifying and logging
visitors' attendance, enhancing premises security and
visitor experience.
- Forensic Investigations: Assists law enforcement
agencies in forensic investigations by providing facial
recognition capabilities for identifying suspects and
analysing surveillance footage.

Chapter – 7

CODE AND WORKING


7.1CODE
"""
This script is used to manage attendance of students in a classroom.

It uses a webcam to capture images of the students' faces, which are


then used to identify them.

The script also allows you to add new students to the system.

Usage:
1. Run the script and wait for it to open a webcam window.
2. Look into the webcam and ensure that the face of the student you want
to add is within the frame.
3. Press the "Start" button to start capturing images.
4. Once the required number of images have been captured, the script
will attempt to identify the student.
5. If the student is successfully identified, their name will be added
to the attendance list.
6. You can repeat steps 2-5 for each student you want to add.
7. Once you're done, press the "Stop" button to close the webcam and
view the attendance list.

Note:
1. The script requires a trained model to identify faces. If no model is
found, the script will prompt you to add a face.
2. The model can be trained using the "Train Model" button.
3. The script saves the attendance data in a CSV file, which can be
viewed and edited manually.
"""

import cv2
import os
from flask import Flask, request, render_template
from datetime import date
from datetime import datetime
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import joblib

app = Flask(__name__)

nimgs = 10

imgBackground=cv2.imread("background.png")

datetoday = date.today().strftime("%m_%d_%y")
datetoday2 = date.today().strftime("%d-%B-%Y")

face_detector =
cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

if not os.path.isdir('Attendance'):
os.makedirs('Attendance')
if not os.path.isdir('static'):
os.makedirs('static')
if not os.path.isdir('static/faces'):
os.makedirs('static/faces')
if f'Attendance-{datetoday}.csv' not in os.listdir('Attendance'):
with open(f'Attendance/Attendance-{datetoday}.csv', 'w') as f:
f.write('Name,Roll,Time')

def totalreg():
return len(os.listdir('static/faces'))

def extract_faces(img):
try:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_points = face_detector.detectMultiScale(gray, 1.2, 5,
minSize=(20, 20))
return face_points
except:
return []

def identify_face(facearray):
model = joblib.load('static/face_recognition_model.pkl')
return model.predict(facearray)
def train_model():
faces = []
labels = []
userlist = os.listdir('static/faces')
for user in userlist:
for imgname in os.listdir(f'static/faces/{user}'):
img = cv2.imread(f'static/faces/{user}/{imgname}')
resized_face = cv2.resize(img, (50, 50))
faces.append(resized_face.ravel())
labels.append(user)
faces = np.array(faces)
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(faces, labels)
joblib.dump(knn, 'static/face_recognition_model.pkl')

def extract_attendance():
df = pd.read_csv(f'Attendance/Attendance-{datetoday}.csv')
names = df['Name']
rolls = df['Roll']
times = df['Time']
l = len(df)
return names, rolls, times, l

def add_attendance(name):
username = name.split('_')[0]
userid = name.split('_')[1]
current_time = datetime.now().strftime("%H:%M:%S")

df = pd.read_csv(f'Attendance/Attendance-{datetoday}.csv')
if int(userid) not in list(df['Roll']):
with open(f'Attendance/Attendance-{datetoday}.csv', 'a') as f:
f.write(f'\n{username},{userid},{current_time}')

def getallusers():
userlist = os.listdir('static/faces')
names = []
rolls = []
l = len(userlist)

for i in userlist:
name, roll = i.split('_')
names.append(name)
rolls.append(roll)

return userlist, names, rolls, l

@app.route('/')
def home():
names, rolls, times, l = extract_attendance()
return render_template('home.html', names=names, rolls=rolls,
times=times, l=l, totalreg=totalreg(), datetoday2=datetoday2)

@app.route('/start', methods=['GET'])
def start():
names, rolls, times, l = extract_attendance()

if 'face_recognition_model.pkl' not in os.listdir('static'):


return render_template('home.html', names=names, rolls=rolls,
times=times, l=l, totalreg=totalreg(), datetoday2=datetoday2,
mess='There is no trained model in the static folder. Please add a new
face to continue.')

ret = True
cap = cv2.VideoCapture(0)
while ret:
ret, frame = cap.read()
if len(extract_faces(frame)) > 0:
(x, y, w, h) = extract_faces(frame)[0]
cv2.rectangle(frame, (x, y), (x+w, y+h), (86, 32, 251), 1)
cv2.rectangle(frame, (x, y), (x+w, y-40), (86, 32, 251), -
1)
face = cv2.resize(frame[y:y+h, x:x+w], (50, 50))
identified_person = identify_face(face.reshape(1, -1))[0]
add_attendance(identified_person)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0,0,255), 1)
cv2.rectangle(frame,(x,y),(x+w,y+h),(50,50,255),2)
cv2.rectangle(frame,(x,y-40),(x+w,y),(50,50,255),-1)
cv2.putText(frame, f'{identified_person}', (x,y-15),
cv2.FONT_HERSHEY_COMPLEX, 1, (255,255,255), 1)
cv2.rectangle(frame, (x,y), (x+w, y+h), (50,50,255), 1)
imgBackground[162:162 + 480, 55:55 + 640] = frame
cv2.imshow('Attendance', imgBackground)
if cv2.waitKey(1) == 27:
break
cap.release()
cv2.destroyAllWindows()
names, rolls, times, l = extract_attendance()
return render_template('home.html', names=names, rolls=rolls,
times=times, l=l, totalreg=totalreg(), datetoday2=datetoday2)

@app.route('/add', methods=['GET', 'POST'])


def add():
newusername = request.form['newusername']
newuserid = request.form['newuserid']
userimagefolder = 'static/faces/'+newusername+'_'+str(newuserid)
if not os.path.isdir(userimagefolder):
os.makedirs(userimagefolder)
i, j = 0, 0
cap = cv2.VideoCapture(0)
while 1:
_, frame = cap.read()
faces = extract_faces(frame)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 20), 2)
cv2.putText(frame, f'Images Captured: {i}/{nimgs}', (30,
30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 20), 2,
cv2.LINE_AA)
if j % 5 == 0:
name = newusername+'_'+str(i)+'.jpg'
cv2.imwrite(userimagefolder+'/'+name, frame[y:y+h,
x:x+w])
i += 1
j += 1
if j == nimgs*5:
break
cv2.imshow('Adding new User', frame)
if cv2.waitKey(1) == 27:
break
cap.release()
cv2.destroyAllWindows()
print('Training Model')
train_model()
names, rolls, times, l = extract_attendance()
return render_template('home.html', names=names, rolls=rolls,
times=times, l=l, totalreg=totalreg(), datetoday2=datetoday2)

if __name__ == '__main__':
app.run(debug=True)

Directory Structure
7.2WORKING
FOLLOW THE URL

THIS PAGE IS MAIN PAGE


ENTER STUDENT OR EMPLOYE
NAME AND UNIQUE ID THEN ADD
USER

IT WILL OPEN CAMERA AND


CAPTURE 10 IMAGES OF FACE
THEN PRESS TAKE ATTENDANCE

PRESS “O” THEN YOUR


ATTENDANCE WILL SAVE IN An
EXCEL FILE IN ROOT FOLDER
NAMED ATTANDENCE
ATTENDANCE HAS BEEN TAKEN
AND SAVED
Chapter – 8

Conclusion
Conclusion
In conclusion, the developed facial recognition-based
attendance management system offers an efficient and
accurate solution for automating attendance tracking processes
in various environments. By leveraging advanced computer
vision techniques and web technologies, the system addresses
the shortcomings of traditional attendance management
methods, providing benefits such as:

- Time Savings: Eliminates the need for manual


attendance taking, saving valuable time for both
administrators and attendees.
- Accuracy: Ensures precise attendance records through
biometric authentication, reducing errors and
discrepancies.
- Security: Enhances security measures by verifying
individuals' identities and detecting fraudulent activities.
- User-Friendly Interface: Offers an intuitive and
accessible user interface for seamless interaction and
management of attendance data.

With its versatile applications across educational institutions,


workplaces, and security systems, the system demonstrates its
adaptability and effectiveness in meeting diverse needs and
requirements.

Moving forward, continuous refinement and enhancement of the


system's features and capabilities will further improve its utility
and performance, ensuring its relevance and reliability in the
evolving landscape of attendance management and security
technologies.
Chapter – 9

FUTURE
ENHANCEMENTS
FUTURE ENHANCEMENTS
9.1 Enhanced Recognition Algorithms
- Deep Learning Models: Explore the use of deep learning models such
as Convolutional Neural Networks (CNNs) for more robust and accurate
face recognition.
- Feature Extraction Techniques: Implement advanced feature
extraction techniques to capture finer details and improve recognition
performance.

9.2 Real-time Monitoring and Notifications


- Real-time Alerts: Integrate real-time notification systems to alert
administrators or supervisors of attendance anomalies or suspicious
activities.
- Live Monitoring: Enable live monitoring capabilities to track attendance
status and access events as they occur.

9.3 Mobile Application


- Mobile Accessibility: Develop a mobile application to facilitate
attendance tracking and management on smartphones and tablets.
- Remote Access: Allow users to access attendance data and perform
administrative tasks remotely via the mobile app.

9.4 Integration with Student Information Systems (SIS) and


Human Resource Management Systems (HRMS)
- SIS Integration: Integrate with existing Student Information Systems to
synchronize attendance data with student records and academic
performance metrics.
- HRMS Integration: Integrate with Human Resource Management
Systems to automate attendance tracking and payroll processing for
employees.
9.5 Facial Recognition in Challenging Conditions
- Low-Light Performance: Enhance face recognition algorithms to
perform effectively in low-light conditions or under varying lighting
environments.
- Pose and Expression Variability: Address challenges related to pose
variations and facial expressions to improve recognition accuracy.
9.6 Privacy and Data Security Measures
- Privacy Controls: Implement privacy controls and consent mechanisms
to ensure compliance with data protection regulations (e.g., GDPR).
- Data Encryption: Employ robust encryption techniques to secure
sensitive attendance data and protect against unauthorized access.

9.7 User Experience Enhancements


- Customizable Interface: Provide customization options for the user
interface to accommodate different user preferences and requirements.
- Multi-language Support: Add support for multiple languages to cater to
diverse user demographics and global audiences.

Chapter – 10

REFERENCES
REFERENCES
1. Lienhart, R., & Maydt, J. (2002). An extended set of Haar-like
features for rapid object detection. In Proceedings of the
International Conference on Image Processing (Vol. 1, pp.
900-903). IEEE.
2. Grinberg, M. (2018). Flask Web Development: Developing
Web Applications with Python. O'Reilly Media.
3. Pedregosa, F., et al. (2011). Scikit-learn: Machine learning in
Python. Journal of Machine Learning Research, 12, 2825-
2830.
4. OpenCV: Open-Source Computer Vision Library. (n.d.).
Retrieved from https://opencv.org/
5. Flask Documentation. (n.d.). Retrieved from
https://flask.palletsprojects.com/en/2.0.x/
6. Pandas Documentation. (n.d.). Retrieved from
https://pandas.pydata.org/docs/
7. Python Documentation. (n.d.). Retrieved from
https://docs.python.org/3/
8. Haarcascades for Face Detection. (n.d.). Retrieved from
https://github.com/opencv/opencv/tree/master/data/haarcascad
es

You might also like