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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
| import cv2 import numpy as np import dlib
class HeadPoseEstimator: """头部姿态估计器""" MODEL_POINTS = np.array([ (0.0, 0.0, 0.0), (0.0, -330.0, -65.0), (-225.0, 170.0, -135.0), (225.0, 170.0, -135.0), (-150.0, -150.0, -125.0), (150.0, -150.0, -125.0) ]) def __init__(self, predictor_path='shape_predictor_68_face_landmarks.dat', camera_matrix=None, dist_coeffs=None): """初始化 Args: predictor_path: 关键点预测器路径 camera_matrix: 相机内参矩阵 dist_coeffs: 畸变系数 """ self.detector = dlib.get_frontal_face_detector() self.predictor = dlib.shape_predictor(predictor_path) self.camera_matrix = camera_matrix self.dist_coeffs = dist_coeffs def get_2d_landmarks(self, frame, face_rect): """获取2D关键点 Args: frame: 输入图像 face_rect: 人脸区域 Returns: landmarks: 2D关键点列表 """ shape = self.predictor(frame, face_rect) image_points = np.array([ (shape.part(30).x, shape.part(30).y), (shape.part(8).x, shape.part(8).y), (shape.part(36).x, shape.part(36).y), (shape.part(45).x, shape.part(45).y), (shape.part(48).x, shape.part(48).y), (shape.part(54).x, shape.part(54).y) ], dtype=np.float64) return image_points def estimate_pose(self, frame): """估计头部姿态 Args: frame: 输入图像 Returns: pose: 姿态字典 {yaw, pitch, roll, translation} landmarks: 关键点 """ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = self.detector(gray) if not faces: return None, None face = faces[0] image_points = self.get_2d_landmarks(gray, face) if self.camera_matrix is None: size = frame.shape focal_length = size[1] center = (size[1] / 2, size[0] / 2) self.camera_matrix = np.array([ [focal_length, 0, center[0]], [0, focal_length, center[1]], [0, 0, 1] ], dtype=np.float64) if self.dist_coeffs is None: self.dist_coeffs = np.zeros((4, 1)) success, rotation_vector, translation_vector = cv2.solvePnP( self.MODEL_POINTS, image_points, self.camera_matrix, self.dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE ) if not success: return None, image_points rotation_mat, _ = cv2.Rodrigues(rotation_vector) pose = self.rotation_matrix_to_euler_angles(rotation_mat) return { 'yaw': pose[1], 'pitch': pose[0], 'roll': pose[2], 'translation': translation_vector.flatten().tolist() }, image_points @staticmethod def rotation_matrix_to_euler_angles(R): """旋转矩阵转欧拉角 Args: R: 3x3旋转矩阵 Returns: euler: (pitch, yaw, roll) in degrees """ sy = np.sqrt(R[0, 0] ** 2 + R[1, 0] ** 2) singular = sy < 1e-6 if not singular: pitch = np.arctan2(-R[2, 0], sy) yaw = np.arctan2(R[1, 0], R[0, 0]) roll = np.arctan2(R[2, 1], R[2, 2]) else: pitch = np.arctan2(-R[2, 0], sy) yaw = np.arctan2(-R[1, 2], R[1, 1]) roll = 0 return np.degrees([pitch, yaw, roll])
class DistractionDetector: """分心检测器""" THRESHOLDS = { 'yaw_max': 30, 'yaw_warn': 25, 'pitch_max': 35, 'pitch_min': -35, 'duration': 2.0 } def __init__(self, fps=30): """初始化 Args: fps: 帧率 """ self.fps = fps self.pose_estimator = HeadPoseEstimator() self.distraction_start = None self.distraction_type = None self.frame_count = 0 def detect(self, frame): """检测分心状态 Args: frame: 输入图像 Returns: result: 检测结果 """ self.frame_count += 1 pose, landmarks = self.pose_estimator.estimate_pose(frame) result = { 'pose': pose, 'is_distracted': False, 'distraction_type': None, 'duration': 0 } if pose is None: return result yaw = abs(pose['yaw']) pitch = pose['pitch'] is_distracted = False distraction_type = None if yaw > self.THRESHOLDS['yaw_max']: is_distracted = True distraction_type = 'horizontal_distraction' elif pitch > self.THRESHOLDS['pitch_max']: is_distracted = True distraction_type = 'looking_up' elif pitch < self.THRESHOLDS['pitch_min']: is_distracted = True distraction_type = 'looking_down' if is_distracted: if self.distraction_start is None: self.distraction_start = self.frame_count self.distraction_type = distraction_type elif self.distraction_type == distraction_type: duration = (self.frame_count - self.distraction_start) / self.fps result['duration'] = duration if duration >= self.THRESHOLDS['duration']: result['is_distracted'] = True result['distraction_type'] = distraction_type else: self.distraction_start = None self.distraction_type = None return result
class DeepHeadPoseEstimator: """基于深度学习的头部姿态估计""" def __init__(self, model_path): """初始化模型 Args: model_path: 模型路径 """ import tensorflow as tf self.model = tf.keras.models.load_model(model_path) self.input_size = (224, 224) def preprocess(self, face_image): """预处理 Args: face_image: 人脸图像 Returns: preprocessed: 预处理后的张量 """ img = cv2.resize(face_image, self.input_size) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img.astype(np.float32) / 255.0 img = np.expand_dims(img, axis=0) return img def predict(self, face_image): """预测头部姿态 Args: face_image: 人脸图像 Returns: pose: (yaw, pitch, roll) """ preprocessed = self.preprocess(face_image) predictions = self.model.predict(preprocessed, verbose=0) yaw = float(predictions[0][0]) pitch = float(predictions[0][1]) roll = float(predictions[0][2]) return { 'yaw': np.degrees(yaw), 'pitch': np.degrees(pitch), 'roll': np.degrees(roll) }
if __name__ == "__main__": detector = DistractionDetector(fps=30) frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = detector.detect(frame) if result['pose']: print(f"头部姿态: Yaw={result['pose']['yaw']:.1f}°, " f"Pitch={result['pose']['pitch']:.1f}°, " f"Roll={result['pose']['roll']:.1f}°") if result['is_distracted']: print(f"警告: 检测到分心! 类型: {result['distraction_type']}, " f"持续: {result['duration']:.1f}秒")
|