0% found this document useful (0 votes)
10 views32 pages

Attendance System with OpenCV

Uploaded by

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

Attendance System with OpenCV

Uploaded by

spoorthi16desai
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

“Attendance Marking System using OpenCV”

PROJECT REPORT

Submitted to

Visvesvaraya Technological University


Belagavi, Karnataka, 590 018

Submitted by
UMESH DODAMANI 2KE21EC115

VAIBHAV KATAGAR 2KE21EC116

VARUN DHOTRAGAVI 2KE21EC120

YASH HABIB 2KE21EC125

Under the Guidance of

Dr. Yerriswamy T

Department of Electronics and Communication Engineering


(NBA Accredited)

K. L. E. SOCIETY’S
K. L. E. INSTITUTE OF TECHNOLOGY,
Hubballi-27

2023-24
K. L. E. SOCIETY’S
K. L. E. INSTITUTE OF TECHNOLOGY,
Hubballi-27

Department of Electronics and communication


engineering

CERTIFICATE

This is to Certify that the project work entitled “Attendance Marking System using
OpenCV” is a bonafide work carried out by UMESH DODAMANI (2KE21EC115),
VAIBHAV KATAGAR (2KE21EC116), VARUN DHOTRAGAVI (2KE21EC120) and
YASH HABIB (2KE21EC125) in partial fulfilment for the award of degree of Bachelor of
Engineering in VI Semester B division, Electronics and Communication Engineering of
Visvesvaraya Technological University, Belagavi, during the year 2023-24. It is certified
that all corrections/suggestions indicated for internal assessment have been incorporated in
the report deposited in the department library. The project report has been approved as it
satisfies the academic requirements in respect of project work prescribed for the said degree.

Dr. Yerriswamy T Dr. Gopal A. Bidkar Dr. Manu T. M.


Guide HOD Principle

I
DECLARATION

We, UMESH DODAMANI (2KE21EC115), VAIBHAV KATAGAR (2KE21EC116),


VARUN DHOTRAGAVI (2KE21EC120), YASH HABIB (2KE21EC125) students of 6th
Semester B.E., K.L.E. Institute of Technology, Hubballi, hereby declare that the mini project
work has been carried out by us and submitted in partial fulfillment of the requirements for the
VI Semester degree of Bachelor of Engineering in Electronics and Communication
Engineering of Visvesvaraya Technological University, Belagavi during academic year 2023-
2024.

Date: 09-08-2024
Place: Hubballi

UMESH DODAMANI (2KE21EC115)


VAIBHAV KATAGAR (2KE21EC116)
VARUN DHOTRAGAVI (2KE21EC120)
YASH HABIB (2KE21EC125)

II
ACKNOWLEDGEMENT

A mini project report on “Attendance Marking System using OpenCV” is the outcome of
guidance, moral support and devotion bestowed on me throughout our work. For this we
acknowledge and express our profound sense of gratitude and thanks to our Mentor, Mr.
Chetan S. I acknowledge that we learnt the importance of technical research and good
presentation skills.

we are thankful to our Guide, Dr. Yerriswamy T, Dean, KLEIT for his encouragement,
effective guidance and valuable suggestions right from the beginning of the project till its
completion, without which this project work would not have been accomplished. We are
greatly indebted to him.

We are also thankful to H.O.D, Dr. Gopal Bidkar, Electronics and Communication
Engineering Department, who has given valuable suggestions during the work and his moral
support and encouragement.

Our sincere gratitude to our beloved principal, Dr. Manu T.M, for providing an ideal
atmosphere to pursue our objectives under his able administration.

We also thank our parents and all our friends wholeheartedly who have rendered their help,
motivation and support to accomplish this project.

UMESH DODAMANI (2KE21EC115)


VAIBHAV KATAGAR (2KE21EC116)
VARUN DHOTRAGAVI (2KE21EC120)
YASH HABIB (2KE21EC125)

III
ABSTRACT

