🧩 1. Overview
We’ll build a simple system that:
- Detects faces in real time via webcam.
- Recognizes known faces (based on stored images).
- Runs 100% offline, using your computer’s camera and CPU (no cloud needed).
🧰 2. Tools You’ll Need (All Free)
| Library | Purpose | Offline? |
|---|---|---|
opencv-python |
Webcam + video processing | ✅ |
face_recognition |
Facial detection & encoding | ✅ |
numpy |
Math operations | ✅ |
🔧 Install dependencies:
Make sure Python ≥ 3.8 is installed, then run:
pip install opencv-python face_recognition numpy
⚠️ Note: On Windows, if
face_recognitiongives a build error, install:pip install cmake dlib pip install face_recognition
📸 3. Folder Setup
Create a project folder like this:
face_recognition_app/
│
├── known_faces/
│ ├── alice.jpg
│ ├── bob.jpg
│
└── face_recognition_live.py
Each image in known_faces/ is a person you want to recognize.
The filename (e.g. alice.jpg) becomes the person’s name.
💻 4. Full Python Code: face_recognition_live.py
import cv2
import face_recognition
import os
import numpy as np
# -----------------------------
# Load known faces
# -----------------------------
known_faces = []
known_names = []
print("📸 Loading known faces...")
for filename in os.listdir("known_faces"):
if filename.endswith(".jpg") or filename.endswith(".png"):
path = os.path.join("known_faces", filename)
image = face_recognition.load_image_file(path)
encoding = face_recognition.face_encodings(image)[0]
known_faces.append(encoding)
known_names.append(os.path.splitext(filename)[0])
print(f"✅ Loaded {len(known_faces)} known faces.")
# -----------------------------
# Start webcam
# -----------------------------
video_capture = cv2.VideoCapture(0)
print("🎥 Starting camera... Press 'q' to quit.")
while True:
ret, frame = video_capture.read()
if not ret:
print("⚠️ Failed to grab frame.")
break
# Resize frame for faster processing
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
# Detect faces
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_faces, face_encoding)
name = "Unknown"
face_distances = face_recognition.face_distance(known_faces, face_encoding)
if len(face_distances) > 0:
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_names[best_match_index]
# Scale back up face locations
top *= 4
right *= 4
bottom *= 4
left *= 4
# Draw box and label
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
cv2.putText(frame, name, (left + 6, bottom - 6),
cv2.FONT_HERSHEY_DUPLEX, 0.9, (0, 0, 0), 2)
# Display
cv2.imshow('Local Face Recognition', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
▶️ 5. Run It
python face_recognition_live.py
You’ll see a live webcam window showing:
- Green boxes around detected faces.
- Labels with the person’s name (if recognized).
- “Unknown” for strangers.
Press q to quit anytime.
🧠 6. How It Works
| Step | Description |
|---|---|
| 1️⃣ | Load known images and compute 128-dimension face encodings |
| 2️⃣ | Capture webcam frames and detect faces |
| 3️⃣ | Compare new face encodings to known ones |
| 4️⃣ | Label the face if it matches closely |
All this happens locally, using HOG + CNN algorithms inside dlib, embedded in face_recognition.
⚙️ 7. Optional: Add New Faces Automatically
You can add new people dynamically by saving new face images:
cv2.imwrite(f"known_faces/{new_name}.jpg", frame)
Then rerun the script to include the new person.
🧩 8. Optional: Faster or GPU Mode
For smoother real-time results:
- On NVIDIA GPU, install CUDA version of
dlib. - For lower-end CPUs, use smaller frame scaling (
fx=fy=0.2).
🔒 9. Privacy & Local Benefits
✅ Runs 100% offline
✅ No data leaves your machine
✅ No API keys or subscriptions
✅ Fully customizable (you own the data)
🧱 10. Project Ideas to Extend It
- 🧍♂️ Attendance system — mark who appeared.
- 🚪 Smart door camera — open only for recognized faces.
- 🧩 Multimodal AI — connect with your voice detection or local agent from before.
Example integration:
if name == "Alice":
print("Welcome back, Alice!")
subprocess.run(["python", "local_agent.py"])
🚀 Summary
✅ Offline, real-time facial detection & recognition
✅ Built with Python + OpenCV + face_recognition
✅ No cost, no internet, and privacy-safe