Absolutely! Building a face detection attendance system is a great project. To get started, you'll require certain tools, libraries, and an understanding of Python. Below, I’ll outline the steps along with some code snippets to help you create a fully functional attendance system.
Prerequisites
-
Python Installed: Make sure you have Python installed on your system. You can download it from python.org.
-
Libraries: You will need a few libraries. You can install them using pip:
pip install opencv-python opencv-python-headless face_recognition pandas
Step-by-Step Guide
Step 1: Set Up Your Environment
Create a new folder for your project and navigate into it. This will be where you store your Python scripts and any related files.
Step 2: Capture Faces
You’ll first need to set up a way to capture faces and store them for recognition. You can use the laptop camera for this.
import cv2
import face_recognition
import os
# Create the directory for images if it doesn't exist
if not os.path.exists("known_faces"):
os.makedirs("known_faces")
def capture_faces():
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
rgb_frame = frame[:, :, ::-1]
# Display the captured frame
cv2.imshow('Video', frame)
# Capture a face
if cv2.waitKey(1) & 0xFF == ord('c'): # Press 'c' to capture
name = input("Enter name for the captured face: ").strip()
face_locations = face_recognition.face_locations(rgb_frame)
if len(face_locations) > 0:
# Save the first detected face
top, right, bottom, left = face_locations[0]
face_image = frame[top:bottom, left:right]
cv2.imwrite(f"known_faces/{name}.jpg", face_image)
print(f"Face saved for {name}")
# Exit the capture loop
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
capture_faces()
Step 3: Face Recognition for Attendance
Next, you’ll want to implement the face recognition system to mark attendance based on the captured faces.
import cv2
import face_recognition
import pandas as pd
import datetime
# Load known faces
def load_known_faces():
known_faces = []
known_names = []
for filename in os.listdir("known_faces"):
if filename.endswith(".jpg"):
image = face_recognition.load_image_file(f"known_faces/{filename}")
encoding = face_recognition.face_encodings(image)[0]
known_faces.append(encoding)
known_names.append(os.path.splitext(filename)[0])
return known_faces, known_names
def mark_attendance(name):
now = datetime.datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
attendance_df = pd.DataFrame({"Name": [name], "Time": [current_time]})
if os.path.isfile("attendance.csv"):
attendance_df.to_csv("attendance.csv", mode='a', header=False, index=False)
else:
attendance_df.to_csv("attendance.csv", index=False)
def recognize_faces():
video_capture = cv2.VideoCapture(0)
known_faces, known_names = load_known_faces()
while True:
ret, frame = video_capture.read()
rgb_frame = frame[:, :, ::-1]
# Find all face locations and encodings in the current frame
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = "Unknown"
# Check if we have a match
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
mark_attendance(name)
# Draw a rectangle around the face and label it
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
# Exit on 'q'
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
recognize_faces()
Final Steps
-
Capture Faces First: Run the first part of the code to capture faces and store them with names before running the recognition part.
-
Run the Recognition Code: Once you have your known faces stored, run the second part to start the attendance system.
-
Attendance Data: The attendance will be logged in attendance.csv including the names and timestamps.
Notes
- Ensure you have installed the necessary libraries, and that your webcam is functioning.
- You may want to enhance this basic system with error handling and user interfaces for a smoother experience.
- Be mindful of privacy and ethical considerations when using face recognition technologies.
Feel free to ask if you have any further questions or need clarification on any steps!