Attendance marking is a critical task in various institutions, often requiring substantial manual
effort and time. This project presents an automated attendance marking system leveraging
computer vision techniques with OpenCV. The system aims to streamline and enhance the
accuracy of attendance records by utilizing facial recognition technology. The core of the
system involves capturing real-time video footage from a camera, detecting faces in the frame,
and recognizing individuals based on pre-registered facial data. OpenCV's robust image
processing and machine learning libraries are employed to perform face detection and
recognition. The system is designed to operate efficiently in various lighting conditions and
handle multiple individuals simultaneously. By automating the attendance process, the system
reduces the potential for human error, saves time, and provides a reliable and scalable solution
for attendance management. The implementation of this system demonstrates the practical
application of computer vision in real-world scenarios, offering a significant improvement over
traditional methods. This project concludes with insights into usability, future enhancements,
and practical applications in Face recognition and its analysis.

IV
Contents
Certificate Ⅰ
Declaration Ⅱ
Acknowledgement Ⅲ
Abstract Ⅳ
Contents Ⅴ-Ⅵ
List of Figures Ⅵ

Page No.
CHAPTER 1 : INTRODUCTION 1 - 11
1.1 Python programming 1
1.1.1 Python Basics 1-5
1.1.2 OpenCV 5-6
1.1.3 Image Processing in OpenCV 6-7
1.1.4 Video processing in OpenCV 7-8
1.1.5 ML and DL in OpenCV 8-9
1.1.6 CV Algorithm in OpenCV 9
1.1.7 Cross-Platform in OpenCV 9 - 10
1.1.8 Community and Documentation 10 - 11

CHAPTER 2 : METHODOLOGY 12 - 21
2.1 Attendance Marking System in Open CV 12
2.2 Program for AMS in OpenCV 12 - 15
2.3 Code Explanation 15 - 20
2.4 Discussion on AMS, Face Recognition 20 - 21

CHAPTER 3 : RESULT 22 - 23
CHAPTER 4 : CONCLUSION AND 24
FUTURE SCOPE
REFRENCES & BIBLIOGRAPHY 25


LIST OF FIGURES

Figure No. Figure Name Page No.

3.1 Program for AMS Using OpenCV. 22


3.2 Face Recognition 23
3.3 Output with Name and Time 23
3.4 Program successfully executed in Terminal. 23


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

CHAPTER 1 INTRODUCTION

1.1 Python programming


Python is a high-level, interpreted, and versatile programming language known for its
readability and simplicity. It supports multiple programming paradigms, including
procedural, object-oriented, and functional programming styles.

Python is widely used in various domains such as web development, data analysis,
artificial intelligence, scientific computing, system automation, and more. Its syntax
emphasizes code readability and its straightforward nature makes it accessible for
beginners while still powerful enough for experienced developers.

Key features of Python programming include:

Readability: Python code is easy to read and understand, enhancing maintainability and
reducing the cost of program maintenance.

Interpreted: Python code does not need to be compiled into machine language instructions
before being run. Instead, Python interprets code line by line at runtime, which can simplify
development and testing.

Dynamic typing: Python automatically determines the type of variables at runtime,


reducing the complexity of type declarations.

Extensive standard library: Python comes with a large collection of modules and
libraries, providing ready-to-use tools and functionalities for various tasks.

1.1.1 Python Basics


Variables and Datatypes: Python variables are dynamically typed, meaning you don't
need to declare a type explicitly.
Example: # Integer
x=5

Department Of Electronics And Communication Engineering KLEIT, Hubballi 1


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

# Float
y = 3.14

# String
name = "Alice"

# Boolean
is_python_fun = True

Basic Input and Output: Python provides straightforward ways to take input from
users and display output.
Example: # Input from user
name = input("Enter your name: ")

# Output
print("Hello, " + name + "!")

Control Flow Statements: Python uses indentation to define blocks of code (no
braces).
Example: # if-elif-else
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")

# for loop
for i in range(5):

Department Of Electronics And Communication Engineering KLEIT, Hubballi 2


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

print(i)
# while loop
i=0
while i < 5:
print(i)
i += 1

Functions: Functions in Python are defined using the ‘def’ keyword.


Example: def greet(name):

print("Hello, " + name + "!")


greet("Alice")

Lists, Tuples and Dictionaries: Lists and dictionaries are fundamental data structures
in Python.
Example: # List
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple

# Tuple (immutable list)


