Note - Double Click to Copy Code Contact Us!
Posts

Driver Drowsiness Detection

Tech Doubility
Driver Drowsiness Detection


  1. import cv2
  2. import dlib
  3. from scipy.spatial import distance
  4.  
  5. # Function to calculate the eye aspect ratio (EAR)
  6. def eye_aspect_ratio(eye):
  7. A = distance.euclidean(eye[1], eye[5])
  8. B = distance.euclidean(eye[2], eye[4])
  9. C = distance.euclidean(eye[0], eye[3])
  10. ear = (A + B) / (2.0 * C)
  11. return ear
  12.  
  13. # Constants for drowsiness detection
  14. EAR_THRESHOLD = 0.25 # Eye aspect ratio threshold for drowsiness detection
  15. CONSECUTIVE_FRAMES = 20 # Number of consecutive frames for drowsiness detection
  16.  
  17. # Load face detector and facial landmark predictor
  18. detector = dlib.get_frontal_face_detector()
  19. predictor = dlib.shape_predictor('path_to_shape_predictor_68_face_landmarks.dat')
  20.  
  21. # Load the video capture
  22. video_capture = cv2.VideoCapture(0) # Use 0 for webcam
  23.  
  24. # Initialize variables
  25. frame_counter = 0
  26. drowsy_frames = 0
  27. alert = False
  28.  
  29. while True:
  30. ret, frame = video_capture.read()
  31. if not ret:
  32. break
  33.  
  34. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  35.  
  36. # Detect faces in the grayscale frame
  37. faces = detector(gray)
  38.  
  39. for face in faces:
  40. shape = predictor(gray, face)
  41. shape = face_utils.shape_to_np(shape)
  42.  
  43. # Extract eye coordinates
  44. left_eye = shape[36:42]
  45. right_eye = shape[42:48]
  46.  
  47. # Calculate eye aspect ratios
  48. left_ear = eye_aspect_ratio(left_eye)
  49. right_ear = eye_aspect_ratio(right_eye)
  50.  
  51. # Average the eye aspect ratios for both eyes
  52. avg_ear = (left_ear + right_ear) / 2.0
  53.  
  54. # Check if the average eye aspect ratio is below the threshold
  55. if avg_ear < EAR_THRESHOLD:
  56. frame_counter += 1
  57. if frame_counter >= CONSECUTIVE_FRAMES:
  58. drowsy_frames += 1
  59. if not alert:
  60. alert = True
  61. print("Drowsiness detected!")
  62. else:
  63. frame_counter = 0
  64. alert = False
  65.  
  66. # Draw the computed eye aspect ratio on the frame
  67. cv2.putText(frame, "EAR: {:.2f}".format(avg_ear), (10, 30),
  68. cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  69.  
  70. cv2.imshow("Driver Drowsiness Detection", frame)
  71. if cv2.waitKey(1) & 0xFF == ord('q'):
  72. break
  73.  
  74. # Release the video capture and close the window
  75. video_capture.release()
  76. 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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.