Drowsiness Detection using Python OpenCV

In today's fast-paced world, road accidents due to driver drowsiness have become a major problem. The danger of accidents caused by drowsy driving can be reduced using modern technologies, including drowsiness detection using Python and OpenCV. When paired with OpenCV, a strong computer vision package, Python provides an effective method for detecting tiredness in drivers by monitoring facial features and identifying indicators of drowsiness, such as eye closures or head movements.

In this article, we will explore drowsiness detection using Python OpenCV. We'll look into methods for detecting eye closures and assessing blinking frequency. Additionally, we will discuss how to set up an alarm system to notify drivers as soon as drowsiness is identified.

Understanding Drowsiness Detection

Drowsiness detection involves monitoring the driver's facial expressions for signs of fatigue, such as prolonged eye closure or unusual head movements. This process is essential for ensuring driver safety and preventing potential accidents. Python and OpenCV provide a reliable and effective framework for developing drowsiness detection systems.

Python offers a large variety of libraries for image processing and computer vision tasks. OpenCV, a powerful computer vision library, provides comprehensive tools and algorithms for analyzing and processing visual input in real-time.

By utilizing Python and OpenCV, developers can access and modify video feeds from cameras or webcams, enabling real-time monitoring of the driver's facial features. This allows detection of subtle changes in eye closure or head movements that indicate drowsiness.

Detecting Eye Closures

Identifying eye closures is the initial step in detecting drowsiness. OpenCV provides several image processing algorithms to accomplish this objective. Haar cascades, for example, are capable of recognizing objects in images or videos ?

import cv2
import numpy as np

# Load the pre-trained Haar cascade classifier for eye detection
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

# Capture video feed from the webcam
cap = cv2.VideoCapture(0)

while True:
    # Read the current frame
    ret, frame = cap.read()
    
    if not ret:
        break
    
    # Convert the frame to grayscale for eye detection
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # Detect eyes in the grayscale frame
    eyes = eye_cascade.detectMultiScale(gray, 1.3, 5)
    
    for (x, y, w, h) in eyes:
        # Draw rectangles around the detected eyes
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    
    # Display the frame with eye rectangles
    cv2.imshow('Drowsiness Detection', frame)
    
    # Break loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture and close windows
cap.release()
cv2.destroyAllWindows()

This basic implementation detects eyes using Haar cascades and draws rectangles around them. When both eyes are closed for a predetermined amount of time, it indicates potential drowsiness.

Measuring Blinking Frequency

Monitoring the frequency of eye blinking is another important aspect of detecting drowsiness. We can identify drowsy patterns by analyzing the time interval between consecutive blinks ?

import cv2
import time

# Variables to track blinking frequency
blink_counter = 0
eyes_closed_start = None
CLOSED_EYES_FRAME = 3

# Load the pre-trained Haar cascade classifier for eye detection
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

# Capture video feed from the webcam
cap = cv2.VideoCapture(0)

closed_eyes_counter = 0

while True:
    # Read the current frame
    ret, frame = cap.read()
    
    if not ret:
        break
    
    # Convert the frame to grayscale for eye detection
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # Detect eyes in the grayscale frame
    eyes = eye_cascade.detectMultiScale(gray, 1.3, 5)
    
    # Check if eyes are detected (open) or not (closed)
    if len(eyes) >= 2:
        # Eyes are open
        closed_eyes_counter = 0
        for (x, y, w, h) in eyes:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    else:
        # Eyes might be closed
        closed_eyes_counter += 1
        if closed_eyes_counter >= CLOSED_EYES_FRAME:
            blink_counter += 1
            closed_eyes_counter = 0
    
    # Display the frame with eye rectangles and blinking frequency
    cv2.putText(frame, f"Blinks: {blink_counter}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
    cv2.imshow('Drowsiness Detection', frame)
    
    # Break loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture and close windows
cap.release()
cv2.destroyAllWindows()

Alerting the Driver

When drowsiness is detected, it is critical to immediately alert the driver to prevent potential accidents. Python provides various alerting methods, such as sound alarms and visual notifications ?

import cv2
import time
import winsound  # For Windows sound alert

# Variables to track drowsiness
blink_counter = 0
closed_eyes_counter = 0
CLOSED_EYES_FRAME = 15  # Number of consecutive frames for drowsiness
DROWSINESS_THRESHOLD = 3  # Seconds of closed eyes to trigger alert

# Load the pre-trained Haar cascade classifier for eye detection
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

# Capture video feed from the webcam
cap = cv2.VideoCapture(0)

while True:
    # Read the current frame
    ret, frame = cap.read()
    
    if not ret:
        break
    
    # Convert the frame to grayscale for eye detection
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # Detect eyes in the grayscale frame
    eyes = eye_cascade.detectMultiScale(gray, 1.3, 5)
    
    # Check if eyes are detected (open) or not (closed)
    if len(eyes) >= 2:
        # Eyes are open
        closed_eyes_counter = 0
        for (x, y, w, h) in eyes:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.putText(frame, "Eyes Open", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
    else:
        # Eyes might be closed
        closed_eyes_counter += 1
        cv2.putText(frame, "Eyes Closed", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        
        # Check for drowsiness
        if closed_eyes_counter >= CLOSED_EYES_FRAME:
            cv2.putText(frame, "DROWSINESS ALERT!", (10, 110), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
            # Sound alert (Windows)
            try:
                winsound.Beep(1000, 500)  # Frequency: 1000Hz, Duration: 500ms
            except:
                print("DROWSINESS ALERT!")  # Fallback if sound fails
    
    # Display the frame with detection results
    cv2.putText(frame, f"Closed frames: {closed_eyes_counter}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
    cv2.imshow('Drowsiness Detection', frame)
    
    # Break loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture and close windows
cap.release()
cv2.destroyAllWindows()

Key Features

Feature Description Implementation
Eye Detection Locates eyes in video frames Haar Cascade Classifier
Blink Monitoring Tracks eye closure patterns Frame counting method
Alert System Warns driver of drowsiness Sound beeps and visual alerts

Conclusion

Python OpenCV provides powerful tools for drowsiness detection by monitoring facial features and identifying drowsiness indicators such as prolonged eye closure. The combination of Haar cascades for eye detection and frame-counting algorithms enables accurate drowsiness assessment. Integrating alert mechanisms ensures timely warnings to prevent accidents caused by driver fatigue.

Updated on: 2026-03-27T09:03:38+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements