0% found this document useful (0 votes)
4 views8 pages

7a 47 49 61 Dip Code

The document contains two Python scripts, 'Attendance.py' and 'Database.py', for a face recognition attendance system. 'Database.py' captures and stores face data for a user, while 'Attendance.py' uses this data to recognize faces in real-time and log attendance. The scripts utilize OpenCV for face detection, KNeighborsClassifier for recognition, and save attendance records in CSV format.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

7a 47 49 61 Dip Code

The document contains two Python scripts, 'Attendance.py' and 'Database.py', for a face recognition attendance system. 'Database.py' captures and stores face data for a user, while 'Attendance.py' uses this data to recognize faces in real-time and log attendance. The scripts utilize OpenCV for face detection, KNeighborsClassifier for recognition, and save attendance records in CSV format.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Attendence.

py:

from sklearn.neighbors import KNeighborsClassifier

import cv2

import pickle

import numpy as np

import os

import csv

import time

from datetime import datetime

from win32com.client import Dispatch

# Speech function for notifications

def speak(message):

try:

voice = Dispatch("SAPI.SpVoice")

voice.Speak(message)

except Exception as e:

print(f"Error in speech synthesis: {e}")

# Create Attendance directory if it doesn't exist

if not os.path.exists('Attendance'):

os.makedirs('Attendance')

# Initialize video capture

video = cv2.VideoCapture(0)

if not video.isOpened():

raise Exception("Error: Could not access the webcam.")

# Load the trained face detection model

cascade_path = r'C:\Users\MONISHA D\Desktop\face+attendance\face


attendance\haarcascade_frontalface_default.xml'
if not os.path.exists(cascade_path):

raise FileNotFoundError(f"Haarcascade file not found at {cascade_path}")

facedetect = cv2.CascadeClassifier(cascade_path)

# Load saved data for names and faces

try:

with open('data/names.pkl', 'rb') as w:

LABELS = pickle.load(w)

with open('data/faces_data.pkl', 'rb') as f:

FACES = pickle.load(f)

except FileNotFoundError as e:

raise FileNotFoundError("Data files not found. Ensure 'names.pkl' and 'faces_data.pkl' exist in
the 'data' directory.")

print('Shape of Faces matrix --> ', FACES.shape)

# Check consistency between FACES and LABELS

print(f"Number of faces: {FACES.shape[0]}")

print(f"Number of labels: {len(LABELS)}")

if FACES.shape[0] != len(LABELS):

raise ValueError("Mismatch between the number of faces and labels. Ensure the dataset is
consistent.")

# Initialize the KNN model and fit it with the data

knn = KNeighborsClassifier(n_neighbors=5)

knn.fit(FACES, LABELS)

# Optional: Load a background image for the UI (if exists)

imgBackground = cv2.imread("background.png") if os.path.exists("background.png") else None

COL_NAMES = ['NAME', 'TIME']


while True:

# Capture each frame from the webcam

ret, frame = video.read()

if not ret:

print("Error: Could not read frame from the webcam.")

break

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Detect faces in the frame

faces = facedetect.detectMultiScale(gray, 1.3, 5)

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

# Crop and resize the face

crop_img = frame[y:y + h, x:x + w]

resized_img = cv2.resize(crop_img, (50, 50)).flatten().reshape(1, -1)

# Predict the name using KNN

try:

output = knn.predict(resized_img)

except Exception as e:

print(f"Error during prediction: {e}")

continue

# Get timestamp for the current entry

ts = time.time()

date = datetime.fromtimestamp(ts).strftime("%d-%m-%Y")

timestamp = datetime.fromtimestamp(ts).strftime("%H:%M:%S")

# Check if the attendance file for the day already exists


attendance_path = f"Attendance/Attendance_{date}.csv"

exist = os.path.isfile(attendance_path)

# Draw rectangle around the face

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

cv2.rectangle(frame, (x, y - 40), (x + w, y), (50, 50, 255), -1)

cv2.putText(frame, str(output[0]), (x, y - 10), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255,


255), 2)

# Prepare attendance data

attendance = [str(output[0]), str(timestamp)]

# Save the attendance when 'o' is pressed

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

speak("Attendance Taken.")

time.sleep(2) # Short delay to avoid duplicate entries

# Write to the CSV file

with open(attendance_path, "a", newline="") as csvfile:

writer = csv.writer(csvfile)

if not exist:

writer.writerow(COL_NAMES) # Write column headers for a new file

writer.writerow(attendance)

# Overlay the frame onto the background image if it exists

if imgBackground is not None:

imgBackground[162:162 + 480, 55:55 + 640] = frame

cv2.imshow("Frame", imgBackground)

else:

cv2.imshow("Frame", frame)
# Break the loop if 'q' key is pressed

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

break

# Release the video capture and close all windows

video.release()

cv2.destroyAllWindows()

Database.py:

import cv2

import pickle

import numpy as np

import os

# Initialize video capture

video = cv2.VideoCapture(0)

# Load the face detection classifier

facedetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Initialize an empty list to store face data

faces_data = []

# Counter for capturing frames

i=0

# Get the user's name

name = input("Enter Your Name: ")

# Ensure the data directory exists

if not os.path.exists('data'):
os.makedirs('data')

while True:

# Capture frame-by-frame

ret, frame = video.read()

# Convert frame to grayscale for face detection

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Detect faces

faces = facedetect.detectMultiScale(gray, 1.3, 5)

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

# Crop and resize the face

crop_img = frame[y:y+h, x:x+w]

resized_img = cv2.resize(crop_img, (50, 50)) # Resize to (50, 50)

# Collect the face data (capture every 10th frame)

if len(faces_data) < 50 and i % 10 == 0:

faces_data.append(resized_img)

# Update the counter

i += 1

# Display the number of images captured

cv2.putText(frame, str(len(faces_data)), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (50, 50,


255), 1)

# Draw a rectangle around the detected face

cv2.rectangle(frame, (x, y), (x + w, y + h), (50, 50, 255), 1)


# Show the frame

cv2.imshow("Frame", frame)

# Stop if 50 faces are collected

if len(faces_data) == 50:

break

# Break the loop on 'q' key press

k = cv2.waitKey(1)

if k == ord('q'):

break

# Release the video capture object and close the window

video.release()

cv2.destroyAllWindows()

# Convert faces_data to numpy array and reshape for storage

faces_data = np.asarray(faces_data)

faces_data = faces_data.reshape(len(faces_data), -1) # Flatten the faces to 3750 dimensions

# Check if the names.pkl file exists, otherwise create it

if 'names.pkl' not in os.listdir('data/'):

names = [name] * 50 # Assign the name to all captured faces

with open('data/names.pkl', 'wb') as f:

pickle.dump(names, f)

else:

# If names.pkl exists, append new names

with open('data/names.pkl', 'rb') as f:

names = pickle.load(f)

names += [name] * 50 # Append the new name 50 times

with open('data/names.pkl', 'wb') as f:


pickle.dump(names, f)

# Check if the faces_data.pkl file exists, otherwise create it

if 'faces_data.pkl' not in os.listdir('data/'):

with open('data/faces_data.pkl', 'wb') as f:

pickle.dump(faces_data, f)

else:

# If faces_data.pkl exists, append new face data

with open('data/faces_data.pkl', 'rb') as f:

faces = pickle.load(f)

faces = np.append(faces, faces_data, axis=0) # Append new faces data, ensuring consistency

with open('data/faces_data.pkl', 'wb') as f:

pickle.dump(faces, f)

print("Data collection completed and saved!")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy