Drowsiness or eye detection in opencv python raspberry pi

Photo of author

By Jackson Taylor

Home » Electronics Topics » Raspberry Pi » Drowsiness or eye detection in opencv python raspberry pi

As an Amazon Associate we earn from qualifying purchases.

Drowsiness detection watches a person’s face through a camera and raises an alert when their eyes stay closed for too long. This guide shows a simple version built with OpenCV and Python on a Raspberry Pi. It first detects a face, then looks for eyes inside that face, and treats a long run of frames without visible eyes as a sign of drowsiness.

The approach uses Haar cascade classifiers. They are not the most accurate option, but they are light enough to run on a Raspberry Pi, and they are a good way to learn how face and eye detection work.

Video demo and code download

The video below shows the project running. The original code is available through the download link under it, and a cleaned-up version is listed further down this page.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
CODE DOWNLOAD

What you need

If you are new to the library, read up on OpenCV and Python basics first. If you work on the Pi from another computer, see how to connect your Raspberry Pi to a laptop using SSH or VNC.

Install OpenCV on the Raspberry Pi

The simplest route is to install OpenCV from the system package manager or from pip. Either of these usually works:

  • apt: sudo apt install python3-opencv python3-numpy
  • pip: pip install opencv-python numpy (inside a virtual environment on recent Raspberry Pi OS versions)

Both OpenCV packages include the Haar cascade XML files. You can load them from cv2.data.haarcascades without downloading anything extra.

How the detection works

  1. Read a frame from the camera and convert it to grayscale, which is faster to process.
  2. Detect faces with haarcascade_frontalface_default.xml.
  3. Crop each face region and search it for eyes with haarcascade_eye.xml.
  4. Draw rectangles around the face and eyes so you can see what the program found.
  5. Report whether eyes were found in the frame.
See also
SENDING EMAIL IN PYTHON

Searching for eyes only inside the face region is faster than scanning the whole frame, and it cuts down on false detections elsewhere in the image.

Basic eye detection code

This is the original script, updated to run on Python 3. The old version used Python 2 print statements, which cause a syntax error on current Raspberry Pi OS. Press Esc to quit.

import cv2

# Haar cascades ship with OpenCV
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

cap = cv2.VideoCapture(0)

while True:
    ret, img = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
        roi_gray = gray[y:y + h, x:x + w]
        roi_color = img[y:y + h, x:x + w]

        eyes = eye_cascade.detectMultiScale(roi_gray)
        if len(eyes) > 0:
            print('eyes')
        else:
            print('no')

        for (ex, ey, ew, eh) in eyes:
            cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)

    cv2.imshow('img', img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

The original file defined an eye_threshol variable but never used it. The next section puts that idea to work.

Turning eye detection into drowsiness detection

Detecting eyes in one frame does not tell you much, because everyone blinks. Drowsiness shows up as eyes staying closed over many consecutive frames. So count the frames where a face is visible but no eyes are found, and raise an alert when the count passes a limit.

import cv2

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)

EYE_THRESHOLD = 15   # frames without eyes before the alert
closed_frames = 0

while True:
    ret, img = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
        roi_gray = gray[y:y + h, x:x + w]
        eyes = eye_cascade.detectMultiScale(roi_gray)

        if len(eyes) == 0:
            closed_frames += 1
        else:
            closed_frames = 0

        if closed_frames >= EYE_THRESHOLD:
            cv2.putText(img, 'DROWSY!', (x, y - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
            # trigger a buzzer or LED on a GPIO pin here

    cv2.imshow('img', img)
    if cv2.waitKey(30) & 0xff == 27:
        break

cap.release()
cv2.destroyAllWindows()

The right threshold depends on your frame rate. On a slow Pi, 15 frames may be a couple of seconds or more, so adjust it by testing with your own setup.

See also
Raspberry Pi Digital Output: Turn an LED On and Off

Tips for better results on a Raspberry Pi

  • Lower the resolution. A smaller frame such as 320×240 gives a much smoother frame rate on a Pi.
  • Use good lighting. Haar cascades struggle in dim light or with strong shadows across the face.
  • Face the camera. The frontal face cascade works best when the head is roughly straight to the camera.
  • Tune detectMultiScale. A higher minNeighbors value reduces false detections, and a larger scale factor makes detection faster but less thorough.
  • Remove the display when deployed. Drawing windows with imshow costs processing time, so skip it once the project is working.

Limitations to know about

The eye cascade does not truly recognise a closed eye. It simply fails to find an open one, which is why the method can misfire. Glasses, reflections, a head turned to the side or poor lighting can all make the eyes disappear from detection even when they are open.

For a more reliable system, look at facial landmark detection and the eye aspect ratio method, which measures how open the eye is from points around it. It needs more processing power, but it is a natural next step once this version works. You can find more ideas in our list of Raspberry Pi Python projects.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

This kind of project is a learning exercise. It should not be relied on as a safety device for drivers.

FAQ

Can a Raspberry Pi run drowsiness detection in real time?

Yes, with Haar cascades at a low resolution it can run at a usable frame rate. Heavier methods, such as deep learning models, will be slower unless you add an accelerator.

Why does the original code give a syntax error?

The original script used Python 2 style print ‘eyes’ statements. In Python 3 you must write print(‘eyes’), as in the updated code above.

Can I use the Raspberry Pi camera module instead of a USB webcam?

Yes, but cv2.VideoCapture(0) may not work with it on newer Raspberry Pi OS versions. In that case, capture frames with the Picamera2 library and pass them to the same OpenCV detection code.

See also
POWER FACTOR MEASUREMENT USING ARDUNO

Why are my eyes not detected even when they are open?

This is usually caused by poor lighting, glasses, a tilted head or a face that is too far from the camera. Improve the lighting, move closer and face the camera directly.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works