coordinates = (3, 4)
print(coordinates[0]) # Output: 3

# Dictionary (key-value pairs)


person = {"name": "Alice", "age": 25}
print(person["name"]) # Output: Alice

Exception Handling: Getting an error, or exception, in your Python program means


the entire program will crash. Python uses ‘try-except’ blocks for error handling.
Example: try:
result = 10 / 0
except ZeroDivisionError:

Department Of Electronics And Communication Engineering KLEIT, Hubballi 3


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

print("Error: Division by zero!")

Traversing: Traversing in Python typically refers to iterating through elements in a


data structure, such as a list, tuple, dictionary, or set.
Example: Using list
my_list = [1, 2, 3, 4, 5]

# Using a for loop


for item in my_list:
print(item)

# Using a while loop


i=0
while i < len(my_list):
print(my_list[i])
i += 1
String methods:
upper():The ‘upper()’ method converts all the characters in a string to uppercase.
Example: name="Hello, World!"
newname=[Link]()
print("Original: {name}")
print("Uppercase: {newname}") # Output: "HELLO, WORLD!"

lower():The ‘lower()’ method converts all the characters in a string to lowercase.


Example: name="Hello, World!"
newname2=[Link]()
print("Original: {name}")
print("Lowercase: {newname2}")# Output: "hello, world!"

Department Of Electronics And Communication Engineering KLEIT, Hubballi 4


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

isupper():The ‘isupper()’ method checks if all the characters in the string are
uppercase. It returns ‘True’ if all characters are uppercase and there is at least one
character, otherwise ‘False’.
Example: name="Hello, World!"
newname3=[Link]()
newname4=[Link]()
print("Is the original string in uppercase? {newname3}")
print("Is the transformed string in uppercase? {newname4}")
#Output: Is the original string in uppercase? False
Is the transformed string in uppercase? True

1.1.2 OpenCV
OpenCV, or Open Source Computer Vision Library, is a powerful open-source
computer vision and machine learning software library primarily designed for real-
time applications. It was originally developed by Intel in 1999 and has since become
one of the most widely used libraries for computer vision tasks due to its efficiency,
extensive functionality, and large community support.

In Python, OpenCV is implemented through the cv2 module, which provides a plethora
of functions and algorithms for tasks such as image and video processing, object
detection and recognition, facial recognition, motion tracking, and more. Its versatility
makes it suitable for a wide range of applications in fields like robotics, augmented
reality, medical image analysis, and surveillance.

Key features of OpenCV in Python include:

Image Processing: It provides functions for loading, manipulating, and saving images
in various formats. It supports basic operations like resizing, cropping, and filtering. A
wide array of techniques and functionalities designed to manipulate digital images for
various purposes, such as enhancing their quality, extracting useful information, or
making them suitable for specific applications like computer vision tasks.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 5


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

Video Analysis(Processing): It allows for video capture, playback, and processing.


This makes it suitable for tasks such as object tracking, motion detection, and video
stabilization.

Machine Learning and Deep Learning: OpenCV integrates with frameworks like
TensorFlow and PyTorch for deep learning-based tasks such as object detection and
image classification.

Computer Vision Algorithms: It includes implementations of algorithms for feature


detection (e.g., Harris corner detection, SIFT, SURF), image segmentation, and
geometric transformations.

Cross-Platform: OpenCV is cross-platform and runs on various operating systems


including Windows, Linux, macOS, iOS, and Android, making it accessible for a wide
range of applications.

Community and Documentation: Being open-source, OpenCV benefits from a large


and active community of developers contributing to its development and maintenance.
It also provides comprehensive documentation and numerous tutorials to help users get
started quickly.

1.1.3 Image processing in OpenCV

Image processing in OpenCV is a powerful toolset for manipulating and analyzing


images. OpenCV (Open Source Computer Vision Library) is an open-source computer
vision and machine learning software library that provides various functions to perform
tasks such as image and video analysis, object detection, face recognition, and more.

Key Concepts in Image Processing with OpenCV:

Loading and Displaying Images: You can load images from files using ‘[Link]()’
and display them using ‘[Link]()’. Remember to use ‘[Link]()’ to handle
the display window properly.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 6


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

