-
Notifications
You must be signed in to change notification settings - Fork 1
/
faceRecognition.py
177 lines (139 loc) · 6.89 KB
/
faceRecognition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import face_recognition
import os
import numpy as np
from pymongo import MongoClient
from pymongo.errors import ConfigurationError
import cv2
from dotenv import load_dotenv
from datetime import datetime
from time import strftime
import csv
# Load environment variables from .env
load_dotenv()
# Access environment variables
database_url = os.getenv("MONGO_URI")
db_name = os.getenv("DB_NAME")
students_collection = os.getenv("STUDENT_DB_COLLECTION")
try:
client = MongoClient(database_url)
print("Connected to MongoDB successfully form recog!")
except ConfigurationError as e:
print("Error: Failed to connect to MongoDB.")
print("ConfigurationError:", str(e))
except Exception as e:
print("Error: An unexpected error occurred.")
print("Exception:", str(e))
collection = client[db_name][students_collection]
class FaceRecognition:
def __init__(self, root):
self.root = root
self.root.geometry("1950x1030+0+0")
self.root.title("Face Recognition System")
# Title Label
title_lbl = tk.Label(self.root, text="FACE RECOGNITION", font=(
"times new roman", 35, "bold"), bg="white", fg="blue")
title_lbl.place(x=0, y=0, width=1950, height=45)
# Left Image
img_left = Image.open(r"Images/face_detector1.jpg")
img_left = img_left.resize((775, 965), Image.ANTIALIAS)
self.photoimg_left = ImageTk.PhotoImage(img_left)
f_lbl = tk.Label(self.root, image=self.photoimg_left)
f_lbl.place(x=0, y=50, width=775, height=965)
# Right Image
img_right = Image.open(r"Images/facedetact2.jpg")
img_right = img_right.resize((1175, 965), Image.ANTIALIAS)
self.photoimg_right = ImageTk.PhotoImage(img_right)
f_rbl = tk.Label(self.root, image=self.photoimg_right)
f_rbl.place(x=775, y=50, width=1175, height=965)
# Button Right Image
b1_1 = tk.Button(f_rbl, text="Face Recognition", command=self.recognize_faces, cursor="hand2", font=(
"times new roman", 20, "bold"), bg="green", fg="white")
b1_1.place(x=470, y=850, width=220, height=50)
# ================== Face Recognition =====================
def recognize_faces(self):
# Load the trained model
model_path = "traindata/trained_model.xml"
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read(model_path)
# Load the face cascade classifier
face_cascade = cv2.CascadeClassifier(
"haarcascade_frontalface_default.xml")
# Start video capture from webcam
video_capture = cv2.VideoCapture(0)
try:
while True:
ret, frame = video_capture.read()
# Convert the captured frame to grayscale for face detection
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect faces in the frame
faces = face_cascade.detectMultiScale(
gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
for (x, y, w, h) in faces:
# Crop the face region from the frame
face_roi = gray_frame[y:y + h, x:x + w]
# Recognize the face
label, confidence = recognizer.predict(face_roi)
if confidence < 100:
# Retrieve student data based on StudentID
student_data = collection.find_one(
{"StudentID": str(label)})
if student_data:
# Extract student details from the database
student_name = student_data["StudentName"]
roll_no = student_data["RollNo"]
student_id = student_data["StudentID"]
department = student_data["Department"]
# Display student details on the frame
cv2.putText(frame, f"Name: {student_name}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9,
(0, 255, 0), 2)
cv2.putText(frame, f"Roll: {roll_no}", (x, y + h + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(frame, f"Student ID: {student_id}", (x, y + h + 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(frame, f"Department: {department}", (
x, y + h + 90), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2),
self.take_attendance(
student_id, roll_no, student_name, department)
else:
cv2.putText(frame, "Unknown", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9,
(0, 0, 255), 2)
cv2.putText(frame, f"Confidence: {round(confidence, 2)}%", (x, y + h + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
cv2.putText(frame, "Unknown", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9,
(0, 0, 255), 2)
cv2.putText(frame, f"Confidence: {round(confidence, 2)}%", (x, y + h + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
# Draw a rectangle around the face
cv2.rectangle(frame, (x, y), (x + w, y + h),
(255, 0, 0), 2)
# Display the frame with recognized faces
cv2.imshow("Face Recognition", frame)
# Exit if the 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
# Release the video capture and destroy all windows
video_capture.release()
cv2.destroyAllWindows()
# =========================== Take Attendance =========================
def take_attendance(self, i, r, n, d):
with open("attendance/attendance.csv", "r+", newline="\n") as f:
myDataList = f.readlines()
name_list = []
for line in myDataList:
entry = line.split((","))
name_list.append(entry[0])
if ((i not in name_list) and (r not in name_list) and (n not in name_list) and (d not in name_list)):
now = datetime.now()
d1 = now.strftime("%d/%m/%Y")
dtString = now.strftime("%H:%M:%S")
f.writelines(f"\n{i},{r},{n},{d},{dtString},{d1},Present")
if __name__ == "__main__":
root = tk.Tk()
obj = FaceRecognition(root)
root.mainloop()