-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
220 lines (171 loc) · 7.64 KB
/
main.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import cv2
import face_recognition
import os
import datetime
import time
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Constants
IMG_DIR = 'img/'
INFO_DIR = 'students_info/'
RECORD_DIR = 'record/'
COOLDOWN_PERIOD = 10
SKIP_FRAMES = 5
# Load student information and face encodings
def load_student_info(info_dir):
student_info = {}
for filename in os.listdir(info_dir):
if filename.endswith(".txt"):
with open(os.path.join(info_dir, filename), 'r') as file:
lines = file.readlines()
name = lines[0].split(":")[1].strip()
roll = lines[1].split(":")[1].strip()
image_path = lines[2].split(":")[1].strip()
student_image = face_recognition.load_image_file(image_path)
student_encoding = face_recognition.face_encodings(student_image)[0]
student_info[name] = {'roll': roll, 'encoding': student_encoding}
return student_info
# Initialize camera
def initialize_camera():
logger.info("Initializing camera...")
return cv2.VideoCapture(0)
# Perform face recognition
def recognize_faces(frame, student_info, last_detection_time, recorded_students):
small_frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
face_locations = face_recognition.face_locations(small_frame)
face_encodings = face_recognition.face_encodings(small_frame, face_locations)
current_time = time.time()
for face_location, face_encoding in zip(face_locations, face_encodings):
if current_time - last_detection_time >= COOLDOWN_PERIOD:
for name, info in student_info.items():
match = face_recognition.compare_faces([info['encoding']], face_encoding)
if match[0] and name not in recorded_students:
now = datetime.datetime.now()
timestamp = now.strftime('%Y-%m-%d')
record_filename = f"{timestamp}.txt"
record_filepath = os.path.join(RECORD_DIR, record_filename)
with open(record_filepath, 'a') as record_file:
record_file.write(f"name={name}\nroll={info['roll']}\npresent=true\ndate={now.strftime('%Y-%m-%d %H:%M:%S')}\n")
recorded_students.add(name)
last_detection_time = current_time
logger.info(f"Recorded student: {name}")
return last_detection_time
# Record absent students
def record_absent_students(recorded_students, student_info):
now = datetime.datetime.now()
timestamp = now.strftime('%Y-%m-%d')
record_filename = f"{timestamp}.txt"
record_filepath = os.path.join(RECORD_DIR, record_filename)
with open(record_filepath, 'a') as record_file:
for name, info in student_info.items():
if name not in recorded_students:
record_file.write(f"name={name}\nroll={info['roll']}\npresent=false\ndate={now.strftime('%Y-%m-%d %H:%M:%S')}\n")
# Main loop
def main():
student_info = load_student_info(INFO_DIR)
cap = initialize_camera()
last_detection_time = time.time()
frame_count = 0
recorded_students = set()
logger.info("Starting main loop...")
try:
while True:
ret, frame = cap.read()
if frame_count % SKIP_FRAMES == 0:
last_detection_time = recognize_faces(frame, student_info, last_detection_time, recorded_students)
# Display recorded students on the top left corner
log_text = f"Recorded Students: {', '.join(recorded_students)}"
cv2.putText(frame, log_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
cv2.imshow('Face Recognition', frame)
if cv2.waitKey(10) & 0xFF == ord('q'):
logger.info("Exiting main loop...")
break
frame_count += 1
finally:
cap.release()
record_absent_students(recorded_students, student_info)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
# import cv2
# import face_recognition
# import os
# import datetime
# import time
# import logging
# # Set up logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
# # Constants
# IMG_DIR = 'img/'
# INFO_DIR = 'students_info/'
# RECORD_DIR = 'record/'
# COOLDOWN_PERIOD = 10
# SKIP_FRAMES = 5
# # Load student information and face encodings
# def load_student_info(info_dir):
# student_info = {}
# for filename in os.listdir(info_dir):
# if filename.endswith(".txt"):
# with open(os.path.join(info_dir, filename), 'r') as file:
# lines = file.readlines()
# name = lines[0].split(":")[1].strip()
# roll = lines[1].split(":")[1].strip()
# image_path = lines[2].split(":")[1].strip()
# student_image = face_recognition.load_image_file(image_path)
# student_encoding = face_recognition.face_encodings(student_image)[0]
# student_info[name] = {'roll': roll, 'encoding': student_encoding}
# return student_info
# # Initialize camera
# def initialize_camera():
# logger.info("Initializing camera...")
# return cv2.VideoCapture(0)
# # Perform face recognition
# def recognize_faces(frame, student_info, last_detection_time, recorded_students):
# small_frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
# face_locations = face_recognition.face_locations(small_frame)
# face_encodings = face_recognition.face_encodings(small_frame, face_locations)
# current_time = time.time()
# for face_location, face_encoding in zip(face_locations, face_encodings):
# if current_time - last_detection_time >= COOLDOWN_PERIOD:
# for name, info in student_info.items():
# match = face_recognition.compare_faces([info['encoding']], face_encoding)
# if match[0] and name not in recorded_students:
# now = datetime.datetime.now()
# timestamp = now.strftime('%Y-%m-%d')
# record_filename = f"{timestamp}.txt"
# record_filepath = os.path.join(RECORD_DIR, record_filename)
# with open(record_filepath, 'a') as record_file:
# record_file.write(f"name={name}\nroll={info['roll']}\npresent=true\ndate={now.strftime('%Y-%m-%d %H:%M:%S')}\n")
# recorded_students.add(name)
# last_detection_time = current_time
# logger.info(f"Recorded student: {name}")
# return last_detection_time
# # Main loop
# def main():
# student_info = load_student_info(INFO_DIR)
# cap = initialize_camera()
# last_detection_time = time.time()
# frame_count = 0
# recorded_students = set()
# logger.info("Starting main loop...")
# try:
# while True:
# ret, frame = cap.read()
# if frame_count % SKIP_FRAMES == 0:
# last_detection_time = recognize_faces(frame, student_info, last_detection_time, recorded_students)
# # Display recorded students on the top left corner
# log_text = f"Recorded Students: {', '.join(recorded_students)}"
# cv2.putText(frame, log_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
# cv2.imshow('Face Recognition', frame)
# if cv2.waitKey(10) & 0xFF == ord('q'):
# logger.info("Exiting main loop...")
# break
# frame_count += 1
# finally:
# cap.release()
# cv2.destroyAllWindows()
# if __name__ == "__main__":
# main()