Basic Image Operations: OpenCV allows you to perform various operations on


images, such as resizing (‘[Link]()’), rotating (‘[Link]()’), and cropping.

Color Space Conversion: OpenCV provides functions to convert images between


different color spaces, such as RGB to grayscale (‘[Link]()’).

Image Filtering and Enhancement: You can apply various filters to images, such as
blurring (‘[Link]()’ or ‘[Link]()’) and sharpening (‘cv2.filter2D()’).

Thresholding and Image Segmentation: Thresholding (‘[Link]()’) is used to


create binary images from grayscale images, which is useful for object detection and
segmentation.

Edge Detection: OpenCV provides methods for detecting edges in images, such as the
Canny edge detector (‘[Link]()’).

Feature Detection and Description: OpenCV supports feature detection algorithms


like SIFT and SURF, although some require additional installations due to patents.

Object Detection and Recognition: Using techniques like Haar cascades or more
advanced methods like deep learning-based object detection (using frameworks like
TensorFlow or PyTorch integrated with OpenCV).

1.1.4 Video processing in OpenCV

Video processing in OpenCV involves manipulating and analyzing video files or


streams using the OpenCV library, which is a popular computer vision library in
Python.

Reading and Writing:

‘[Link]()’: To capture video from a file or a camera.

‘[Link]()’: To write video to a file.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 7


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

Displaying Video Frames:

‘[Link]()’: To display video frames in a window.

Processing Video Frames: Iterating through each frame and applying transformations,
filters, or algorithms. Examples include resizing, rotating, converting to grayscale, edge
detection, and more.

Real-Time Video Processing: Capturing video from a webcam and applying real-time
processing, such as face detection, object tracking, etc.

Saving Processed Videos: Writing the processed frames to a new video file using
‘[Link]()’.

1.1.5 Machine Learning and Deep Learning in OpenCV

OpenCV (Open Source Computer Vision Library) is a powerful and widely-used


library for computer vision and image processing tasks. It provides various tools and
functionalities for implementing machine learning (ML) and deep learning (DL)
algorithms.

Machine Learning in OpenCV

OpenCV includes a module for machine learning (cv::ml), which contains


implementations of many classical machine learning algorithms, such as:

 K-Nearest Neighbors (KNN)


 Support Vector Machines (SVM)
 Decision Trees and Random Forests
 Boosting (e.g., AdaBoost)
 Neural Networks (e.g., MLP)
 Expectation-Maximization (EM)
 K-Means Clustering

Department Of Electronics And Communication Engineering KLEIT, Hubballi 8


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

Deep Learning in OpenCV

OpenCV supports deep learning through the (cv::dnn) module, which allows you to
load pre-trained models from popular deep learning frameworks such as:

 Caffe
 TensorFlow
 Torch
 ONNX(Open Neural Network Exchange)

1.1.6 Computer Vision Algorithms in OpenCV

OpenCV (Open Source Computer Vision Library) is a popular open-source computer


vision and machine learning software library. It contains more than 2500 optimized
algorithms, which can be used for a wide range of applications, including face
detection, object identification, and tracking, motion tracking, and more.

1.1.7 Cross-Platform in OpenCV

OpenCV is designed to be highly portable and can be used across various platforms,
including Windows, Linux, macOS, Android, and iOS.

Language Bindings:

 C++: The core language for OpenCV development. Most of the functionalities
are first implemented in C++.
 Python: A popular choice due to its simplicity and the extensive support
OpenCV offers. The cv2 module is the primary interface for Python.
 Java: OpenCV offers Java bindings, which are useful for Android
development.
 MATLAB/Octave: Through the ‘mexopencv’ package, OpenCV can be used
in MATLAB or Octave.

Operating System Support:

Department Of Electronics And Communication Engineering KLEIT, Hubballi 9


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

 Windows: OpenCV can be built using various compilers like Visual Studio,
MinGW, etc. Pre-built binaries and installer packages are available for ease of
installation
 Linux: OpenCV is well-supported on Linux distributions, and it can be installed
using package managers like apt for Debian-based systems or yum for RPM-
based systems. Building from source is also straightforward.
 macOS: OpenCV can be installed using Homebrew or built from source using
