Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import face_recognition
- import os, sys
- import cv2
- import numpy as np
- import pandas as pd
- import datetime
- import traceback
- class FaceRecognition:
- def __init__(self):
- self.known_face_encodings, self.known_face_names = self.encode_faces()
- self.attendance_df = self.load_or_create_attendance_file()
- self.process_current_frame = True
- self.color_border = (0, 0, 255)
- self.color_text = (255, 255, 255)
- self.process_scale = 0.25
- def encode_faces(self):
- known_face_encodings = []
- known_face_names = []
- for image in os.listdir('faces'):
- face_image = face_recognition.load_image_file(f'./faces/{image}')
- face_encodings = face_recognition.face_encodings(face_image)
- if len(face_encodings) > 0:
- known_face_encodings.append(face_encodings[0])
- known_face_names.append(image.split('.')[0])
- print("Known faces:", known_face_names)
- return known_face_encodings, known_face_names
- def load_or_create_attendance_file(self):
- attendance_file_path = 'attendance.xlsx'
- if os.path.exists(attendance_file_path):
- return pd.read_excel(attendance_file_path, index_col=0)
- else:
- # Create a new DataFrame with student names
- student_names = [name.split('.')[0] for name in os.listdir('faces')]
- attendance_df = pd.DataFrame(index=student_names, columns=['Date'])
- attendance_df.to_excel(attendance_file_path)
- return attendance_df
- def mark_attendance(self, name):
- today = datetime.date.today().strftime("%Y-%m-%d")
- if today not in self.attendance_df.columns:
- self.attendance_df[today] = ''
- self.attendance_df.at[name, today] = 'p'
- self.attendance_df.to_excel('attendance.xlsx')
- def process_frame(self, frame):
- face_locations = face_recognition.face_locations(frame)
- if not face_locations:
- print("No faces found.")
- return []
- print(f"Found {len(face_locations)} face(s): {face_locations}")
- face_encodings = face_recognition.face_encodings(frame, face_locations)
- found_faces = []
- for i, face_encoding in enumerate(face_encodings):
- print(f"* Analyzing face #{i}")
- matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding)
- face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
- best_match_index = np.argmin(face_distances)
- print(f"** Best #{best_match_index} | {list(zip(face_distances, matches))}")
- if matches[best_match_index]:
- name = self.known_face_names[best_match_index]
- found_faces.append((name, face_locations[i]))
- print(f" -> Matched as {name}")
- else:
- print(" -> No good match.")
- return found_faces
- def draw_annotation(self, frame, name, position):
- (top, right, bottom, left) = map(lambda x: 4 * x, position)
- cv2.rectangle(frame, (left, top), (right, bottom + 35), self.color_border , 2)
- cv2.rectangle(frame, (left, bottom), (right, bottom + 35), self.color_border , -1)
- cv2.putText(frame, name, (left + 6, bottom + 35 - 6), cv2.FONT_HERSHEY_DUPLEX, 0.8, self.color_text, 1)
- return frame
- def run_recognition(self, video_file):
- video_file_path = os.path.abspath(video_file)
- if not os.path.exists(video_file_path):
- raise FileNotFoundError(f"Video file not found: {video_file_path}")
- video_capture = cv2.VideoCapture(video_file_path)
- if not video_capture.isOpened():
- raise RuntimeError(f"Unable to read file: {video_file_path}")
- try:
- frame_number = -1
- while True:
- frame_number += 1
- ret, frame = video_capture.read()
- if not ret:
- print("Video capture completed. Exiting...")
- break
- if self.process_current_frame:
- print(f"Frame #{frame_number} -- ", end="")
- small_frame = cv2.resize(frame, None, fx=self.process_scale, fy=self.process_scale)
- rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
- found_faces = self.process_frame(rgb_small_frame)
- for name, position in found_faces:
- print(f"* Marking attendance for {name}")
- self.mark_attendance(name)
- self.draw_annotation(frame, name, position)
- # self.process_current_frame = not self.process_current_frame
- cv2.putText(frame, f"Frame {frame_number}", (10, 40), cv2.FONT_HERSHEY_DUPLEX, 1.0, self.color_text, 1)
- cv2.imshow("Face Recognition", frame)
- if cv2.waitKey(1) == ord('q'):
- break
- except Exception as e:
- print("An error occurred. Full backtrace:")
- traceback.print_exc()
- finally:
- video_capture.release()
- cv2.destroyAllWindows()
- if __name__ == "__main__":
- video_file_path = 'video.mp4'
- fr = FaceRecognition()
- fr.run_recognition(video_file_path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement