0% found this document useful (0 votes)
1 views6 pages

Dataset

Uploaded by

Sai Krishna2303
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)
1 views6 pages

Dataset

Uploaded by

Sai Krishna2303
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/ 6

✅ 1.

Dataset Creation Module (with Preprocessing)


python
CopyEdit
import cv2
import os

def create_student_dataset(student_id, name, save_dir='dataset'):


cap = cv2.VideoCapture(0)
haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
student_path = os.path.join(save_dir, f"{student_id}_{name}")
os.makedirs(student_path, exist_ok=True)

count = 0
while count < 30:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = haar.detectMultiScale(gray, scaleFactor=1.3,
minNeighbors=5)

for (x, y, w, h) in faces:


roi = gray[y:y+h, x:x+w]
roi_resized = cv2.resize(roi, (200, 200))
cv2.imwrite(f"{student_path}/{count}.jpg", roi_resized)
count += 1
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

cv2.imshow("Capturing Dataset", frame)


if cv2.waitKey(1) == 27: # ESC to break
break

cap.release()
cv2.destroyAllWindows()

✅ 2. Training the LBPH Face Recognizer


python
CopyEdit
import numpy as np
from PIL import Image
from cv2 import face

def train_model(dataset_path='dataset', model_save='trainer.yml'):


recognizer = face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

image_paths = []
labels = []
label_map = {}

current_id = 0
for folder in os.listdir(dataset_path):
folder_path = os.path.join(dataset_path, folder)
if os.path.isdir(folder_path):
label_map[current_id] = folder
for image_file in os.listdir(folder_path):
image_path = os.path.join(folder_path, image_file)
gray_image = Image.open(image_path).convert('L')
img_np = np.array(gray_image, 'uint8')

faces = detector.detectMultiScale(img_np)
for (x, y, w, h) in faces:
face_roi = img_np[y:y+h, x:x+w]
image_paths.append(face_roi)
labels.append(current_id)
current_id += 1

recognizer.train(image_paths, np.array(labels))
recognizer.save(model_save)
return label_map

✅ 3. Real-Time Face Recognition & Attendance Marking


python
CopyEdit
def recognize_and_mark_attendance(trainer='trainer.yml', label_map={},
excel_path='attendance.xlsx'):
recognizer = face.LBPHFaceRecognizer_create()
recognizer.read(trainer)

face_cascade =
cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)

while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x, y, w, h) in faces:


face_roi = gray[y:y+h, x:x+w]
id_, confidence = recognizer.predict(face_roi)
name = label_map.get(id_, "Unknown")

if confidence < 70:


mark_attendance(name)
text = f"{name} ({round(confidence,2)}%)"
else:
text = "Unknown"

cv2.putText(frame, text, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX,


0.9, (0, 255, 0), 2)
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

cv2.imshow("Face Recognition", frame)


if cv2.waitKey(1) == 27:
break

cap.release()
cv2.destroyAllWindows()

✅ 4. Attendance Marking + Emailing Absentee List


mark_attendance() function:

python
CopyEdit
import pandas as pd
import datetime

def mark_attendance(name, excel_path='attendance.xlsx'):


date = datetime.date.today().strftime("%Y-%m-%d")
time = datetime.datetime.now().strftime("%H:%M:%S")

if not os.path.exists(excel_path):
df = pd.DataFrame(columns=["Name", "Date", "Time"])
else:
df = pd.read_excel(excel_path)

if not ((df['Name'] == name) & (df['Date'] == date)).any():


df = pd.concat([df, pd.DataFrame([[name, date, time]],
columns=["Name", "Date", "Time"])])
df.to_excel(excel_path, index=False)

📧 Email Absentee List (End of Session)

python
CopyEdit
import smtplib
from email.message import EmailMessage

def send_absentees_email(attendance_file, total_students, faculty_email):


today = datetime.date.today().strftime("%Y-%m-%d")
df = pd.read_excel(attendance_file)
present_today = df[df['Date'] == today]['Name'].unique().tolist()
absentees = list(set(total_students) - set(present_today))

if not absentees:
return

message = EmailMessage()
message['Subject'] = f"Absentee List - {today}"
message['From'] = "[email protected]"
message['To'] = faculty_email
message.set_content("Absent Students:\n" + "\n".join(absentees))

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:


smtp.login("[email protected]", "your_app_password")
smtp.send_message(message)

Replace [email protected] and "your_app_password" with Gmail & App Password.


You must enable App Passwords in Google.

Would you like me to generate the corresponding HTML templates (student upload,
attendance view, report page), or a one-click .bat or .sh launcher?

You said:
yes
ChatGPT said:

Memory updated

Great! Let's start with the HTML templates first. I’ll give you the three main templates for:

1. Dashboard (dashboard.html)
2. Student Management (students.html)
3. Attendance Management (attendance.html)
4. Report View (report.html)

templates/dashboard.html

html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Attendance System</h1>
<ul>
<li><a href="/students">Manage Students</a></li>
<li><a href="/lecturers">Manage Lecturers</a></li>
<li><a href="/attendance">View Attendance</a></li>
<li><a href="/report">Generate Report</a></li>
</ul>
</body>
</html>

👩‍🎓 templates/students.html
html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Students</title>
</head>
<body>
<h2>Student Management</h2>
<form method="POST" action="/add_student">
Student ID: <input type="text" name="student_id" required><br>
Name: <input type="text" name="name" required><br>
<button type="submit">Add Student (Capture Image)</button>
</form>

<h3>Registered Students</h3>
<ul>
{% for student in students %}
<li>
{{ student['Student ID'] }} - {{ student['Name'] }}
<a href="/delete_student/{{ student['Student ID']
}}">Delete</a>
</li>
{% endfor %}
</ul>
</body>
</html>

📅 templates/attendance.html
html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Attendance Records</title>
</head>
<body>
<h2>Attendance Records</h2>
<table border="1">
<thead>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Subject</th>
<th>Lecturer</th>
<th>Session Time</th>
<th>Duration</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{% for row in attendance %}
<tr>
<td>{{ row['Student ID'] }}</td>
<td>{{ row['Name'] }}</td>
<td>{{ row['Subject'] }}</td>
<td>{{ row['Lecturer'] }}</td>
<td>{{ row['Session Time'] }}</td>
<td>{{ row['Duration'] }}</td>
<td>{{ row['Date'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

📊 templates/report.html
html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Absentee Report</title>
</head>
<body>
<h2>Absentee Summary - {{ date }}</h2>
<table border="1">
<thead>
<tr>
<th>Subject</th>
<th>Absentees Count</th>
</tr>
</thead>
<tbody>
{% for subject, count in report.items() %}
<tr>
<td>{{ subject }}</td>
<td>{{ count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

You might also like