Xcode.
 Android: OpenCV provides a native Android SDK, making it easy to integrate
computer vision functionalities in Android apps.
 iOS: Similar to Android, OpenCV offers an iOS framework for integrating with
iOS applications.

Installation Methods:

 Pre-built Binaries: Available for Windows, Linux, and macOS.


 Package Managers: OpenCV can be installed using package managers like pip
for Python, apt-get for Debian-based Linux, brew for macOS, etc.

1.1.8 Community and Documentation in OpenCV

OpenCV (Open Source Computer Vision Library) is an open-source computer vision


and machine learning software library. It is designed to provide a common
infrastructure for computer vision applications and to accelerate the use of machine
perception in commercial products. Community support and documentation are critical
aspects of OpenCV, as they help developers understand and utilize the library
effectively.

Community

Forums and Q&A Sites:

Department Of Electronics And Communication Engineering KLEIT, Hubballi 10


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

 OpenCV Forum: The official OpenCV forum is a place where developers can
ask questions, share knowledge, and discuss issues related to OpenCV.

 Stack Overflow: The OpenCV tag on Stack Overflow has a large number of
questions and answers. It's a valuable resource for finding solutions to common
problems and for asking new questions.

Social Media and Networking:

 GitHub: The OpenCV project is hosted on GitHub, where developers can


report issues, contribute to the codebase, and review changes. The GitHub
repository is the central hub for OpenCV's development.
 LinkedIn: There are several groups and pages related to OpenCV on LinkedIn
where professionals discuss industry trends, share job postings, and network.
 Twitter: Following the official OpenCV Twitter account is a good way to stay
updated on the latest news, updates, and events.

Documentation

Official Documentation:

 OpenCV Documentation: The official documentation is comprehensive and


includes tutorials, guides and API references. It's the primary source of
information for learning how to use OpenCV.
 OpenCV Tutorials: The official site provides a range of tutorials, from basic
to advanced topics, which help in understanding various aspects of OpenCV.

Books and Online Courses:

 Books: Several books are available that cover OpenCV in-depth, such as
"Learning OpenCV" by Gary Bradski and Adrian Kaehler and "Mastering
OpenCV with Practical Computer Vision Projects".
 Online Courses: Websites like Coursera, Udemy, and edX offer courses on
computer vision that include modules on OpenCV.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 11


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

CHAPTER 2 METHODOLOGY

2.1 Attendance Marking System using Open CV

Attendance is prime important for both the teacher and student of an educational
organization. So it is very important to keep record of the attendance. The problem
arises when we think about the traditional process of taking attendance in class room.
Calling name or roll number of the student for attendance is not only a problem of time
consumption but also it needs energy. So an automatic attendance system can solve all
above problems. There are some automatic attendances making system which are
currently used by much institution. One of such system is biometric technique and
RFID system. Although it is automatic and a step ahead of traditional method it fails to
meet the time constraint. The student has to wait in queue for giving attendance, which
is time taking. This project introduces an involuntary attendance marking system,
devoid of any kind of interference with the normal teaching procedure. The system can
be also implemented during exam sessions or in other teaching activities where
attendance is highly essential. This system eliminates classical student identification
such as calling name of the student, or checking respective identification cards of the
student, which can not only interfere with the ongoing teaching process, but also can
be stressful for students during examination sessions. In addition, the students have to
register in the database to be recognized. The enrolment can be done on the spot through
the user friendly interface

2.2 Python program for Attendance system using OpenCV

import cv2
import numpy as np
import os
from datetime import datetime

path = 'imgs'
Department Of Electronics And Communication Engineering KLEIT, Hubballi 12
ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

images = []
classNames = []
try:
myList = [Link](path)
print("Images found:", myList)
except FileNotFoundError:
print(f"Error: Directory '{path}' not found.")
myList = []

for cl in myList:
curImg = [Link](f'{path}/{cl}')
if curImg is not None:
gray = [Link](curImg, cv2.COLOR_BGR2GRAY)
[Link](gray)
[Link]([Link](cl)[0])
else:
print(f"Warning: {cl} could not be loaded.")

print("Class Names:", classNames)

if images and classNames:


recognizer = [Link].LBPHFaceRecognizer_create()

