Here's a simplified Python code example for Distracted Driver Detection using OpenCV, dlib (for facial landmark detection), and MediaPipe (as an alternative). This basic version detects whether the driver is looking away from the road by analyzing head pose and eye gaze direction.
🔧 Requirements
Install the necessary libraries:
pip install opencv-python dlib numpy mediapipe
📸 Code: Distracted Driver Detection (Head Pose + Eye Gaze)
This script uses facial landmarks to estimate head orientation and detect if the driver’s eyes are off the road.
import cv2
import dlib
import numpy as np
# Load face detector and landmark predictor from dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 3D model points for head pose estimation
model_points = np.array([
(0.0, 0.0, 0.0), # Nose tip
(0.0, -330.0, -65.0), # Chin
(-225.0, 170.0, -135.0), # Left eye left corner
(225.0, 170.0, -135.0), # Right eye right corner
(-150.0, -150.0, -125.0), # Left Mouth corner
(150.0, -150.0, -125.0) # Right mouth corner
])
def get_head_pose(landmarks, frame):
image_points = np.array([
(landmarks[30][0], landmarks[30][1]), # Nose
(landmarks[8][0], landmarks[8][1]), # Chin
(landmarks[36][0], landmarks[36][1]), # Left eye
(landmarks[45][0], landmarks[45][1]), # Right eye
(landmarks[48][0], landmarks[48][1]), # Left mouth
(landmarks[54][0], landmarks[54][1]) # Right mouth
], dtype="double")
size = frame.shape
focal_length = size[1]
center = (size[1]/2, size[0]/2)
camera_matrix = np.array([
[focal_length, 0, center[0]],
[0, focal_length, center[1]],
[0, 0, 1]
], dtype="double")
dist_coeffs = np.zeros((4,1))
(success, rotation_vector, translation_vector) = cv2.solvePnP(model_points, image_points, camera_matrix, dist_coeffs)
# Draw axis
axis = np.float32([[300,0,0], [0,300,0], [0,0,300]]).reshape(-1,3)
imgpts, jac = cv2.projectPoints(axis, rotation_vector, translation_vector, camera_matrix, dist_coeffs)
frame = draw_axis(frame, imgpts)
return rotation_vector
def draw_axis(img, imgpts):
img = cv2.line(img, tuple(imgpts[0].ravel()), tuple(imgpts[1].ravel()), (0,255,0), 5) # Y - green
img = cv2.line(img, tuple(imgpts[0].ravel()), tuple(imgpts[2].ravel()), (255,0,0), 5) # Z - blue
img = cv2.line(img, tuple(imgpts[0].ravel()), tuple(imgpts[3].ravel()), (0,0,255), 5) # X - red
return img
def shape_to_np(shape):
return np.array([(p.x, p.y) for p in shape.parts()])
def main():
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
for face in faces:
shape = predictor(gray, face)
shape_np = shape_to_np(shape)
for (x, y) in shape_np:
cv2.circle(frame, (x, y), 2, (0, 255, 0), -1)
rot_vec = get_head_pose(shape_np, frame)
nose_point = tuple(shape_np[30])
# Simple distraction check based on head angle
if abs(rot_vec[0]) > 0.5 or abs(rot_vec[1]) > 0.5:
cv2.putText(frame, "DISTRACTED", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow("Driver Monitor", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
📁 Required File
✅ What This Detects
- Head pose (tilt and turn)
- If the driver turns their head significantly (e.g., looking at phone or passenger), the system flags them as distracted.
🧠 Optional Enhancements
You can improve this with:
- Eye Blink Detection: Using EAR (Eye Aspect Ratio) to detect prolonged closed eyes.
- Phone/Object Detection: Use YOLO or SSD to detect phones or food items.
- Deep Learning Models: Use CNNs trained on the State Farm Distracted Driver dataset.
- MediaPipe Face Mesh: For more accurate facial tracking.
📦 Example Dataset
For training deep learning models, use the State Farm Distracted Driver Dataset:
It includes 10 classes of distractions like texting, eating, talking on the phone, etc.
Would you like me to provide a deep learning-based solution using TensorFlow/Keras next?