0% found this document useful (0 votes)
20 views

Face Recognize Code

The document outlines a Python program that implements a face recognition attendance system using Tkinter for the GUI and OpenCV for video capture. It allows users to register students' faces, track attendance, and save the data to an Excel file. The program features functionalities to start face recognition, display attendance logs, and show registered student data.

Uploaded by

dhanvanshg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Face Recognize Code

The document outlines a Python program that implements a face recognition attendance system using Tkinter for the GUI and OpenCV for video capture. It allows users to register students' faces, track attendance, and save the data to an Excel file. The program features functionalities to start face recognition, display attendance logs, and show registered student data.

Uploaded by

dhanvanshg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

import cv2

import face_recognition

import numpy as np

import pandas as pd

from tkinter import *

from tkinter import ttk

from tkinter import messagebox

from datetime import datetime

import threading

import os

from PIL import Image, ImageTk

# Create a simple window with Tkinter

root = Tk()

root.title("ATTENDIFY - Face Recognition Attendance System")

# Set the size of the window and disable resizing

root.geometry("700x750")

root.resizable(False, False)

# Load school logo

school_logo_path = r"C:\Users\lenovo\Pictures\Screenshots\Screenshot (17).png"

school_logo = Image.open(school_logo_path)

school_logo = school_logo.resize((150, 150), Image.Resampling.LANCZOS)

school_logo_img = ImageTk.PhotoImage(school_logo)

known_face_encodings = []

known_face_names = []

known_face_classes = [] # To store class and section information

attendance_df = pd.DataFrame(columns=["Name", "Class", "Section", "Attendance 1", "Time"])

attendance_file = 'Attendance_Data_File.xlsx'

# Check if the Excel file exists, otherwise create a new one

if os.path.exists(attendance_file):

attendance_df = pd.read_excel(attendance_file)

else:

attendance_df = pd.DataFrame(columns=["Name", "Class", "Section", "Attendance 1", "Time"])

# Function to add known faces and student data

def add_known_face(name, class_name, section, image_path):

try:

image = face_recognition.load_image_file(image_path)

encoding = face_recognition.face_encodings(image)[0]

known_face_encodings.append(encoding)
known_face_names.append(name)

known_face_classes.append((class_name, section)) # Store class and section as a tuple

except Exception as e:

print(f"Error adding face for {name}: {e}")

# Add predefined known faces and student information

def initialize_faces():

add_known_face("Prisha", "12", "A", r"C:\Users\lenovo\Downloads\Face_recognition-attendance-system-master\Mihu.jpg")

add_known_face("Shreya", "12", "A", r"C:\Users\lenovo\Downloads\WhatsApp Image 2025-01-15 at 7.46.15 PM.jpeg")

add_known_face("Arzoo", "12", "A", r"C:\Users\lenovo\Downloads\Face_recognition-attendance-system-master\Arzoo.jpg")

add_known_face("Anushka", "12", "B", r"C:\Users\lenovo\Downloads\WhatsApp Image 2025-01-15 at 7.49.17 PM.jpeg")

add_known_face("Vineeta Somni", "PGT", "A.I", r"C:\Users\lenovo\Downloads\WhatsApp Image 2025-01-03 at 11.42.21 AM (1).jpeg")

# Initialize the faces on startup

initialize_faces()

# Function to update Excel

def save_attendance_async():

try:

with pd.ExcelWriter(attendance_file, engine='openpyxl') as writer:

attendance_df.to_excel(writer, index=False)

print(f"Attendance successfully saved to {attendance_file}")

except PermissionError:

messagebox.showerror("Permission Error", f"Unable to write to {attendance_file}. Please ensure the file is not open in another
program.")

# Function to capture video and recognize faces

def start_face_recognition():

global attendance_df

video_capture = cv2.VideoCapture(0)

while True:

ret, frame = video_capture.read()

if not ret:

messagebox.showerror("Error", "Failed to grab frame from webcam!")

break

small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

rgb_small_frame = small_frame[:, :, ::-1]

face_locations = face_recognition.face_locations(rgb_small_frame)

face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):

matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.6)

name = "Unknown"
class_name = "Unknown"

section = "Unknown"

if True in matches:

first_match_index = matches.index(True)

name = known_face_names[first_match_index]

class_name, section = known_face_classes[first_match_index]

# Check if the student is already in the DataFrame

if name in attendance_df['Name'].values:

student_index = attendance_df[attendance_df['Name'] == name].index[0]

# Find the next available attendance column

attendance_column = None

for col in attendance_df.columns[3:]:

if pd.isna(attendance_df.at[student_index, col]):