def create_labels(images, classNames):


label_ids = {name: idx for idx, name in enumerate(classNames)}
labels = [label_ids[name] for name in classNames]
return labels
labels = create_labels(images, classNames)
[Link](images, [Link](labels))
print('Training Complete')
else:

Department Of Electronics And Communication Engineering KLEIT, Hubballi 13


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

print('Error: No images to train on.')


def markAttendance(name):

if not [Link]('[Link]'):
with open('[Link]', 'w') as f:
[Link]('Name,Time\n')
with open('[Link]', 'a+') as f:
[Link](0)
myDataList = [Link]()
nameList = [[Link](',')[0] for line in myDataList]

if name not in nameList:


now = [Link]()
dtString = [Link]('%H:%M:%S')
[Link](f'{name},{dtString}\n')

cap = [Link](0)
face_cascade = [Link]([Link] +
'haarcascade_frontalface_default.xml')

while True:
success, img = [Link]()
if not success:
print("Warning: Failed to capture image from webcam.")
continue

gray = [Link](img, cv2.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

for (x, y, w, h) in faces:


roi_gray = gray[y:y+h, x:x+w]

Department Of Electronics And Communication Engineering KLEIT, Hubballi 14


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

id_, conf = [Link](roi_gray)


if conf >= 45: # Confidence threshold
name = classNames[id_].upper()
[Link](img, (x, y), (x+w, y+h), (0, 255, 0), 2)
[Link](img, (x, y-35), (x+w, y), (0, 255, 0), [Link])
[Link](img, name, (x+6, y-6), cv2.FONT_HERSHEY_COMPLEX, 1,
(255, 255, 255), 2)
markAttendance(name)

else:
[Link](img, (x, y), (x+w, y+h), (0, 0, 255), 2)
[Link](img, (x, y-35), (x+w, y), (0, 0, 255), [Link])
[Link](img, 'Unknown', (x+6, y-6), cv2.FONT_HERSHEY_COMPLEX,
1, (255, 255, 255),2)

[Link]('Webcam', img)
if [Link](1) & 0xFF == ord('q'):
break
[Link]()
[Link]()

2.3 Code Explanation


Importing Libraries
import cv2
import numpy as np
import os
from datetime import datetime

 ‘cv2’: The OpenCV library used for computer vision tasks.


 ‘numpy’: For handling arrays and numerical operations.
 ‘os’: For interacting with the operating system (e.g., reading directory contents).

Department Of Electronics And Communication Engineering KLEIT, Hubballi 15


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

 ‘datetime’: For handling date and time.

Initializing Variables and Reading Images


path = 'imgs'
images = []

classNames = []
try:
myList = [Link](path)
print("Images found:", myList)

except FileNotFoundError:
print(f"Error: Directory '{path}' not found.")
myList = []
 ‘path’: The directory where images are stored.
 ‘images’: List to store the loaded images.
 ‘classNames’: List to store the names of the classes (labels) derived from the image
filenames.
 ‘try-except’: To handle the case where the directory does not exist.

Loading and Processing Images


for cl in myList:
curImg = [Link](f'{path}/{cl}')
if curImg is not None:
gray = [Link](curImg, cv2.COLOR_BGR2GRAY)
[Link](gray)
[Link]([Link](cl)[0])
else:
print(f"Warning: {cl} could not be loaded.")

 Iterate through each file in the directory.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 16


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

 Read the image using ‘[Link]’.


 Convert the image to grayscale using ‘[Link]’.
 Append the grayscale image to ‘images’ and the filename (without extension)
to ‘classNames’.

Training the Face Recognizer


print("Class Names:", classNames)
if images and classNames:

if int(cv2.__version__.split('.')[0]) < 3:
recognizer = [Link]()
else:
recognizer = [Link].LBPHFaceRecognizer_create()
def create_labels(images, classNames):
label_ids = {name: idx for idx, name in enumerate(classNames)}

labels = [label_ids[name] for name in classNames]


return labels

labels = create_labels(images, classNames)


[Link](images, [Link](labels))
print('Training Complete')
else:
print('Error: No images to train on.')
 Print the class names.
 Check if there are images and class names to train on.
 Create the recognizerusing‘[Link].LBPHFaceRecognizer_create()’ (or
‘[Link]()’ for older OpenCV versions).
 Define ‘create_labels’ to map class names to numeric labels.
 Train the recognizer using the images and labels

Department Of Electronics And Communication Engineering KLEIT, Hubballi 17


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

Marking Attendance
def markAttendance(name):
if not [Link]('[Link]'):
with open('[Link]', 'w') as f:
[Link]('Name,Time\n')
with open('[Link]', 'a+') as f:
[Link](0)
myDataList = [Link]()

nameList = [[Link](',')[0] for line in myDataList]


if name not in nameList:
now = [Link]()
dtString = [Link]('%H:%M:%S')
[Link](f'{name},{dtString}\n')
 Define a function to mark attendance.
 Check if ‘[Link]’ exists; if not, create it and write the header.
 Append the current time and name to the file if the name is not already in the file.

Capturing and Recognizing Faces


cap = [Link](0)
if not [Link]():
print("Error: Could not open webcam.")
exit()
face_cascade = [Link]([Link]
'haarcascade_frontalface_default.xml')
while True:
success, img = [Link]()
if not success:
print("Warning: Failed to capture image from webcam.")
continue
gray = [Link](img, cv2.COLOR_BGR2GRAY)

Department Of Electronics And Communication Engineering KLEIT, Hubballi 18


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)


