Face Recognise
@amitmund
June 26, 2026
capture_faces.py
import cv2
import os
import pyttsx3
import time
# -----------------------
# USER NAME
# -----------------------
person_name = input("Enter person name: ")
save_path = f"dataset/{person_name}"
os.makedirs(save_path, exist_ok=True)
# -----------------------
# CREATE VOICE FILE
# -----------------------
engine = pyttsx3.init()
engine.save_to_file(f"Welcome {person_name}", f"Welcome_{person_name}.mp3")
engine.runAndWait()
# -----------------------
# CAMERA + FACE DETECTOR
# -----------------------
face_detector = cv2.CascadeClassifier(
cv2.data.haarcascades +
"haarcascade_frontalface_default.xml"
)
cap = cv2.VideoCapture(0)
# Flip camera like selfie mode (IMPORTANT)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
# -----------------------
# ENROLLMENT SETTINGS
# -----------------------
total_images = 70
count = 0
instructions = [
"LOOK STRAIGHT",
"TURN LEFT",
"TURN RIGHT",
"LOOK UP",
"LOOK DOWN",
"MOVE CLOSER",
"MOVE BACK"
]
step = 0
images_per_step = total_images // len(instructions)
print("Starting Face Enrollment...")
while True:
ret, frame = cap.read()
if not ret:
print("Camera error")
break
# MIRROR EFFECT (IMPORTANT for user experience)
frame = cv2.flip(frame, 1)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, 1.3, 5)
# -----------------------
# UI OVERLAY
# -----------------------
cv2.putText(frame, f"Name: {person_name}", (20, 40),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
cv2.putText(frame, f"Instruction: {instructions[step]}", (20, 80),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
cv2.putText(frame, f"Captured: {count}/{total_images}", (20, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.putText(frame, "Press Q to quit", (20, 160),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# -----------------------
# FACE DETECTION + SAVE
# -----------------------
for (x, y, w, h) in faces:
# draw face box
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
face = gray[y:y+h, x:x+w]
if count < total_images:
face = cv2.resize(face, (200, 200))
cv2.imwrite(f"{save_path}/{count}.jpg", face)
count += 1
# -----------------------
# STEP CHANGE LOGIC
# -----------------------
if count > 0 and count % images_per_step == 0:
if step < len(instructions) - 1:
step += 1
time.sleep(0.8) # small pause for adjustment
# -----------------------
# SHOW CAMERA WINDOW
# -----------------------
cv2.imshow("Face Registration (FaceID Style)", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q') or count >= total_images:
break
cap.release()
cv2.destroyAllWindows()
print("Registration Completed Successfully")
train_model.py
import cv2
import os
import numpy as np
# -----------------------
# DATASET PATH
# -----------------------
dataset_path = "dataset"
faces = []
labels = []
label_map = {}
current_id = 0
print("Starting training...")
# -----------------------
# LOOP THROUGH PEOPLE
# -----------------------
for person_name in os.listdir(dataset_path):
person_path = os.path.join(dataset_path, person_name)
if not os.path.isdir(person_path):
continue
label_map[current_id] = person_name
image_count = 0
# -----------------------
# LOOP THROUGH IMAGES
# -----------------------
for image_name in os.listdir(person_path):
image_path = os.path.join(person_path, image_name)
# read image in grayscale
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
print(f"Skipping invalid file: {image_path}")
continue
# normalize size (IMPORTANT for accuracy)
image = cv2.resize(image, (200, 200))
faces.append(image)
labels.append(current_id)
image_count += 1
print(f"Loaded {image_count} images for {person_name}")
current_id += 1
# -----------------------
# VALIDATION CHECK
# -----------------------
if len(faces) == 0:
print("ERROR: No valid training data found!")
exit()
labels = np.array(labels)
# -----------------------
# TRAIN MODEL
# -----------------------
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces, labels)
recognizer.save("trainer.yml")
print("\nTraining completed successfully!")
# -----------------------
# SAVE LABEL MAP
# -----------------------
with open("labels.txt", "w") as f:
for id, name in label_map.items():
f.write(f"{id},{name}\n")
print("Labels saved to labels.txt")
print("\nFinal label mapping:")
print(label_map)
import cv2
from pygame import mixer
import time
import os
from collections import deque
# -----------------------
# AUDIO INIT
# -----------------------
mixer.init()
# -----------------------
# LABELS
# -----------------------
label_map = {}
with open("labels.txt", "r") as f:
for line in f:
id, name = line.strip().split(",")
label_map[int(id)] = name
# -----------------------
# AUDIO MAP
# -----------------------
audio_map = {}
for name in label_map.values():
file = f"Welcome_{name}.mp3"
if os.path.exists(file):
audio_map[name] = mixer.Sound(file)
unknown_sound = mixer.Sound("Unknown_Human_Face.mp3")
# -----------------------
# TRAINER + DETECTOR
# -----------------------
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainer.yml")
face_detector = cv2.CascadeClassifier(
cv2.data.haarcascades +
"haarcascade_frontalface_default.xml"
)
cap = cv2.VideoCapture(0)
# -----------------------
# CCTV STATE SYSTEM
# -----------------------
face_buffer = deque(maxlen=7)
tracked_people = {} # MAIN CCTV STATE
LEAVE_TIMEOUT = 2.5 # seconds
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, 1.3, 5)
current_time = time.time()
current_frame_people = set()
# -----------------------
# PROCESS FACES
# -----------------------
for (x, y, w, h) in faces:
face = cv2.resize(gray[y:y+h, x:x+w], (200, 200))
id, confidence = recognizer.predict(face)
if confidence < 60 and id in label_map:
name = label_map[id]
else:
name = "Unknown"
current_frame_people.add(name)
# -----------------------
# BUFFER STABILITY
# -----------------------
face_buffer.append(name)
stable_name = max(set(face_buffer), key=face_buffer.count)
# -----------------------
# INIT PERSON STATE
# -----------------------
if stable_name not in tracked_people:
tracked_people[stable_name] = {
"seen": False,
"last_seen": 0,
"greeted": False
}
person = tracked_people[stable_name]
person["last_seen"] = current_time
# -----------------------
# ENTRY EVENT (ONLY ONCE)
# -----------------------
if not person["greeted"]:
if stable_name != "Unknown":
if stable_name in audio_map:
audio_map[stable_name].play()
else:
unknown_sound.play()
person["greeted"] = True
person["seen"] = True
# -----------------------
# DRAW UI
# -----------------------
if stable_name != "Unknown":
color = (0, 255, 0)
else:
color = (0, 0, 255)
cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
cv2.putText(frame, stable_name, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
# -----------------------
# EXIT (LEAVE DETECTION)
# -----------------------
for name in list(tracked_people.keys()):
if name not in current_frame_people:
if current_time - tracked_people[name]["last_seen"] > LEAVE_TIMEOUT:
# RESET ON EXIT (VERY IMPORTANT)
tracked_people[name]["greeted"] = False
tracked_people[name]["seen"] = False
cv2.imshow("CCTV Identity Lock System", frame)
if cv2.waitKey(1) & 0xFF in [ord('q'), 27]:
break
cap.release()
cv2.destroyAllWindows()