Face Detection and Recognition System Source Code
Creating a face detection and recognition system involves using libraries like OpenCV for image processing and a machine learning model for face recognition. Below is a basic example using Python, OpenCV, and the face_recognition
library, which simplifies face recognition tasks.
Install Required Libraries
First, ensure you have Python installed on your computer. Then, install the necessary libraries:
pip install opencv-python
pip install face_recognition
pip install numpy
Set Up the Project Directory
Create a project directory with the following structure:
face-recognition-system/
├── encode_faces.py
├── recognize_faces.py
├── dataset/
│ ├── person1/
│ │ ├── image1.jpg
│ │ ├── image2.jpg
│ └── person2/
│ ├── image1.jpg
│ ├── image2.jpg
└── encodings.pickle
Encode Known Faces
Create an encode_faces.py
file to encode known faces: Copy and past the following code.
import face_recognition
import pickle
import cv2
import os
# Initialize the list of known encodings and known names
known_encodings = []
known_names = []
# Loop over the dataset
dataset_path = "dataset"
for person_name in os.listdir(dataset_path):
person_folder = os.path.join(dataset_path, person_name)
for image_name in os.listdir(person_folder):
image_path = os.path.join(person_folder, image_name)
print(f"Processing {image_path}")
# Load the image and convert it from BGR (OpenCV ordering) to RGB (face_recognition ordering)
image = cv2.imread(image_path)
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Detect the coordinates of the bounding boxes corresponding to each face in the input image
boxes = face_recognition.face_locations(rgb_image, model="hog")
# Compute the facial embedding for the face
encodings = face_recognition.face_encodings(rgb_image, boxes)
for encoding in encodings:
known_encodings.append(encoding)
known_names.append(person_name)
# Save the facial encodings + names to disk
data = {"encodings": known_encodings, "names": known_names}
with open("encodings.pickle", "wb") as f:
f.write(pickle.dumps(data))
Recognize Faces
Create a recognize_faces.py
file to recognize faces in real-time using a webcam: This machine might not always be 100% accurate.
import face_recognition
import pickle
import cv2
# Load the known faces and embeddings
with open("encodings.pickle", "rb") as f:
data = pickle.loads(f.read())
# Initialize the video stream and pointer to output video file
video_capture = cv2.VideoCapture(0)
while True:
# Grab a single frame of video
ret, frame = video_capture.read()
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
# Loop over each face found in the frame to see if it's someone we know
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(data["encodings"], face_encoding)
name = "Unknown"
face_distances = face_recognition.face_distance(data["encodings"], face_encoding)
best_match_index = face_distances.argmin()
if matches[best_match_index]:
name = data["names"][best_match_index]
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
# Draw a label with a name below the face
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)
# Display the resulting image
cv2.imshow('Video', frame)
# Hit 'q' on the keyboard to quit!
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()
Run the System
- Encode the faces:
bash python encode_faces.py
- Run the face recognition:
bash python recognize_faces.py
This project demonstrates a simple face detection and recognition system using Python, OpenCV, and the face_recognition
library. The system captures real-time video from a webcam, detects faces, and recognizes them based on a dataset of known faces.