import cv2 import dlib from scipy.spatial import distance # Function to calculate the eye aspect ratio (EAR) def eye_aspect_ratio(eye): A = distance.euclidean(eye[1], eye[5]) B = distance.euclidean(eye[2], eye[4]) C = distance.euclidean(eye[0], eye[3]) ear = (A + B) / (2.0 * C) return ear # Constants for drowsiness detection EAR_THRESHOLD = 0.25 # Eye aspect ratio threshold for drowsiness detection CONSECUTIVE_FRAMES = 20 # Number of consecutive frames for drowsiness detection # Load face detector and facial landmark predictor detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('path_to_shape_predictor_68_face_landmarks.dat') # Load the video capture video_capture = cv2.VideoCapture(0) # Use 0 for webcam # Initialize variables frame_counter = 0 drowsy_frames = 0 alert = False while True: ret, frame = video_capture.read() if not ret: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect faces in the grayscale frame faces = detector(gray) for face in faces: shape = predictor(gray, face) shape = face_utils.shape_to_np(shape) # Extract eye coordinates left_eye = shape[36:42] right_eye = shape[42:48] # Calculate eye aspect ratios left_ear = eye_aspect_ratio(left_eye) right_ear = eye_aspect_ratio(right_eye) # Average the eye aspect ratios for both eyes avg_ear = (left_ear + right_ear) / 2.0 # Check if the average eye aspect ratio is below the threshold if avg_ear < EAR_THRESHOLD: frame_counter += 1 if frame_counter >= CONSECUTIVE_FRAMES: drowsy_frames += 1 if not alert: alert = True print("Drowsiness detected!") else: frame_counter = 0 alert = False # Draw the computed eye aspect ratio on the frame cv2.putText(frame, "EAR: {:.2f}".format(avg_ear), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) cv2.imshow("Driver Drowsiness Detection", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the video capture and close the window video_capture.release() cv2.destroyAllWindows()
Note: Before running the code, make sure to download the "shape_predictor_68_face_landmarks.dat" file, which is the pre-trained model for facial landmark detection in dlib. You can download it from the following link: shape_predictor_68_face_landmarks.dat
Make sure to replace 'path_to_shape_predictor_68_face_landmarks.dat' with the actual path to the downloaded file on your system.
This code continuously captures video frames from a webcam, detects faces, and calculates the eye aspect ratio (EAR) to determine drowsiness. If the average EAR falls below a certain threshold for a specified number of consecutive frames, it triggers a drowsiness alert.
Feel free to modify and adapt the code to suit your specific requirements or integrate it into a larger system as needed.