for (x, y, w, h) in faces:
roi_gray = gray[y:y+h, x:x+w]
id_, conf = [Link](roi_gray)
if conf >= 45: # Confidence threshold
name = classNames[id_].upper()
[Link](img, (x, y), (x+w, y+h), (0, 255, 0), 2)
[Link](img, (x, y-35), (x+w, y), (0, 255, 0), [Link])
[Link](img, name, (x+6, y-6), cv2.FONT_HERSHEY_COMPLEX, 1,
(255, 255, 255), 2)
markAttendance(name)

else:
[Link](img, (x, y), (x+w, y+h), (0, 0, 255), 2)
[Link](img, (x, y-35), (x+w, y), (0, 0, 255), [Link])
[Link](img, 'Unknown', (x+6, y-6), cv2.FONT_HERSHEY_COMPLEX,
1, (255, 255, 255),2)
[Link]('Webcam', img)
if [Link](1) & 0xFF == ord('q'):
break
[Link]()
[Link]()
 Initialize the webcam.
 Check if the webcam opened successfully.
 Load the face cascade classifier for detecting faces.
 In a loop, capture frames from the webcam, convert them to grayscale, and
detect faces.
 For each detected face, predict the identity using the recognizer.
 If the confidence is above a threshold, draw a green rectangle and label the face
with the name.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 19


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

 If the confidence is below the threshold, draw a red rectangle and label the face
as ‘Unknown’.
 Mark attendance for recognized faces.
 Display the video feed with the annotations.
 Exit the loop and release resources when ‘q’ is pressed.
 while True: Infinite loop to continuously read frames from the webcam.
 ‘[Link]()’: Capture a frame.
 ‘gray’: Convert the frame to grayscale.
 ‘faces’: Detect faces in the frame.
 ‘for (x, y, w, h) in faces’: Iterate over detected faces.
 ‘else’: Handle unrecognized faces
 ‘[Link]('Webcam', img)’: Display the frame with annotations.
 ‘[Link](1)’: Wait for 1 millisecond for a key press.
 ‘if [Link](1) & 0xFF == ord('q')’: Break the loop if 'q' is pressed.
 ‘[Link]()’: Release the webcam.
 ‘[Link]()’: Close all OpenCV windows.

2.4 Discussion on Attendance Marking System and Face Recognition


The script efficiently integrates several key components of computer vision and face
recognition, leveraging the OpenCV library for image processing and the LBPH face
recognizer for identifying individuals. By converting images to grayscale, the script
ensures uniformity and reduces computational complexity, which is essential for
accurate face recognition. The use of a Haar Cascade classifier allows for reliable face
detection, which is the initial step in the recognition process.

