1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
| import cv2 import numpy as np from scipy import signal from collections import deque
class PupilDiameterMonitor: """瞳孔直径监测器""" def __init__(self, history_length=300, fatigue_threshold=0.15): """初始化 Args: history_length: 历史数据长度 fatigue_threshold: 疲劳阈值(相对下降比例) """ self.history = deque(maxlen=history_length) self.baseline = None self.fatigue_threshold = fatigue_threshold self.eye_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_eye.xml' ) def detect_pupil(self, eye_roi): """检测瞳孔 Args: eye_roi: 眼部区域图像 Returns: pupil_diameter: 瞳孔直径(像素) confidence: 检测置信度 """ gray = cv2.cvtColor(eye_roi, cv2.COLOR_BGR2GRAY) if len(eye_roi.shape) == 3 else eye_roi blurred = cv2.GaussianBlur(gray, (5, 5), 0) _, thresh = cv2.threshold(blurred, 50, 255, cv2.THRESH_BINARY_INV) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: return None, 0 best_contour = max(contours, key=lambda c: cv2.contourArea(c)) area = cv2.contourArea(best_contour) if area < 10: return None, 0 diameter = 2 * np.sqrt(area / np.pi) perimeter = cv2.arcLength(best_contour, True) if perimeter == 0: return None, 0 circularity = 4 * np.pi * area / (perimeter ** 2) return diameter, circularity def update_baseline(self, diameter): """更新基线 Args: diameter: 当前瞳孔直径 """ self.history.append(diameter) if len(self.history) >= 100: self.baseline = np.mean(list(self.history)[-100:]) def assess_fatigue(self, current_diameter): """评估疲劳程度 Args: current_diameter: 当前瞳孔直径 Returns: fatigue_level: 疲劳等级 (0-3) ratio: 相对基线变化比例 """ if self.baseline is None: return 0, 0 ratio = (self.baseline - current_diameter) / self.baseline if ratio > 0.25: return 3, ratio elif ratio > 0.15: return 2, ratio elif ratio > 0.08: return 1, ratio else: return 0, ratio def calculate_cognitive_load(self, time_window=30): """计算认知负荷指标 基于瞳孔直径波动分析 Args: time_window: 时间窗口(帧数) Returns: load_index: 认知负荷指数 """ if len(self.history) < time_window: return 0 recent = np.array(list(self.history)[-time_window:]) if len(recent) >= 11: smoothed = signal.savgol_filter(recent, 11, 3) variation = np.std(smoothed) / np.mean(smoothed) load_index = min(variation * 10, 1.0) return load_index return 0
class PupilBasedFatigueDetector: """基于瞳孔的疲劳检测系统""" def __init__(self): self.pupil_monitor = PupilDiameterMonitor() self.warning_count = 0 def process_frame(self, frame): """处理单帧图像 Args: frame: BGR图像 Returns: result: 检测结果字典 """ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' ) faces = face_cascade.detectMultiScale(gray, 1.3, 5) results = { 'pupil_detected': False, 'diameter': None, 'fatigue_level': 0, 'cognitive_load': 0, 'warning': None } for (x, y, w, h) in faces: roi_gray = gray[y:y+h, x:x+w] eyes = self.pupil_monitor.eye_cascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in eyes: eye_roi = roi_gray[ey:ey+eh, ex:ex+ew] diameter, confidence = self.pupil_monitor.detect_pupil( cv2.cvtColor(frame[y+ey:y+ey+eh, x+ex:x+ex+ew], cv2.COLOR_BGR2GRAY) ) if diameter and confidence > 0.5: results['pupil_detected'] = True results['diameter'] = diameter self.pupil_monitor.update_baseline(diameter) fatigue, ratio = self.pupil_monitor.assess_fatigue(diameter) results['fatigue_level'] = fatigue results['cognitive_load'] = self.pupil_monitor.calculate_cognitive_load() if fatigue >= 2: results['warning'] = f"疲劳警告:瞳孔直径下降{ratio*100:.1f}%" self.warning_count += 1 elif fatigue == 1: results['warning'] = "轻度疲劳,请保持警觉" return results
if __name__ == "__main__": detector = PupilBasedFatigueDetector() for i in range(100): frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = detector.process_frame(frame) if result['pupil_detected']: print(f"帧{i}: 直径={result['diameter']:.1f}, " f"疲劳={result['fatigue_level']}, " f"负荷={result['cognitive_load']:.2f}")
|