import cv2
import numpy as np
import face_recognition
import os
import csv
from datetime import datetime
# Folder containing images of known faces
KNOWN_FACES_DIR = "known_faces"
ATTENDANCE_FILE = "attendance.csv"
# Load known face encodings and names
known_encodings = []
known_names = []
for filename in os.listdir(KNOWN_FACES_DIR):
image_path = os.path.join(KNOWN_FACES_DIR, filename)
image = face_recognition.load_image_file(image_path)
encoding = face_recognition.face_encodings(image)[0]
known_encodings.append(encoding)
known_names.append(os.path.splitext(filename)[0]) # Remove file extension
# Initialize webcam
video_capture = cv2.VideoCapture(0)
# Function to mark attendance
def mark_attendance(name):
with open(ATTENDANCE_FILE, "a", newline="") as file:
writer = csv.writer(file)
now = datetime.now()
time_str = now.strftime("%H:%M:%S")
date_str = now.strftime("%Y-%m-%d")
writer.writerow([name, date_str, time_str])
# Create CSV file with headers if it doesn't exist
if not os.path.exists(ATTENDANCE_FILE):
with open(ATTENDANCE_FILE, "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Date", "Time"])
# Process video stream
while True:
ret, frame = video_capture.read()
if not ret:
break
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Optimize performance
rgb_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
# Detect faces in the frame
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for encoding, location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_encodings, encoding)
name = "Unknown"
if True in matches:
index = matches.index(True)
name = known_names[index]
mark_attendance(name) # Mark attendance in CSV
# Draw bounding box around detected face
top, right, bottom, left = [v * 4 for v in location]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.imshow("Face Attendance System", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
video_capture.release()
cv2.destroyAllWindows()
No comments:
Post a Comment