import cv2
import mediapipe as mp
import numpy as np
from collections import deque
from datetime import datetime
import json
class AdvancedBlinkDetector:
def __init__(self, window_size=5):
"""
Advanced blink detection with smoothing
"""
self.mp_face_mesh = mp.solutions.face_mesh
self.face_mesh = self.mp_face_mesh.FaceMesh(
static_image_mode=False,
max_num_faces=1,
refine_landmarks=True,
min_detection_confidence=0.5
)
# Eye landmarks
self.LEFT_EYE = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466,
388, 387, 386, 385, 384, 398]
self.RIGHT_EYE = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173,
157, 158, 159, 160, 161, 246]
# Precise eye regions for EAR calculation
self.LEFT_EYE_TOP = [386, 374, 373]
self.LEFT_EYE_BOTTOM = [390, 388, 387]
self.RIGHT_EYE_TOP = [159, 145, 144]
self.RIGHT_EYE_BOTTOM = [163, 157, 158]
# EAR smoothing
self.ear_window = deque(maxlen=window_size)
# Blink parameters
self.EAR_THRESHOLD = 0.18
self.CONSECUTIVE_FRAMES = 2
# Statistics
self.blink_data = []
self.current_eye_state = "open"
self.frames_counter = 0
self.blink_start_time = None
self.total_blinks = 0
self.total_closed_time = 0.0
def calculate_distance(self, p1, p2):
"""Calculate Euclidean distance between two points"""
return np.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
def calculate_eye_aspect_ratio(self, landmarks, top_indices, bottom_indices):
"""Calculate EAR with improved formula"""
# Get landmark coordinates
top_points = np.array([landmarks[i][:2] for i in top_indices])
bottom_points = np.array([landmarks[i][:2] for i in bottom_indices])
# Calculate distances
dist1 = self.calculate_distance(top_points[0], bottom_points[0])
dist2 = self.calculate_distance(top_points[1], bottom_points[1])
dist3 = self.calculate_distance(top_points[2], bottom_points[2])
# Horizontal distance (eye width)
horizontal = self.calculate_distance(top_points[0], top_points[2])
# EAR formula
ear = (dist1 + dist2 + dist3) / (3 * horizontal + 1e-6)
return ear
def smooth_ear(self, ear_value):
"""Apply smoothing to EAR values"""
self.ear_window.append(ear_value)
return np.mean(self.ear_window)
def detect_blink(self, left_ear, right_ear, timestamp):
"""Detect blink with state machine"""
avg_ear = (left_ear + right_ear) / 2
smooth_ear = self.smooth_ear(avg_ear)
is_blink = False
if smooth_ear < self.EAR_THRESHOLD:
if self.current_eye_state == "open":
self.current_eye_state = "closed"
self.blink_start_time = timestamp
self.frames_counter = 1
else:
self.frames_counter += 1
else:
if self.current_eye_state == "closed":
if self.frames_counter >= self.CONSECUTIVE_FRAMES:
# Valid blink detected
self.total_blinks += 1
blink_duration = timestamp - self.blink_start_time
self.total_closed_time += blink_duration
self.blink_data.append({
'timestamp': timestamp,
'duration': blink_duration,
'ear_min': min(self.ear_window)
})
is_blink = True
self.current_eye_state = "open"
self.frames_counter = 0
return is_blink, smooth_ear, self.current_eye_state == "closed"
def get_statistics(self):
"""Generate statistics report"""
stats = {
'total_blinks': self.total_blinks,
'total_closed_time': self.total_closed_time,
'average_blink_duration': np.mean([b['duration'] for b in self.blink_data])
if self.blink_data else 0,
'blink_data': self.blink_data
}
return stats
def process_frame(self, frame, timestamp):
"""Process frame and return results"""
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = self.face_mesh.process(rgb_frame)
info = {
'landmarks': None,
'left_ear': 0,
'right_ear': 0,
'is_blink': False,
'smooth_ear': 0,
'is_closed': False
}
if results.multi_face_landmarks:
landmarks = results.multi_face_landmarks[0].landmark
left_ear = self.calculate_eye_aspect_ratio(
landmarks, self.LEFT_EYE_TOP, self.LEFT_EYE_BOTTOM
)
right_ear = self.calculate_eye_aspect_ratio(
landmarks, self.RIGHT_EYE_TOP, self.RIGHT_EYE_BOTTOM
)
is_blink, smooth_ear, is_closed = self.detect_blink(
left_ear, right_ear, timestamp
)
info = {
'landmarks': landmarks,
'left_ear': left_ear,
'right_ear': right_ear,
'is_blink': is_blink,
'smooth_ear': smooth_ear,
'is_closed': is_closed
}
return info
def save_statistics(self, filename='blink_statistics.json'):
"""Save statistics to file"""
stats = self.get_statistics()
with open(filename, 'w') as f:
json.dump(stats, f, indent=2, default=str)
print(f"Statistics saved to {filename}")
class BlinkVisualizerAdvanced:
def __init__(self):
"""Advanced visualization with graphs"""
self.ear_history = deque(maxlen=300) # 10 seconds at 30 fps
self.time_history = deque(maxlen=300)
def draw_landmark_with_labels(self, image, landmarks):
"""Draw landmarks with specific coloring"""
h, w, c = image.shape
# Define regions
regions = {
'mouth': list(range(78, 96)),
'left_eye': [362, 382, 381, 380, 374, 373, 390, 249, 263, 466],
'right_eye': [33, 7, 163, 144, 145, 153, 154, 155, 133, 173],
'nose': list(range(1, 22)),
}
colors = {
'mouth': (200, 100, 100),
'left_eye': (100, 100, 200),
'right_eye': (200, 100, 100),
'nose': (100, 200, 100),
'face': (100, 100, 100)
}
for idx, landmark in enumerate(landmarks):
x = int(landmark.x * w)
y = int(landmark.y * h)
color = colors['face']
radius = 1
for region_name, indices in regions.items():
if idx in indices:
color = colors[region_name]
if region_name in ['left_eye', 'right_eye']:
radius = 2
break
cv2.circle(image, (x, y), radius, color, -1)
return image
def draw_ear_graph(self, image, ear_values, threshold=0.18):
"""Draw EAR history graph"""
h, w, c = image.shape
# Graph dimensions
graph_w, graph_h = 300, 150
graph_x, graph_y = w - graph_w - 20, 20
# Background
cv2.rectangle(image, (graph_x, graph_y),
(graph_x + graph_w, graph_y + graph_h),
(0, 0, 0), -1)
cv2.rectangle(image, (graph_x, graph_y),
(graph_x + graph_w, graph_y + graph_h),
(255, 255, 255), 2)
# Draw threshold line
thresh_y = int(graph_y + graph_h - (threshold * graph_h / 0.5))
cv2.line(image, (graph_x, thresh_y),
(graph_x + graph_w, thresh_y), (0, 0, 255), 1)
# Draw EAR values
if len(ear_values) > 1:
for i in range(len(ear_values) - 1):
x1 = graph_x + int(i * graph_w / len(ear_values))
x2 = graph_x + int((i + 1) * graph_w / len(ear_values))
y1 = graph_y + graph_h - int(min(ear_values[i], 0.5) * graph_h / 0.5)
y2 = graph_y + graph_h - int(min(ear_values[i + 1], 0.5) * graph_h / 0.5)
color = (0, 255, 0) if ear_values[i] > threshold else (0, 0, 255)
cv2.line(image, (x1, y1), (x2, y2), color, 2)
# Labels
cv2.putText(image, "EAR Graph", (graph_x + 10, graph_y + 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.putText(image, f"Threshold: {threshold:.2f}",
(graph_x + 10, graph_y + 40),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255), 1)
return image
def draw_statistics_panel(self, image, detector, info):
"""Draw comprehensive statistics panel"""
h, w, c = image.shape
# Panel dimensions
panel_w, panel_h = 350, 200
panel_x, panel_y = 15, 15
# Background with transparency effect
cv2.rectangle(image, (panel_x, panel_y),
(panel_x + panel_w, panel_y + panel_h),
(0, 0, 0), -1)
cv2.rectangle(image, (panel_x, panel_y),
(panel_x + panel_w, panel_y + panel_h),
(100, 255, 100), 2)
# Content
line_y = panel_y + 30
line_step = 25
cv2.putText(image, "BLINK DETECTION STATS",
(panel_x + 10, line_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (100, 255, 100), 2)
line_y += line_step + 5
# Blink status
status_text = "BLINKING!" if info['is_blink'] else "Eyes Open"
status_color = (0, 0, 255) if info['is_blink'] else (0, 255, 0)
cv2.putText(image, f"Status: {status_text}",
(panel_x + 10, line_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, status_color, 2)
line_y += line_step
cv2.putText(image, f"Total Blinks: {detector.total_blinks}",
(panel_x + 10, line_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1)
line_y += line_step
cv2.putText(image, f"EAR (Left): {info['left_ear']:.3f}",
(panel_x + 10, line_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (100, 100, 255), 1)
line_y += line_step
cv2.putText(image, f"EAR (Right): {info['right_ear']:.3f}",
(panel_x + 10, line_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 100, 100), 1)
line_y += line_step
cv2.putText(image, f"EAR (Smooth): {info['smooth_ear']:.3f}",
(panel_x + 10, line_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 100), 1)
return image
def advanced_demo():
"""Run advanced blink detection demo"""
detector = AdvancedBlinkDetector()
visualizer = BlinkVisualizerAdvanced()
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
frame_count = 0
start_time = time.time()
print("Advanced Blink Detection Running...")
print("Press 'q' to quit and save statistics")
while True:
ret, frame = cap.read()
if not ret:
break
timestamp = time.time() - start_time
info = detector.process_frame(frame, timestamp)
if info['landmarks']:
# Draw landmarks
visualizer.draw_landmark_with_labels(frame, info['landmarks'])
# Draw statistics
visualizer.draw_statistics_panel(frame, detector, info)
# Draw EAR graph
visualizer.ear_history.append(info['smooth_ear'])
visualizer.draw_ear_graph(frame, list(visualizer.ear_history))
# Draw FPS
frame_count += 1
fps = frame_count / (timestamp + 1e-6)
cv2.putText(frame, f"FPS: {fps:.1f}", (20, 100),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imshow('Advanced Blink Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Save statistics
detector.save_statistics()
stats = detector.get_statistics()
print("\n=== Statistics ===")
print(f"Total Blinks: {stats['total_blinks']}")
print(f"Total Closed Time: {stats['total_closed_time']:.2f}s")
print(f"Average Blink Duration: {stats['average_blink_duration']:.3f}s")
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
# Run advanced demo
import time
advanced_demo()