Skip to content

Commit 2f2d42c

Browse files
committed
add facial recognition system tutorial
1 parent 7e80569 commit 2f2d42c

14 files changed

+274
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
9898
- [How to Upscale Images using Stable Diffusion in Python](https://www.thepythoncode.com/article/upscale-images-using-stable-diffusion-x4-upscaler-huggingface). ([code](machine-learning/stable-diffusion-upscaler))
9999
- [Real-Time Vehicle Detection, Tracking and Counting in Python](https://thepythoncode.com/article/real-time-vehicle-tracking-and-counting-with-yolov8-opencv). ([code](https://github.com/python-dontrepeatyourself/Real-Time-Vehicle-Detection-Tracking-and-Counting-in-Python/))
100100
- [How to Cartoonify Images in Python](https://thepythoncode.com/article/make-a-cartoonifier-with-opencv-in-python). ([code](machine-learning/cartoonify-images))
101+
- [How to Make a Facial Recognition System in Python](https://thepythoncode.com/article/create-a-facial-recognition-system-in-python). ([code](machine-learning/facial-recognition-system))
101102
- [Building a Speech Emotion Recognizer using Scikit-learn](https://www.thepythoncode.com/article/building-a-speech-emotion-recognizer-using-sklearn). ([code](machine-learning/speech-emotion-recognition))
102103
- [How to Convert Speech to Text in Python](https://www.thepythoncode.com/article/using-speech-recognition-to-convert-speech-to-text-python). ([code](machine-learning/speech-recognition))
103104
- [Top 8 Python Libraries For Data Scientists and Machine Learning Engineers](https://www.thepythoncode.com/article/top-python-libraries-for-data-scientists).
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# [How to Make a Facial Recognition System in Python](https://thepythoncode.com/article/create-a-facial-recognition-system-in-python)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import cv2, numpy as np, face_recognition, os, tkinter as tk
2+
from tkinter import filedialog
3+
4+
# Initialize empty lists to store images and people's names.
5+
known_faces = []
6+
face_labels = []
7+
8+
# Get a list of all images in the TrainingImages directory.
9+
image_files = os.listdir("TrainingImages")
10+
11+
# Loop through the images in the directory.
12+
for image_name in image_files:
13+
# Read each image and add it to the known_faces list.
14+
current_image = cv2.imread(f'TrainingImages/{image_name}')
15+
known_faces.append(current_image)
16+
17+
# Extract the person's name by removing the file extension and add it to the face_labels list.
18+
face_labels.append(os.path.splitext(image_name)[0])
19+
20+
21+
# Function to get face encodings from a list of images.
22+
def get_face_encodings(images):
23+
encoding_list = []
24+
for image in images:
25+
# Convert the image to RGB format. RGB is Red Green Blue.
26+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
27+
# Get the face encoding for the first face found in the image.
28+
face_encoding = face_recognition.face_encodings(image)[0]
29+
encoding_list.append(face_encoding)
30+
return encoding_list
31+
32+
33+
# Get face encodings for known images.
34+
known_face_encodings = get_face_encodings(known_faces)
35+
36+
37+
# Function to handle image selection and recognition
38+
def select_and_recognize_image():
39+
# Use a file dialog to let the user select an image.
40+
selected_file = filedialog.askopenfilename()
41+
if selected_file:
42+
# Read the selected image.
43+
selected_image = cv2.imread(selected_file)
44+
45+
# Convert the image to RGB format.
46+
selected_image_rgb = cv2.cvtColor(selected_image, cv2.COLOR_BGR2RGB)
47+
48+
# Get face encodings for the selected image.
49+
selected_face_encodings = face_recognition.face_encodings(selected_image_rgb)
50+
51+
match_found = False # Flag to track if a match is found.
52+
53+
if not selected_face_encodings:
54+
print("No faces found in the selected image.")
55+
else:
56+
# Loop through the detected faces in the selected image.
57+
for face_encoding in selected_face_encodings:
58+
# Compare the current face encoding with the known encodings.
59+
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
60+
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
61+
62+
# Find the index of the best match. That is, the best resemblance.
63+
best_match_index = np.argmin(face_distances)
64+
65+
if matches[best_match_index]:
66+
# If a match is found, get the name of the recognized person.
67+
recognized_name = face_labels[best_match_index].upper()
68+
69+
# Draw a green rectangle around the recognized face.
70+
top, right, bottom, left = face_recognition.face_locations(selected_image_rgb)[0]
71+
cv2.rectangle(selected_image, (left, top), (right, bottom), (0, 255, 0), 2,)
72+
73+
# Display the name below the face.
74+
cv2.putText(selected_image, recognized_name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_COMPLEX, 0.5,
75+
(0, 255, 0), 2)
76+
77+
match_found = True # Match found flag.
78+
break # Exit loop as soon as a match is found.
79+
80+
if not match_found:
81+
# If no match is found, draw a red rectangle and display No Match.
82+
top, right, bottom, left = face_recognition.face_locations(selected_image_rgb)[0]
83+
cv2.rectangle(selected_image, (left, top), (right, bottom), (0, 0, 255), 2)
84+
cv2.putText(selected_image, "No match", (left + 6, bottom - 6), cv2.FONT_HERSHEY_COMPLEX, 1,
85+
(0, 0, 255), 2)
86+
87+
# Show the image with the rectangle and name.
88+
cv2.imshow("Recognized Image", selected_image)
89+
known_faces.clear()# To prevent the program from slowing down due to excess unnecessary encodings.
90+
cv2.waitKey(0)
91+
cv2.destroyAllWindows()
92+
93+
94+
# Create the main application window.
95+
root = tk.Tk()
96+
root.title("Face Recognition Program")
97+
98+
# Create a button to select an image for recognition.
99+
select_button = tk.Button(root, text="Select Image for Recognition", command=select_and_recognize_image)
100+
select_button.pack(pady=10)
101+
102+
103+
# Function to quit the application.
104+
def quit_app():
105+
root.quit()
106+
107+
108+
# Create a quit button to exit the application.
109+
quit_button = tk.Button(root, text="Quit", command=quit_app)
110+
quit_button.pack(pady=10)
111+
112+
# Start the Tkinter event loop.
113+
root.mainloop()
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import tkinter as tk, numpy as np, cv2, os, face_recognition
2+
from datetime import datetime
3+
4+
# Initialize empty lists to store images and people's names.
5+
known_faces = []
6+
face_labels = []
7+
8+
# Get a list of all images in the TrainingImages directory.
9+
image_files = os.listdir("TrainingImages")
10+
11+
# Loop through the images in the directory.
12+
for image_name in image_files:
13+
# Read each image and add it to the known_faces list.
14+
current_image = cv2.imread(f'TrainingImages/{image_name}')
15+
known_faces.append(current_image)
16+
17+
# Extract the person's name by removing the file extension and add it to the face_labels list.
18+
face_labels.append(os.path.splitext(image_name)[0])
19+
20+
21+
# Function to get face encodings from a list of images.
22+
def get_face_encodings(images):
23+
encoding_list = []
24+
for image in images:
25+
# Convert the image to RGB format. RGB is Red Green Blue.
26+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
27+
# Get the face encoding for the first face found in the image.
28+
face_encoding = face_recognition.face_encodings(image)[0]
29+
encoding_list.append(face_encoding)
30+
return encoding_list
31+
32+
33+
# Define a function to document the recognized face.
34+
def document_recognised_face(name, filename='records.csv'):
35+
# Get the current date in the YYYY-MM-DD format.
36+
capture_date = datetime.now().strftime("%Y-%m-%d")
37+
38+
# Check if the specified CSV file exists.
39+
if not os.path.isfile(filename):
40+
# If the file doesn't exist, create it and write the header.
41+
with open(filename, 'w') as f:
42+
f.write('Name,Date,Time') # Create the file and write the header.
43+
44+
# Open the CSV file for reading and writing ('r+')
45+
with open(filename, 'r+') as file:
46+
# Read all lines from the file into a list.
47+
lines = file.readlines()
48+
49+
# Extract the names from existing lines in the CSV.
50+
existing_names = [line.split(",")[0] for line in lines]
51+
52+
# Check if the provided name is not already in the existing names.
53+
if name not in existing_names:
54+
# Get the current time in the HH:MM:SS format.
55+
now = datetime.now()
56+
current_time = now.strftime("%H:%M:%S")
57+
58+
# Write the new entry to the CSV file including name, capture date, and time.
59+
file.write(f'\n{name},{capture_date},{current_time}')
60+
61+
62+
# Get face encodings for known images.
63+
known_face_encodings = get_face_encodings(known_faces)
64+
65+
66+
# Function to start the Facial recognition program.
67+
def start_recognition_program():
68+
# Open a webcam for capturing video. If you are using your computer's webcam, change 1 to 0.
69+
# If using an external webcam, leave it as 1.
70+
video_capture = cv2.VideoCapture(1)
71+
72+
while True:
73+
# Read a frame from the webcam.
74+
frame = video_capture.read()
75+
76+
# Check if the frame is not None (indicating a successful frame capture).
77+
if frame is not None:
78+
frame = frame[1] # The frame is usually the second element of the tuple returned by video_capture.read().
79+
80+
# Resize the image to a smaller size.
81+
resized_frame = cv2.resize(frame, (0, 0), None, 0.25, 0.25)
82+
resized_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB)
83+
84+
# Detect faces in the current frame.
85+
face_locations = face_recognition.face_locations(resized_frame)
86+
87+
# Get face encodings for the faces detected in the current frame.
88+
current_face_encodings = face_recognition.face_encodings(resized_frame, face_locations)
89+
90+
# Loop through the detected faces in the current frame.
91+
for face_encoding, location in zip(current_face_encodings, face_locations):
92+
# Compare the current face encoding with the known encodings.
93+
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
94+
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
95+
96+
# Find the index of the best match. That is, the best resemblance.
97+
best_match_index = np.argmin(face_distances)
98+
99+
if matches[best_match_index]:
100+
# If a match is found, get the name of the recognized person.
101+
recognized_name = face_labels[best_match_index].upper()
102+
103+
# Extract face location coordinates.
104+
top, right, bottom, left = location
105+
top, right, bottom, left = top * 4, right * 4, bottom * 4, left * 4
106+
107+
# Draw a rectangle around the recognized face.
108+
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
109+
110+
# Draw a filled rectangle and display the name above the face.
111+
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
112+
cv2.putText(frame, recognized_name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_COMPLEX, 1,
113+
(255, 255, 255), 2)
114+
document_recognised_face(recognized_name)
115+
116+
# Display the image with recognized faces.
117+
cv2.imshow("Webcam", frame)
118+
119+
# Check for key press
120+
key = cv2.waitKey(1) & 0xFF
121+
122+
# Check if the 'q' key is pressed to exit the program.
123+
if key == ord('q'):
124+
break
125+
126+
# Release the video capture and close all OpenCV windows.
127+
video_capture.release()
128+
cv2.destroyAllWindows()
129+
130+
131+
# Create the main application window.
132+
root = tk.Tk()
133+
root.title("Face Recognition Program")
134+
135+
# Create a label
136+
label = tk.Label(root, text="Click the button to start the facial recognition program")
137+
label.pack(pady=10)
138+
139+
# Create a button to start the program
140+
start_button = tk.Button(root, text="Start Recognition", command=start_recognition_program)
141+
start_button.pack(pady=10)
142+
143+
144+
# Function to quit the application. This is for quitting the entire program. To quit the webcam stream, hit q.
145+
def quit_app():
146+
root.quit()
147+
cv2.destroyAllWindows()
148+
149+
150+
# Create a quit button to exit the application.
151+
exit_button = tk.Button(root, text="Close", command=quit_app)
152+
exit_button.pack(pady=10)
153+
154+
# Start the Tkinter event loop.
155+
root.mainloop()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
cmake
2+
dlib==19.18.0
3+
face-recognition
4+
opencv-python

0 commit comments

Comments
 (0)