Build a face recognition based attendance system using Python

It's a face recognition based attendance system using python - PySeek

Introduction

In this digital age, many organizations use face recognition systems to identify if an employee is present and to record their entry time. There are many face recognition systems available which are advanced as well.

But here, we'll create our own system using our lovely programming language. In this tutorial, I will guide you to build such a face recognition based attendance system using python.

It's a very popular python project and can be used in real-life too. So, without wasting your time, let's get started.

☛Visit AlsoTic Tac Toe Game in Python with Artificial Intelligence

 

The project details

In this project, I used OpenCV and the face-recognition library to read and identify faces through a webcam. This project consists of two folders ('Image' and 'Records') and a program file('attendance.py').

The 'Image' folder contains pictures of employees or students. To show you an example, I have taken some pictures of my friends and put them into that folder. You can put other pictures here as you need.

It's a folder, containing five images for showing as an example for the face recognition attendance system.

The program file reads faces through the WebCam. If the face is identified, then it will create a CSV file(One time only, for the first match) with the current date. For example, a CSV file will be created automatically as follows: "record_10_03_2022.csv" for 10th March 2022.

A great feature of this program is that you don't have to create CSV files with different names every day. 

At midnight, another CSV file will be automatically created according to the next day's date(only if the program is running) and the recording will start anew.

In the program, you'll see a different thread has been used for reading the video frame through the WebCam. I've followed this way to avoid the sluggish situation while the camera is working.

You must Install these libraries

Before installing the 'face_recognition' library you have to install 'cmake' and 'dlib'.

Let's perform the installation process one by one as below. Use pip3 instead of pip if you are using Linux.

Install cmake

☞pip install cmake

Install dlib

Dlib is a cross-platform software library; written in C++. You've to install cmake before installing dlib. It may take around 15-20 minutes to install. So, don't be surprised if it takes extra time.

☞pip install dlib

Install face recognition

Now, install the face_recognition library. You can read the documentation from here.

☞pip install face_recognition

Install OpenCV

OpenCV-Python is a python library that is designed to solve computer vision problems. It's a python wrapper for the original OpenCV, implemented using C++.

Python is slower as compared to C/C++. But it can be extended with C++ using Python wrappers, which will be used as Python modules. It will give us two advantages. First, the code will be as fast as the C++ code, and second, it will be easy to code in Python than in C++.

☞pip install opencv-python

There are many lovely projects where OpenCV has played a major role. Visit them too.

👉Cartoonify an Image using a Python Application

👉A face recognition based attendance system using Python

👉Live Glass Detection on Faces using Python

Install NumPy

NumPy is a Python library that provides a powerful N-dimensional array object, several mathematical functions, and much more. 

It's used widely in machine learning, deep learning, image processing, etc. for working with multi-dimensional arrays. I've used it in this project for performing a computational task.

☞pip install numpy

Import the modules

Let's create a python file with this name, "attendance.py" and start writing your code by importing the necessary modules here.


import face_recognition as fr
from threading import Thread
import numpy as np
import time
import os
import cv2

Declare a list

I've declared a python list here. It contains the names of some people.

It contains the names of some people. If anyone from there appears in front of the camera, the program will not add their record to the CSV file.

It is optional; You can avoid these features added to the project.


exclude_names = ['Unknown', 'HOD', 'Principal']

Create a class to capture and read video frames

Here, we'll create a different class to capture the video frames through the WebCam and read that frames in a different thread.


class VideoStream:
def __init__(self, stream):
self.video = cv2.VideoCapture(stream)
# Setting the FPS for the video stream
self.video.set(cv2.CAP_PROP_FPS, 60)

if self.video.isOpened() is False:
print("Can't accessing the webcam stream.")
exit(0)

self.grabbed , self.frame = self.video.read()

self.stopped = True

self.thread = Thread(target=self.update)
self.thread.daemon = True

def start(self):
self.stopped = False
self.thread.start()

def update(self):
while True :
if self.stopped is True :
break
self.grabbed , self.frame = self.video.read()
self.video.release()

def read(self):
return self.frame

def stop(self):
self.stopped = True

Encode the faces


def encode_faces():
encoded_data = {}

