Attendence / app.py
Bhanumani12's picture
Update app.py
3d03826 verified
import cv2
import gradio as gr
import numpy as np
import os
# Directory to store registered students' faces
registered_faces_dir = "registered_faces"
# Ensure the directory exists
if not os.path.exists(registered_faces_dir):
os.makedirs(registered_faces_dir)
# Load Haar Cascade Classifier for face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# Function to register the student
def register_student(enrollment_id, student_name, image):
# Convert the image to grayscale for face detection
img_gray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = face_cascade.detectMultiScale(img_gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
if len(faces) == 0:
return "No face found in the image. Please upload a valid face image."
# Process the detected face
for (x, y, w, h) in faces:
face_image = img_gray[y:y+h, x:x+w]
# Resize the face image to a fixed size for registration
face_image_resized = cv2.resize(face_image, (100, 100))
# Check if the face already exists in the registered directory
for filename in os.listdir(registered_faces_dir):
# Load the existing face image and compare using simple template matching
registered_face = cv2.imread(os.path.join(registered_faces_dir, filename), cv2.IMREAD_GRAYSCALE)
registered_face_resized = cv2.resize(registered_face, (100, 100))
# Use template matching to compare faces
res = cv2.matchTemplate(registered_face_resized, face_image_resized, cv2.TM_CCOEFF_NORMED)
match_value = np.max(res)
if match_value > 0.8: # Adjust threshold as needed
return f"Student already registered with Enrollment ID: {filename.split('_')[0]}"
# If it's a new face, register it
face_file_path = os.path.join(registered_faces_dir, f"{enrollment_id}_{student_name}.jpg")
cv2.imwrite(face_file_path, face_image_resized) # Save the detected face image
return "Student registered successfully."
# Gradio Interface
def face_registration_interface(enrollment_id, student_name, image):
return register_student(enrollment_id, student_name, image)
iface = gr.Interface(
fn=face_registration_interface,
inputs=[
gr.inputs.Textbox(label="Enrollment ID"),
gr.inputs.Textbox(label="Student Name"),
gr.inputs.Image(type="pil", label="Upload Student's Face Image")
],
outputs="text",
live=True
)
iface.launch()