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 294 295 296 297 298
| """ 深度学习瞳孔检测与视线估计 基于论文方法复现 """
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, Tuple, Optional
class PupilDetector(nn.Module): """ 瞳孔检测网络 输出:瞳孔中心坐标 + 椭圆参数 """ def __init__(self, config: Dict): super().__init__() self.encoder = nn.Sequential( nn.Conv2d(1, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.BatchNorm2d(256), nn.ReLU() ) self.center_head = nn.Sequential( nn.Conv2d(256, 128, 3, padding=1), nn.ReLU(), nn.Conv2d(128, 1, 1), nn.Sigmoid() ) self.ellipse_head = nn.Sequential( nn.Conv2d(256, 64, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 5) ) self.segmentation_head = nn.Sequential( nn.ConvTranspose2d(256, 128, 4, stride=2, padding=1), nn.ReLU(), nn.ConvTranspose2d(128, 64, 4, stride=2, padding=1), nn.ReLU(), nn.ConvTranspose2d(64, 32, 4, stride=2, padding=1), nn.ReLU(), nn.ConvTranspose2d(32, 1, 4, stride=2, padding=1), nn.Sigmoid() ) def forward(self, eye_image: torch.Tensor) -> Dict: """ 前向传播 Args: eye_image: 眼部图像 (B, 1, H, W) 灰度 Returns: outputs: 检测结果 """ features = self.encoder(eye_image) center_heatmap = self.center_head(features) ellipse_params = self.ellipse_head(features) segmentation = self.segmentation_head(features) batch_size = eye_image.shape[0] center_coords = self._extract_center(center_heatmap, batch_size) return { 'center': center_coords, 'ellipse': ellipse_params, 'segmentation': segmentation, 'heatmap': center_heatmap } def _extract_center(self, heatmap: torch.Tensor, batch_size: int) -> torch.Tensor: """从热图提取瞳孔中心""" flat = heatmap.view(batch_size, -1) max_idx = flat.argmax(dim=1) h, w = heatmap.shape[2], heatmap.shape[3] y = (max_idx // w).float() / h x = (max_idx % w).float() / w return torch.stack([x, y], dim=1)
class GazeEstimator(nn.Module): """ 视线估计网络 输入:眼部图像 + 头部姿态 输出:3D 视线向量 """ def __init__(self, config: Dict): super().__init__() self.eye_encoder = nn.Sequential( nn.Conv2d(1, 32, 5, stride=2, padding=2), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten() ) self.head_encoder = nn.Sequential( nn.Linear(3, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU() ) self.gaze_regressor = nn.Sequential( nn.Linear(128 + 64, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 2) ) def forward(self, eye_image: torch.Tensor, head_pose: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: eye_image: 眼部图像 (B, 1, H, W) head_pose: 头部姿态 (B, 3) [pitch, yaw, roll] 度 Returns: gaze: 视线向量 (B, 2) [yaw, pitch] 度 """ eye_features = self.eye_encoder(eye_image) head_features = self.head_encoder(head_pose) combined = torch.cat([eye_features, head_features], dim=1) gaze = self.gaze_regressor(combined) return gaze
class EyeTrackerPipeline: """ 完整眼动追踪流水线 整合人脸检测、眼部定位、瞳孔检测、视线估计 """ def __init__(self, config: Dict): self.pupil_detector = PupilDetector(config) self.gaze_estimator = GazeEstimator(config) def process_frame(self, frame: np.ndarray) -> Dict: """ 处理单帧图像 Args: frame: 输入图像 (H, W, 3) BGR Returns: result: 眼动追踪结果 """ face_bbox = self._detect_face(frame) left_eye, right_eye = self._locate_eyes(frame, face_bbox) left_pupil = self._detect_pupil(left_eye) right_pupil = self._detect_pupil(right_eye) left_gaze = self._estimate_gaze(left_eye, head_pose=(0, 0, 0)) right_gaze = self._estimate_gaze(right_eye, head_pose=(0, 0, 0)) final_gaze = self._fuse_gaze(left_gaze, right_gaze) return { 'left_pupil': left_pupil, 'right_pupil': right_pupil, 'left_gaze': left_gaze, 'right_gaze': right_gaze, 'final_gaze': final_gaze } def _detect_face(self, frame: np.ndarray) -> Tuple[int, int, int, int]: """人脸检测(简化)""" return (0, 0, frame.shape[1], frame.shape[0]) def _locate_eyes(self, frame: np.ndarray, face_bbox: Tuple) -> Tuple[np.ndarray, np.ndarray]: """眼部定位(简化)""" h, w = frame.shape[:2] left_eye = frame[h//4:h//2, w//4:w//2] right_eye = frame[h//4:h//2, w//2:3*w//4] return left_eye, right_eye def _detect_pupil(self, eye_image: np.ndarray) -> Dict: """瞳孔检测""" gray = cv2.cvtColor(eye_image, cv2.COLOR_BGR2GRAY) tensor = torch.from_numpy(gray).float().unsqueeze(0).unsqueeze(0) / 255.0 with torch.no_grad(): output = self.pupil_detector(tensor) return { 'center': output['center'].cpu().numpy()[0], 'ellipse': output['ellipse'].cpu().numpy()[0] } def _estimate_gaze(self, eye_image: np.ndarray, head_pose: Tuple) -> np.ndarray: """视线估计""" gray = cv2.cvtColor(eye_image, cv2.COLOR_BGR2GRAY) eye_tensor = torch.from_numpy(gray).float().unsqueeze(0).unsqueeze(0) / 255.0 head_tensor = torch.tensor(head_pose).float().unsqueeze(0) with torch.no_grad(): gaze = self.gaze_estimator(eye_tensor, head_tensor) return gaze.cpu().numpy()[0] def _fuse_gaze(self, left: np.ndarray, right: np.ndarray) -> np.ndarray: """双眼融合""" return (left + right) / 2
if __name__ == "__main__": import cv2 config = {} pipeline = EyeTrackerPipeline(config) dummy_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = pipeline.process_frame(dummy_frame) print("=== 眼动追踪结果 ===") print(f"左眼瞳孔中心: {result['left_pupil']['center']}") print(f"右眼瞳孔中心: {result['right_pupil']['center']}") print(f"最终视线方向: {result['final_gaze']}")
|