Real-Time Drowsiness Detection using OpenCV Python

Real-Time Drowsiness Detection using OpenCV Python With Source Code

The Real-Time Drowsiness Detection OpenCV Python was developed using Python OpenCV, this Drowsiness Detection is a safety technology that can prevent accidents that are caused by drivers who fall asleep while driving.

In a Drowsiness Detection OpenCV Python project, we will be using OpenCV to gather the images from the webcam and feed them into a Deep Learning model which will classify whether the person’s eyes are ‘Open’ or ‘Closed’.

In this Python OpenCV Project also includes a downloadable Python Project With Source Code for free, just find the downloadable source code below and click to start downloading.

By the way, if you are new to Python programming and don’t know what Python IDE is and its usage. I have here a list of the Best Python IDE for Windows, Linux, and Mac OS that will suit you.

I also have here How to Download and Install the Latest Version of Python on Windows.

To start executing Real-Time Drowsiness Detection OpenCV Python With Source Code, make sure that you have installed Python 3.9 and PyCharm on your computer.

How to run the Real-Time Drowsiness Detection using OpenCV Python? A step-by-step Guide with Source Code

Time needed: 5 minutes

These are the steps on how to run Real-Time Drowsiness Detection OpenCV Python With Source Code

  • Step 1: Download the given source code below.

    First, download the given source code below and unzip the source code.
    drowsiness detection download source code

  • Step 2: Import the project to your PyCharm IDE.

    Next, import the source code you’ve downloaded to your PyCharm IDE.
    drowsiness detection open project

  • Step 3: Run the project.

    Lastly, run the project with the command “py main.py”
    drowsiness detection run project

Installed Libraries

from scipy.spatial import distance
from imutils import face_utils
import imutils
import dlib
import cv2

Complete Source Code

from scipy.spatial import distance
from imutils import face_utils
import imutils
import dlib
import cv2

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
	
thresh = 0.25
frame_check = 20
detect = dlib.get_frontal_face_detector()
predict = dlib.shape_predictor(".\shape_predictor_68_face_landmarks.dat")# Dat file is the crux of the code

(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["right_eye"]
cap=cv2.VideoCapture(0)
flag=0
while True:
	ret, frame=cap.read()
	frame = imutils.resize(frame, width=450)
	gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
	subjects = detect(gray, 0)
	for subject in subjects:
		shape = predict(gray, subject)
		shape = face_utils.shape_to_np(shape)#converting to NumPy Array
		leftEye = shape[lStart:lEnd]
		rightEye = shape[rStart:rEnd]
		leftEAR = eye_aspect_ratio(leftEye)
		rightEAR = eye_aspect_ratio(rightEye)
		ear = (leftEAR + rightEAR) / 2.0
		leftEyeHull = cv2.convexHull(leftEye)
		rightEyeHull = cv2.convexHull(rightEye)
		cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
		cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)
		if ear < thresh:
			flag += 1
			print (flag)
			if flag >= frame_check:
				cv2.putText(frame, "****************ALERT!****************", (10, 30),
					cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
				cv2.putText(frame, "****************ALERT!****************", (10,325),
					cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
				#print ("Drowsy")
		else:
			flag = 0
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
	if key == ord("q"):
		break
cv2.destroyAllWindows()
cap.stop()

Output:

Download the Source Code below

Summary

In this Python project, we have built a drowsy driver alert system that you can implement in numerous ways.

We used OpenCV to detect faces and eyes using a haar cascade classifier and then we used a CNN model to predict the status.

Related Articles

Inquiries

If you have any questions or suggestions about Real-Time Drowsiness Detection OpenCV Python With Source Code, please feel free to leave a comment below.

Frequently Asked Questions

How does the real-time drowsiness detection system work?

MediaPipe Face Mesh or dlib detects 68 face landmarks. The script computes the Eye Aspect Ratio (EAR): ratio of vertical eye height to horizontal width. When EAR drops below ~0.21 for more than ~15 consecutive frames (~0.5 seconds), the system flags drowsiness and plays an alarm sound via pygame.mixer. Foundation for driver-monitoring systems used in commercial fleet management.

What Python and library versions do I need?

Python 3.10, 3.11, or 3.12 (avoid 3.13 until all DL wheels catch up). Install with: pip install opencv-python numpy. For deep learning models add: tensorflow keras (CPU build is fine for most demos), torch torchvision (PyTorch alternative), mediapipe (for face/hand/pose). Some projects also need: pytesseract for OCR, pyzbar for barcode, dlib for legacy face-landmark predictor.

Do I need a GPU to run this deep learning project?

For inference on a pretrained model: no, CPU runs at 10-30 FPS for most computer-vision tasks. For TRAINING a custom model: GPU strongly recommended (CPU works but slow). Free GPU options for training: Google Colab Free (12-hour sessions, sufficient for most BSIT capstones), Kaggle Notebooks Free. Buying a $1000+ GPU just for capstone is overkill.

Can I use this deep learning project for a BSIT or CSE capstone?

Yes, but extend it. A single OpenCV deep-learning demo (face detection, object detection alone) is too narrow for full capstone scope. Combine with a real domain wrapper: an attendance system using face recognition, a traffic monitoring system using vehicle detection, a wildlife camera using object detection, a driver-monitoring app using drowsiness detection. Add database logging, simple UI, and Chapter 1-5 manuscript.

Why does my model give wrong predictions or low accuracy?

Three most common causes: (1) Input preprocessing mismatch: the model expects 224×224 RGB normalized to [0,1] or [-1,1]; using BGR (OpenCV default) or wrong size produces garbage. (2) Insufficient training data: if you trained your own model on under 1,000 samples per class, accuracy plateaus low. Augment with cv2.flip, rotate, brightness shifts. (3) Lighting and angle drift between training and live use: train on data that matches the deployment environment.

Where can I find more deep learning project ideas with source code?

Browse our Deep Learning Projects hub for 19+ vision demos. For broader AI / ML / RAG / NLP capstones see 100+ AI Capstone Project Ideas. For pure ML (no deep learning) see Machine Learning Projects.

Angel Jude Suarez

Full-Stack Developer at PIES IT Solution

Focuses on Python development, machine learning, and AI integration. Has built production AI systems including OpenAI Whisper integration for medical transcription and GPT-4o-powered diagnosis assistance. Strong background in pandas, scikit-learn, and TensorFlow.

Expertise: Python · PHP · Java · VB.NET · ASP.NET · Machine Learning · AI Integration · OpenCV · Django · CodeIgniter  · View all posts by Angel Jude Suarez →

Leave a Comment