Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Face Recognition System project #104

Merged
merged 5 commits into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Computer Vision/smart_attendance_system/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
cmake-3.30.3-windows-x86_64
*.csv
yolov8
runs
myenv
5 changes: 5 additions & 0 deletions Computer Vision/smart_attendance_system/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Steps to run the project:

1) Create a virtual environment.
2) Before installing the requirements, install dlib separately using `pip install "dlib_file_path"`
3) Install the requirements using `pip install -r requirements.txt`
Binary file not shown.
88 changes: 88 additions & 0 deletions Computer Vision/smart_attendance_system/face_rec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import face_recognition
import cv2
import numpy as np
import csv
import os
import streamlit as st
from datetime import datetime
from ultralytics import YOLO

# Load YOLO model
yolo_model = YOLO("yolov8/yolov8n-face.pt")

# Load and encode images
image_dir = "photos/"
encodings = {}
known_face_names = []

for fname in os.listdir(image_dir):
file_path = os.path.join(image_dir, fname)
image = face_recognition.load_image_file(file_path)
encoding = face_recognition.face_encodings(image)
if encoding:
encodings[fname] = encoding[0]
known_face_names.append(fname.split('.')[0]) # Assuming the names are derived from file names

# Known face encodings and names
known_face_encodings = list(encodings.values())
known_face_names = [name.split('.')[0] for name in encodings.keys()]

# Streamlit app
st.title("Face Recognition Attendance System")
uploaded_image = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])

if uploaded_image is not None:
# Read and process the uploaded image
img = face_recognition.load_image_file(uploaded_image)

# Create or open a CSV file for the current date
now = datetime.now()
current_date = now.strftime("%Y-%m-%d")
attendance_file = current_date + '.csv'

# Initialize students list
students = known_face_names.copy()
attendance_records = [] # Store attendance records

# Get YOLO results
yolo_results = yolo_model(img)
yolo_boxes = yolo_results[0].boxes

# Find face locations and encodings for detected faces
face_locations = face_recognition.face_locations(img)
face_encodings = face_recognition.face_encodings(img, face_locations)

face_names = [] # List to hold names for all detected faces

for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown" # Default to "Unknown" for unmatched faces

if True in matches: # If there is a match
best_match_index = np.argmin(face_recognition.face_distance(known_face_encodings, face_encoding))
name = known_face_names[best_match_index] # Get the name of the matched face

# Attendance tracking
if name in students:
students.remove(name)
# Record attendance in the list
attendance_records.append([name, 'present'])
face_names.append(name) # Append the name to the list (either known or "Unknown")