The script captures frames from the webcam in real-time, ensuring a continuous and
dynamic monitoring system. Each detected face is compared against the trained model,
and if the confidence level meets a predefined threshold, the face is recognized and
labeled with the corresponding name. This feature is crucial for distinguishing between
known and unknown individuals.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 20


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

One of the standout functionalities is the attendance marking system. By recording the
names of recognized individuals along with the current timestamp in [Link],
the script automates the attendance process. This not only enhances accuracy but also
saves time compared to manual methods. The condition to check if a name has already
been recorded prevents duplicate entries, ensuring a clean and accurate log.

The real-time display of the webcam feed with annotations adds a layer of transparency,
allowing users to see the recognition process as it happens. The use of different colored
rectangles (green for recognized faces and red for unknown) provides a clear visual
distinction, making it user-friendly.

Overall, the script demonstrates a well-rounded approach to real-time face recognition


and attendance marking, with practical applications in various settings such as schools,
offices, and events.

Key Components:
 Face Detection: Identifies faces in images or video streams.
 Face Recognition: Matches detected faces with stored templates.
 Attendance Marking: Marks attendance based on recognized faces.

Benefits:
 Accuracy: Reduces errors and biases in attendance marking.
 Efficiency: Saves time and resources.
 Security: Enhances security by preventing proxy attendance.
 Real-time Tracking: Provides real-time attendance data.

Challenges:
 Data Privacy: Raises concerns about storing and managing sensitive biometric
data.
 Variability: Faces can change due to aging, accessories, or lighting conditions.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 21


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

CHAPTER 3 RESULT

Figure 3.1 Program for Attendance Marking System Using OpenCV

Department Of Electronics And Communication Engineering KLEIT, Hubballi 22


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

Figure 3.2 Face Recognition

Figure 3.3 Output with Name and Time

Figure 3.4 Program successfully executed in Terminal

Department Of Electronics And Communication Engineering KLEIT, Hubballi 23


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

CHAPTER 4 CONCLUSION AND FUTURE SCOPE

CONCLUSION

The script successfully loads images from the imgs directory, converts them to
grayscale, and trains a Local Binary Patterns Histograms (LBPH) face recognizer. It
captures frames from the webcam in real-time, detects faces using the Haar Cascade
classifier, and predicts the identity of each detected face. Recognized faces are labeled
with their names, while unrecognized faces are labeled as "Unknown". The script marks
attendance by recording recognized names and the current time in [Link] if
they haven't been previously recorded. The webcam feed displays rectangles around
faces with the corresponding labels. Pressing 'q' stops the webcam feed and closes all
OpenCV windows, ensuring a smooth and user-friendly experience.

FUTURE SCOPE

Project Scope and Direction The main intention of this project is to solve the issues
encountered in the old attendance system while reproducing a brand new innovative
smart system that can provide convenience to the institution. In this project, an
application will be developed which is capable of recognising the identity of each
individuals and eventually record down the data into a database system. Apart from
that, an excel sheet is created which shows the students attendance and is directly
mailed to the respected faculty.

The followings are the project scopes:


 The targeted groups of the attendance monitoring system are the students and
staff of an educational institution.
 The facial recognition process can only be done for 1 person at a time.
 An excel sheet is created which contains the student attendance and is mailed
to the respected faculty.

Department Of Electronics And Communication Engineering KLEIT, Hubballi 24


ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025

REFERENCES

1. Fawaz, A. (2019). A smart classroom of wireless sensor networks for students


time attendance system. In IEEE integrated STEM education conference
(ISEC).

2. Helmi, R., Yusuf, S., & Jamal, A. (2019). Face recognition automatic class
attendance system (FRACAS). In IEEE international conference on automatic
control and intelligent systems (I2CACIS 2019), Selangor, Malaysia, June 29,
2019.

3. Xing, Y. (2019). A class attendance system based on SL4A. In IEEE 4th


international conference on cloud computing and big data analytics.

4. Rosebrock, A. (2018). YOLO object detection with OpenCV. Py Image Search.


Retrieved December 20, 2018.

BIBLIOGRAPHY

1. [Link]

2. [Link]
Management-System-using-OpenCV

3. [Link]
attendance-system-using-python/

4. [Link]
python/

Department Of Electronics And Communication Engineering KLEIT, Hubballi 25

You might also like