Attendence / automaticAttedance.py
Bhanumani12's picture
Create automaticAttedance.py
0d46e2c verified
import cv2
import numpy as np
import pandas as pd
import os
from datetime import datetime
def fill_attendance(update_message, video_path=None):
# Load the trained face recognition model
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainer.yml")
# Load the Haar Cascade for face detection
face_detector = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
# Read the student details
student_details = pd.read_csv("StudentDetails/studentdetails.csv")
# Get the video stream
if video_path:
video_capture = cv2.VideoCapture(video_path)
else:
video_capture = cv2.VideoCapture(0)
# Process frames
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_detector.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
# Get the face region
face = gray[y:y + h, x:x + w]
# Recognize the face
id_, confidence = recognizer.predict(face)
if confidence < 100:
student_name = student_details.loc[student_details['ID'] == id_, 'Name'].values[0]
update_message(f"Attendance marked for {student_name}")
cv2.putText(frame, f"ID: {id_} - {student_name}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# Log the attendance in the CSV
log_attendance(id_, student_name)
else:
student_name = "Unknown"
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the video feed
cv2.imshow("Attendance", frame)
# Break if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
def log_attendance(student_id, student_name):
attendance_file = "Attendance/attendance.csv"
# If the attendance file doesn't exist, create it with headers
if not os.path.exists(attendance_file):
with open(attendance_file, 'w') as f:
f.write("ID,Name,Time\n")
# Log attendance with timestamp
with open(attendance_file, 'a') as f:
f.write(f"{student_id},{student_name},{datetime.now()}\n")