# Draw rectangles and labels for all detected faces
for (top, right, bottom, left), name in zip(face_locations, face_names):
cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(img, name, (left, bottom + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)

# Display the image in Streamlit
st.image(img, caption='Processed Image', channels="RGB")

# Write to CSV
with open(attendance_file, 'w', newline='') as f:
lnwriter = csv.writer(f)
lnwriter.writerow(["Name", "Status"]) # Write header
# Write present records
lnwriter.writerows(attendance_records)
# Write absent students
for name in students:
lnwriter.writerow([name, 'absent'])
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
72 changes: 72 additions & 0 deletions Computer Vision/smart_attendance_system/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
altair==5.4.1
antlr4-python3-runtime==4.9.3
attrs==24.2.0
blinker==1.8.2
cachetools==5.5.0
certifi==2024.8.30
charset-normalizer==3.3.2
click==8.1.7
cmake==3.30.4
colorama==0.4.6
contourpy==1.3.0
cycler==0.12.1
dill==0.3.9
dlib @ file:///C:/Users/aniru/Documents/Projects/gssoc_ext_2024/ML-Nexus/Computer%20Vision/smart_attendance_system/dlib-19.24.99-cp312-cp312-win_amd64.whl#sha256=20c62e606ca4c9961305f7be3d03990380d3e6c17f8d27798996e97a73271862
face-recognition==1.3.0
face_recognition_models==0.3.0
filelock==3.16.1
fonttools==4.54.1
fsspec==2024.9.0
gitdb==4.0.11
GitPython==3.1.43
idna==3.10
Jinja2==3.1.4
jsonschema==4.23.0
jsonschema-specifications==2023.12.1
kiwisolver==1.4.7
markdown-it-py==3.0.0
MarkupSafe==2.1.5
matplotlib==3.9.2
mdurl==0.1.2
mpmath==1.3.0
narwhals==1.9.1
networkx==3.3
numpy==1.26.4
omegaconf==2.3.0
opencv-python==4.10.0.84
packaging==24.1
pandas==2.2.3
pillow==10.4.0
protobuf==5.28.2
psutil==6.0.0
py-cpuinfo==9.0.0
pyarrow==17.0.0
pydeck==0.9.1
Pygments==2.18.0
pyparsing==3.1.4
python-dateutil==2.9.0.post0
pytz==2024.2
PyYAML==6.0.2
referencing==0.35.1
requests==2.32.3
rich==13.9.2
rpds-py==0.20.0
scipy==1.14.1
seaborn==0.13.2
setuptools==75.1.0
six==1.16.0
smmap==5.0.1
streamlit==1.39.0
sympy==1.13.3
tenacity==9.0.0
toml==0.10.2
torch==2.4.1
torchvision==0.19.1
tornado==6.4.1
tqdm==4.66.5
typing_extensions==4.12.2
tzdata==2024.2
ultralytics==8.3.5
ultralytics-thop==2.0.9
urllib3==2.2.3
watchdog==5.0.3
120 changes: 120 additions & 0 deletions Computer Vision/smart_attendance_system/smart_attendance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import face_recognition
import cv2
import numpy as np
import csv
from datetime import datetime
import os
from ultralytics import YOLO

# Load YOLO model
yolo_model = YOLO("yolov8/yolov8n-face.pt")

# Start video capture
video_capture = cv2.VideoCapture(0)

# Load and encode images
image_dir = "photos/"
encodings = {}
known_face_names = []

for fname in os.listdir(image_dir):
file_path = os.path.join(image_dir, fname)
image = face_recognition.load_image_file(file_path)
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
encoding = face_recognition.face_encodings(img)
if encoding:
encodings[fname] = encoding[0]
known_face_names.append(fname.split('.')[0]) # Assuming the names are derived from file names

# Known face encodings and names
known_face_encodings = list(encodings.values())
known_face_names = [name.split('.')[0] for name in encodings.keys()]

students = known_face_names.copy()

face_locations = []
face_encodings = []
face_names = []
s = True

now = datetime.now()
current_date = now.strftime("%Y-%m-%d")

# Create or open a CSV file for the current date
with open(current_date + '.csv', 'w+', newline='') as f:
lnwriter = csv.writer(f)

while True:
ret, frame = video_capture.read()
if not ret:
break

small_frame = cv2.resize(frame, (0, 0), fx=1, fy=1)
rgb_small_frame = np.ascontiguousarray(small_frame[:, :, ::-1])

# Get YOLO results
yolo_results = yolo_model(rgb_small_frame)
yolo_boxes = yolo_results[0].boxes

# Draw rectangles for YOLO-detected faces
for box in yolo_boxes:
top_left_x, top_left_y = int(box.xyxy.tolist()[0][0]), int(box.xyxy.tolist()[0][1])
bottom_right_x, bottom_right_y = int(box.xyxy.tolist()[0][2]), int(box.xyxy.tolist()[0][3])
cv2.rectangle(frame, (top_left_x, top_left_y), (bottom_right_x, bottom_right_y), (50, 200, 129), 2)

if s:
face_locations = face_recognition.face_locations(rgb_small_frame)
if face_locations:
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = ""
face_distance = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distance)
if matches[best_match_index]:
name = known_face_names[best_match_index]

face_names.append(name)

# Display the name on the frame
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10, 50)
fontScale = 1.5
fontColor = (0, 255, 0)
thickness = 3
lineType = 2

if name in known_face_names:
cv2.putText(frame, name + ' present',
bottomLeftCornerOfText,
font,
fontScale,
fontColor,
thickness,
lineType)

if name in students:
students.remove(name)
print(students)
lnwriter.writerow([name, 'present'])
else:
cv2.putText(frame, 'unknown',
bottomLeftCornerOfText,
font,
fontScale,
fontColor,
thickness,
lineType)

cv2.imshow("Attendance System", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# Write absent students to CSV
for name in students:
lnwriter.writerow([name, 'absent'])

# Release video capture and close windows
video_capture.release()
cv2.destroyAllWindows()
Loading