import cv2
import dlib
import numpy as np
import pygame
import os
from deepface import DeepFace
from scipy.spatial import distance
# Initialize alert sound
pygame.mixer.init()
alert_sound = pygame.mixer.Sound("alert.wav") # Ensure this file exists
# Load Dlib’s face detector & landmark predictor
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # Ensure this file exists
# Define eye landmarks
LEFT_EYE = [36, 37, 38, 39, 40, 41]
RIGHT_EYE = [42, 43, 44, 45, 46, 47]
# Load multiple authorized faces
authorized_faces_dir = "authorized_faces/"
authorized_faces = [os.path.join(authorized_faces_dir, img) for img in os.listdir(authorized_faces_dir) if img.endswith(('.jpg', '.png', '.jpeg'))]
if not authorized_faces:
print(" Error: No authorized face images found in 'authorized_faces/' directory!")
exit(1)
# Define camera matrix for head pose estimation
focal_length = 640
center = (320, 240)
camera_matrix = np.array([
[focal_length, 0, center[0]],
[0, focal_length, center[1]],
[0, 0, 1]
], dtype="double")
dist_coeffs = np.zeros((4,1)) # No lens distortion
# Thresholds
EAR_THRESHOLD = 0.25
DROWSY_FRAMES = 30
drowsy_counter = 0
verified = False
def calculate_EAR(eye):
A = distance.euclidean(eye[1], eye[5])
B = distance.euclidean(eye[2], eye[4])
C = distance.euclidean(eye[0], eye[3])
return (A + B) / (2.0 * C)
def verify_identity(temp_face_path):
for authorized_face in authorized_faces:
try:
result = DeepFace.verify(img1_path=temp_face_path, img2_path=authorized_face, model_name="VGG-Face", detector_backend="opencv", enforce_detection=False)
if result["verified"]:
print(f" Access Granted! Matched with: {os.path.basename(authorized_face)}")
return True
except Exception as e:
print(f" Error during verification: {str(e)}")
return False
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
for face in faces:
shape = predictor(gray, face)
landmarks = np.array([[p.x, p.y] for p in shape.parts()], dtype="double")
left_eye = landmarks[LEFT_EYE]
right_eye = landmarks[RIGHT_EYE]
avg_EAR = (calculate_EAR(left_eye) + calculate_EAR(right_eye)) / 2.0
if avg_EAR < EAR_THRESHOLD:
drowsy_counter += 1
if drowsy_counter >= DROWSY_FRAMES:
cv2.putText(frame, "DROWSY ALERT!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
alert_sound.play()
else:
drowsy_counter = 0
if not verified:
temp_face_path = "temp_face.jpg"
cv2.imwrite(temp_face_path, frame)
if verify_identity(temp_face_path):
verified = True
else:
print(" Access Denied! Face did not match any authorized users.")
exit(1)
os.remove(temp_face_path)
x, y, w, h = (face.left(), face.top(), face.width(), face.height())
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Driver Monitoring System", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
in this code importing lib are not avilable in the python 3.12