Face recognition has gone from sci-fi to daily reality — it’s used in phone unlocks, surveillance, and smart apps. Python makes it surprisingly easy to implement thanks to the powerful face_recognition
library.
This tutorial will walk you through everything you need to know: installation, detecting faces, recognizing people, and building a simple face recognition system — all using just a few lines of Python code.
What is face_recognition
?
face_recognition
is a Python library built on top of dlib and deep learning. It allows you to:
- Detect faces in images or video
- Recognize and identify faces
- Extract facial features and compare faces
- Label known people in photos
It’s known for being:
- Extremely accurate (based on deep learning)
- Very easy to use
- Open-source and actively maintained
Installation
First, make sure you’re using Python 3.6–3.11.
1. Install CMake (required for dlib)
pip install cmake
2. Install dlib and face_recognition
pip install dlib
pip install face_recognition
Note: On Windows, you might need to install Visual Studio Build Tools. On macOS, install
brew install cmake
.
📂 Prepare Your Images
Create a folder like:
face_project/
├── known/
│ ├── alice.jpg
│ └── bob.jpg
├── unknown/
│ └── test.jpg
- Place clear, front-facing images in
known/
- Place the test image in
unknown/
Basic Face Detection
import face_recognition
import cv2
image = face_recognition.load_image_file("unknown/test.jpg")
face_locations = face_recognition.face_locations(image)
print(f"Found {len(face_locations)} face(s) in the image.")
Basic Face Recognition (Compare Faces)
known_image = face_recognition.load_image_file("known/alice.jpg")
unknown_image = face_recognition.load_image_file("unknown/test.jpg")
alice_encoding = face_recognition.face_encodings(known_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
results = face_recognition.compare_faces([alice_encoding], unknown_encoding)
if results[0]:
print("This is Alice!")
else:
print("Not Alice.")
Identify Multiple People in a Photo
import os
known_encodings = []
known_names = []
for filename in os.listdir("known"):
image = face_recognition.load_image_file(f"known/{filename}")
encoding = face_recognition.face_encodings(image)[0]
known_encodings.append(encoding)
known_names.append(os.path.splitext(filename)[0])
# Load unknown image
image = face_recognition.load_image_file("unknown/test.jpg")
face_locations = face_recognition.face_locations(image)
face_encodings = face_recognition.face_encodings(image, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(known_encodings, face_encoding)
name = "Unknown"
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
print(f"Detected: {name}")
Real-Time Face Recognition with Webcam
import face_recognition
import cv2
# Load known face
known_image = face_recognition.load_image_file("known/alice.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
known_names = ["Alice"]
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces([known_encoding], face_encoding)
name = "Unknown"
if True in matches:
name = known_names[0]
# Scale back up
top *= 4; right *= 4; bottom *= 4; left *= 4
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
Tips for Better Accuracy
- Use high-resolution images for face encoding.
- Make sure the faces are front-facing and well-lit.
- For faster performance, resize frames to 1/4 scale (as shown above).
Advanced Features in face_recognition
Feature | Method |
---|---|
Get face landmarks | face_recognition.face_landmarks() |
Find facial features | Eyes, nose, lips, jaw |
Compare multiple faces | compare_faces() with multiple encodings |
Get face distances | face_recognition.face_distance() |
Troubleshooting
Problem | Solution |
---|---|
No faces found | Use clear, front-facing images |
IndexError on encoding | Ensure face_encodings() returns a result |
Slow webcam performance | Resize frame to 1/4 or use a GPU build of dlib |
What Can You Build with face_recognition
?
- Smart door lock using Raspberry Pi
- Attendance system for schools
- Face-sorting photo gallery
- Real-time face-based tagging for security cameras
Conclusion
The face_recognition
library makes face detection and recognition in Python extremely accessible, even for beginners. With just a few lines of code, you can build impressive, real-world projects that leverage computer vision.
You now know how to:
- Detect and identify faces in images and videos
- Compare faces with known profiles
- Build real-time face recognition with a webcam