for dirpath, dnames, fnames in os.walk("./Images"):
for f in fnames:
if f.endswith(".jpg") or f.endswith(".png"):
face = fr.load_image_file("Images/" + f)
encoding = fr.face_encodings(face)[0]
encoded_data[f.split(".")[0]] = encoding

# return encoded data of images
return encoded_data

Remember, we put five images including mine in the 'Images' folder. Now, the above code does the following tasks.

1. The program finds image files in the 'Images' folder.

2. Selects only those files that ended with .jpg or .png extensions.

3. Then, it stores those selected files into a variable and encodes them one by one.

4. The Encoded data is stored in a python dictionary variable named 'encoded_data'.

5. In the end, the function returns a variable, 'encoded_data'.

Keep the record of attendance

Let's declare a different function, 'Attendance' to record the entering time of the employees or students along with their names. 

First, the function will check if the CSV file is present there. If not, it will create a new CSV file every day with the current date.


def Attendance(name):
# It will get the current date
today = time.strftime('%d_%m_%Y')
# To create a file if it doesn't exists
f = open(f'Records/record_{today}.csv', 'a')
f.close()

# It will read the CSV file and check if the name
# is already present there or not.
# If the name doesn't exist there, it'll be added
# to a list called 'names'
with open(f'Records/record_{today}.csv', 'r') as f:
data = f.readlines()
names = []
for line in data:
entry = line.split(',')
names.append(entry[0])

# It will check it the name is in the list 'names'
# or not. If not then, the name will be added to
# the CSV file along with the entering time
with open(f'Records/record_{today}.csv', 'a') as fs:
if name not in names:
current_time = time.strftime('%H:%M:%S')
if name not in exclude_names:
fs.write(f"\n{name}, {current_time}")

The main function

Here is the full code for your convenience.


if __name__ == "__main__":
faces = encode_faces()
encoded_faces = list(faces.values())
faces_name = list(faces.keys())
video_frame = True

# Initialize and start multi-thread video input
# stream from the WebCam.
# 0 refers to the default WebCam
video_stream = VideoStream(stream=0)
video_stream.start()

while True:
if video_stream.stopped is True:
break
else :
frame = video_stream.read()

if video_frame:
face_locations = fr.face_locations(frame)
unknown_face_encodings = fr.face_encodings(frame, \
face_locations)

face_names = []
for face_encoding in unknown_face_encodings:
# Comapring the faces
matches = fr.compare_faces(encoded_faces, \
face_encoding)
name = "Unknown"

face_distances = fr.face_distance(encoded_faces,\
face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = faces_name[best_match_index]

face_names.append(name)

video_frame = not video_frame

for (top, right, bottom, left), name in zip(face_locations,\
face_names):
# Draw a rectangular box around the face
cv2.rectangle(frame, (left-20, top-20), (right+20, \
bottom+20), (0, 255, 0), 2)
# Draw a Label for showing the name of the person
cv2.rectangle(frame, (left-20, bottom -15), \
(right+20, bottom+20), (0, 255, 0), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
# Showing the name of the detected person through
# the WebCam
cv2.putText(frame, name, (left -20, bottom + 15), \
font, 0.85, (255, 255, 255), 2)

# Call the function for attendance
Attendance(name)

# delay for processing a frame
delay = 0.04
time.sleep(delay)

cv2.imshow('frame' , frame)
key = cv2.waitKey(1)
# Press 'q' for stop the executing of the program
if key == ord('q'):
break

video_stream.stop()

# closing all windows
cv2.destroyAllWindows()

Download the entire project

Download the zip file of this Attendance System project from my GitHub page(https://github.com/subhankar-rakshit) through the Download button.

☛Visit AlsoLive Glass Detection on Faces using Python - Most Easy Approach

Summary

In this tutorial, we build a face recognition based attendance system using python. We used OpenCV and face_recognition library to read and identify faces through the WebCam.

We used the threading module here to capture video frames to a different thread so that the program could perform other tasks more efficiently.

You can use this project in real life too, just need to improve the camera quality a little bit higher. You can use your mobile phone camera or an external WebCam to get a good quality of video capturing. There is a mobile application called 'IP WebCam', which allows accessing mobile phone cameras through other devices like desktops, laptops, etc.

That's all for today, see you soon on the next topic. Be sure to leave your comments below for any questions related to this project. You will receive an immediate response.

Thanks for reading!💙

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post