Spaces:
Runtime error
Runtime error
| import streamlit as st | |
| import cv2 | |
| import numpy as np | |
| import face_recognition | |
| import os | |
| def load_known_faces(): | |
| known_faces = [] | |
| known_names = [] | |
| # Assuming you have a folder named "database" containing subfolders with student faces | |
| database_path = "database" | |
| for folder_name in os.listdir(database_path): | |
| folder_path = os.path.join(database_path, folder_name) | |
| if os.path.isdir(folder_path): | |
| for file_name in os.listdir(folder_path): | |
| file_path = os.path.join(folder_path, file_name) | |
| # Load the image and encode the face | |
| image = face_recognition.load_image_file(file_path) | |
| face_encoding = face_recognition.face_encodings(image)[0] | |
| known_faces.append(face_encoding) | |
| known_names.append(folder_name) | |
| return known_faces, known_names | |
| def detect_and_match_face(frame, known_faces, known_names): | |
| # Find faces in the frame | |
| face_locations = face_recognition.face_locations(frame) | |
| face_encodings = face_recognition.face_encodings(frame, face_locations) | |
| for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): | |
| # Check if the face matches any known faces | |
| matches = face_recognition.compare_faces(known_faces, face_encoding) | |
| name = "Unknown" | |
| # If a match is found, use the name of the first matching face | |
| if True in matches: | |
| first_match_index = matches.index(True) | |
| name = known_names[first_match_index] | |
| # Draw a rectangle around the face and display the name | |
| cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2) | |
| font = cv2.FONT_HERSHEY_DUPLEX | |
| cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1) | |
| return frame | |
| def main(): | |
| st.title("Face Recognition App") | |
| # Login system | |
| username = st.sidebar.text_input("Username") | |
| password = st.sidebar.text_input("Password", type="password") | |
| if username == "your_username" and password == "your_password": | |
| st.sidebar.success("Logged In") | |
| st.write("Welcome, {}".format(username)) | |
| known_faces, known_names = load_known_faces() | |
| # OpenCV webcam setup | |
| video_capture = cv2.VideoCapture(0) | |
| while True: | |
| # Read each frame from the webcam | |
| ret, frame = video_capture.read() | |
| # Detect and match faces in the frame | |
| frame_with_faces = detect_and_match_face(frame, known_faces, known_names) | |
| # Display the frame with faces | |
| st.image(frame_with_faces, channels="BGR", use_column_width=True) | |
| # Break the loop if the user clicks the 'Stop' button | |
| if st.button("Stop"): | |
| break | |
| # Release the webcam | |
| video_capture.release() | |
| else: | |
| st.sidebar.warning("Incorrect username or password") | |
| if __name__ == "__main__": | |
| main() | |