attendance_column = col

break

if not attendance_column:

attendance_column = f"Attendance {len([col for col in attendance_df.columns if 'Attendance' in col]) + 1}"

# Update attendance

attendance_df.at[student_index, attendance_column] = f"Present ({datetime.now().strftime('%H:%M:%S')})"

else:

# Create a new entry for the student

new_row = pd.DataFrame([{

"Name": name,

"Class": class_name,

"Section": section,

"Attendance 1": f"Present ({datetime.now().strftime('%H:%M:%S')})",

"Time": datetime.now().strftime('%H:%M:%S')

}])

# Append new row to the DataFrame

attendance_df = pd.concat([attendance_df, new_row], ignore_index=True)

# Use threading to update the Excel file

threading.Thread(target=save_attendance_async).start()

# Update UI with the recognized student's information

root.after(0, update_status_label, f"Face Recognized: {name} (Class: {class_name} {section})", "green")

video_capture.release() # Stop webcam feed

return # Exit after recognizing one face

else:
root.after(0, update_status_label, "Face Not Recognized", "red")

if cv2.waitKey(1) & 0xFF == ord('q'):

break

video_capture.release()

cv2.destroyAllWindows()

# Function to update the status label

def update_status_label(text, color):

status_label.config(text=text, fg=color)

# Function to show the attendance log in the Tkinter window

def show_attendance():

global attendance_df

# Create a new window to display the attendance log

attendance_window = Toplevel(root)

attendance_window.title("Attendance Log")

attendance_window.geometry("700x500")

# Create a label for the date

current_date = datetime.now().strftime("%B %d, %Y")

date_label = Label(attendance_window, text=f"Date: {current_date}", font=("Helvetica", 12), fg="black", bg="#f7f7f7")

date_label.pack(pady=5)

# Create a text widget to display the attendance

attendance_text = Text(attendance_window, wrap=WORD, width=70, height=20)

attendance_text.pack(padx=10, pady=10)

# Clear the text widget before showing the updated data

attendance_text.delete(1.0, END)

# Show the attendance in the text widget

for index, row in attendance_df.iterrows():

attendance_text.insert(END, f"{row['Name']} - {row['Class']} {row['Section']} - {row.get('Attendance 1', 'Absent')} - {row['Time']}\n")

# Make the text widget read-only

attendance_text.config(state=DISABLED)

# Function to show the Registered Data in a new window

def show_registered_data():

registered_window = Toplevel(root)

registered_window.title("Registered Data")

registered_window.geometry("600x400")

# Create a Treeview to display the registered data

registered_tree = ttk.Treeview(registered_window, columns=("Name", "Class", "Section"), show="headings")

registered_tree.heading("Name", text="Name")

registered_tree.heading("Class", text="Class")
registered_tree.heading("Section", text="Section")

# Insert the known faces data into the tree

for i in range(len(known_face_names)):

registered_tree.insert("", "end", values=(known_face_names[i], known_face_classes[i][0], known_face_classes[i][1]))

registered_tree.pack(padx=10, pady=10, fill=BOTH, expand=True)

# Function to stop the attendance system (close Tkinter window)

def stop_system():

root.quit()

# GUI Elements (Tkinter Widgets)

# School logo at the top

logo_label = Label(root, image=school_logo_img, bg="#f7f7f7")

logo_label.pack(pady=10)

# Title with School Name

title_label = Label(root, text="Face Recognition Attendance System", font=("Helvetica", 16, "bold"), fg="#333", bg="#f7f7f7")

title_label.pack(pady=10)

# Start the Face Recognition Button

start_button = Button(root, text="Start Face Recognition", font=("Helvetica", 14), fg="white", bg="#4CAF50",


command=start_face_recognition)

start_button.pack(pady=10)

# Show Attendance Button

show_attendance_button = Button(root, text="Show Attendance Log", font=("Helvetica", 14), fg="white", bg="#2196F3",


command=show_attendance)

show_attendance_button.pack(pady=10)

# Show Registered Data Button

show_registered_button = Button(root, text="Show Registered Students", font=("Helvetica", 14), fg="white", bg="#FFC107",


command=show_registered_data)

show_registered_button.pack(pady=10)

# Stop Button

stop_button = Button(root, text="Stop System", font=("Helvetica", 14), fg="white", bg="#f44336", command=stop_system)

stop_button.pack(pady=20)

# Status Label

status_label = Label(root, text="Status: Waiting for input...", font=("Helvetica", 12), fg="black", bg="#f7f7f7")

status_label.pack(pady=10)

# Run the Tkinter event loop

root.mainloop()

You might also like