Attendance System with OpenCV
Attendance System with OpenCV
PROJECT REPORT
Submitted to
Submitted by
UMESH DODAMANI 2KE21EC115
Dr. Yerriswamy T
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
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.
I
DECLARATION
Date: 09-08-2024
Place: Hubballi
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.
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
Ⅵ
ATTENDANCE MARKING SYSTEM USING OPENCV 2024-2025
CHAPTER 1 INTRODUCTION
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.
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.
Extensive standard library: Python comes with a large collection of modules and
libraries, providing ready-to-use tools and functionalities for various tasks.
# 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):
print(i)
# while loop
i=0
while i < 5:
print(i)
i += 1
Lists, Tuples and Dictionaries: Lists and dictionaries are fundamental data structures
in Python.
Example: # List
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
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.
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.
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.
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.
Image Filtering and Enhancement: You can apply various filters to images, such as
blurring (‘[Link]()’ or ‘[Link]()’) and sharpening (‘cv2.filter2D()’).
Edge Detection: OpenCV provides methods for detecting edges in images, such as the
Canny edge detector (‘[Link]()’).
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).
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]()’.
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)
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.
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:
Community
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.
Documentation
Official Documentation:
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.
CHAPTER 2 METHODOLOGY
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
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.")
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]
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
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]()
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.
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)}
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]()
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.
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.
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.
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.
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.
CHAPTER 3 RESULT
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.
REFERENCES
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.
BIBLIOGRAPHY
1. [Link]
2. [Link]
Management-System-using-OpenCV
3. [Link]
attendance-system-using-python/
4. [Link]
python/