Building a Face Recognition Attendance System using Python and OpenCV

Building a Face Recognition Attendance System using Python and OpenCV

ยท

3 min read

Introduction: In this article, we'll explore how to build a face recognition attendance system using Python and OpenCV. Face recognition is a powerful technique that can be used for various applications, including attendance tracking. We'll utilize the face_recognition library, which provides an easy-to-use interface for face detection and recognition. Let's dive into the code and see how it works!

Prerequisites: Before getting started, make sure you have the following libraries installed:

  • OpenCV (pip install opencv-python)

  • face_recognition (pip install face-recognition)

Code Explanation:

import cv2
import csv
import numpy as np
import face_recognition
from datetime import datetime

video_capture = cv2.VideoCapture(0)

We begin by importing the required libraries and initializing the video capture object to access the webcam.

# Load known faces
image1 = face_recognition.load_image_file('') # Enter path for the image file
image1_encoding = face_recognition.face_encodings(image1)[0]
image2 = face_recognition.load_image_file('') # Enter path for the image file
image2_encoding = face_recognition.face_encodings(image2)[0]

known_face_encodings = [image1_encoding, image2_encoding]
known_face_names = ["", ""] # Enter name you want to display for the face

Next, we load the known faces for recognition. Replace the empty strings in image1 and image2 with the paths to your own image files. Each known face is encoded using the face_encodings function and stored in the known_face_encodings list. Similarly, provide corresponding names in the known_face_names list.

# List of person
persons = known_face_names.copy()

We create a copy of the known_face_names list and store it in the persons list. This will be used to keep track of the people present.

face_locations = []
face_encodings = []

# Get the current date and time
now = datetime.now()
current_date = now.strftime("%Y-%m-%d")

f = open(f"{current_date}.csv", "w+", newline="")
lnwriter = csv.writer()

We initialize some variables and open a CSV file for writing the attendance data. The file name is based on the current date.

while True:
    _, frame = video_capture.read()
    smallframe = cv2.resize(frame, (0,0), fx=0.25, fy=0.25)
    rgb_small_frame = cv2.cvtColor(smallframe, cv2.COLOR_BGR2RGB)

Inside the main loop, we capture frames from the webcam and resize them to improve processing speed. The frames are converted to RGB format for face recognition.

 # Recognise faces
    face_locations = face_recognition.face_locations(rgb_small_frame)
    face_encodings = face_recognition.face_encodings(rgb_small_frame)

    for face_encoding in face_encodings:
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
        face_distance = face_recognition.face_distance(known_face_encodings, face_encoding)
        best_match_index = np.argmin(face_distance)

        if (matches[best_match_index]):
            name = known_face_names[best_match_index]

        # Add the text if a person is present
        if name in known_face_names:
            font = cv2.FONT_HERSHEY_SIMPLEX
            bottomLeftCornerOfText = (10, 100)
            fontScale = 1.5


            fontColor = (255, 0, 0)
            thickness = 3
            lineType = 2
            cv2.putText(frame, name + " Present", bottomLeftCornerOfText, font, fontScale, fontColor, thickness, lineType)

            if name in persons:
                persons.remove(name)
                current_time = now.strftime("%H:%M:%S")
                lnwriter.writerow(name, current_time)

            cv2.imshow("Attendance", frame)
            if cv2.waitKey(1) & 0xFF == ord("q"):
                break

The code identifies faces in the frame by comparing their encodings with the known face encodings. If a match is found, the corresponding name is retrieved from known_face_names. If the person is present and their name is in the persons list, we remove their name from the list, record the current time, and write the attendance data to the CSV file.

Lastly, we display the frame with the person's name and check for the 'q' key to break the loop.

video_capture.release()
cv2.destroyAllWindows()
f.close()

Finally, we release the video capture, close the OpenCV windows, and close the CSV file.

Conclusion:

In this article, we learned how to build a face recognition attendance system using Python and OpenCV. By utilizing the face_recognition library, we were able to detect and recognize faces in real-time, record attendance, and save the data to a CSV file. Face recognition technology has numerous applications beyond attendance systems, such as access control, surveillance, and personalized experiences. Feel free to explore and expand upon this code to suit your specific needs!

Did you find this article valuable?

Support BigSmoke's Blog by becoming a sponsor. Any amount is appreciated!

ย