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
| import cv2 import numpy as np from typing import Tuple, Optional
class MoireEyeTracker: """ 基于莫尔条纹的眼动追踪器 功能:从隐形眼镜的莫尔图案中解算视线方向 """ def __init__(self): self.focal_length = 800 self.image_center = (320, 240) self.grating_period = 8 self.num_quadrants = 4 self.quadrant_configs = [ {"angle1": 0, "angle2": 5}, {"angle1": 45, "angle2": 50}, {"angle1": 90, "angle2": 95}, {"angle1": 135, "angle2": 140} ] def detect_lens_region( self, image: np.ndarray ) -> Optional[Tuple[int, int, int]]: """ 检测隐形眼镜区域 Args: image: 输入图像 Returns: (cx, cy, radius): 镜片中心和半径 """ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150) circles = cv2.HoughCircles( edges, cv2.HOUGH_GRADIENT, dp=1, minDist=50, param1=50, param2=30, minRadius=50, maxRadius=150 ) if circles is not None: circles = np.uint16(np.around(circles)) largest = circles[0][np.argmax(circles[0][:, 2])] return tuple(largest) return None def extract_quadrants( self, image: np.ndarray, lens_center: Tuple[int, int, int] ) -> list: """ 提取四个象限的莫尔条纹区域 Args: image: 输入图像 lens_center: 镜片中心 (cx, cy, radius) Returns: quadrants: 四个象限的图像块 """ cx, cy, radius = lens_center offsets = [ (-radius//3, -radius//3), (radius//3, -radius//3), (-radius//3, radius//3), (radius//3, radius//3) ] quadrant_size = radius // 2 quadrants = [] for dx, dy in offsets: qx = cx + dx qy = cy + dy x1 = max(0, qx - quadrant_size//2) y1 = max(0, qy - quadrant_size//2) x2 = min(image.shape[1], qx + quadrant_size//2) y2 = min(image.shape[0], qy + quadrant_size//2) quadrant = image[y1:y2, x1:x2] quadrants.append(quadrant) return quadrants def analyze_moire_pattern( self, quadrant_image: np.ndarray, expected_angle: float ) -> Tuple[float, float]: """ 分析单个象限的莫尔条纹 Args: quadrant_image: 象限图像 expected_angle: 预期光栅角度 Returns: (measured_angle, confidence): 测量角度和置信度 """ if len(quadrant_image.shape) == 3: gray = cv2.cvtColor(quadrant_image, cv2.COLOR_BGR2GRAY) else: gray = quadrant_image fft = np.fft.fft2(gray) fft_shift = np.fft.fftshift(fft) magnitude = np.log(np.abs(fft_shift) + 1) magnitude = cv2.normalize( magnitude, None, 0, 255, cv2.NORM_MINMAX ).astype(np.uint8) edges = cv2.Canny(magnitude, 50, 150) lines = cv2.HoughLines(edges, 1, np.pi/180, 50) if lines is not None: angles = lines[:, 0, 1] dominant_angle = np.mean(angles) confidence = min(1.0, len(lines) / 10) return np.rad2deg(dominant_angle), confidence return expected_angle, 0.0 def compute_gaze_direction( self, quadrant_angles: list ) -> Tuple[float, float]: """ 从四个象限的角度解算视线方向 Args: quadrant_angles: 四个象限的测量角度 Returns: (azimuth, elevation): 方位角和俯仰角(度) """ horizontal_shift = quadrant_angles[1] - quadrant_angles[0] azimuth = horizontal_shift * 0.5 vertical_shift = quadrant_angles[2] - quadrant_angles[0] elevation = vertical_shift * 0.5 azimuth = np.clip(azimuth, -45, 45) elevation = np.clip(elevation, -30, 30) return azimuth, elevation def track( self, image: np.ndarray ) -> dict: """ 完整的眼动追踪流程 Args: image: 输入图像(来自标准摄像头) Returns: result: { "gaze": (azimuth, elevation), "confidence": 总体置信度, "lens_detected": 是否检测到镜片, "quadrant_data": 四个象限的详细数据 } """ lens_center = self.detect_lens_region(image) if lens_center is None: return { "gaze": (0, 0), "confidence": 0.0, "lens_detected": False, "quadrant_data": [] } quadrants = self.extract_quadrants(image, lens_center) quadrant_angles = [] quadrant_confidences = [] quadrant_data = [] for i, (quadrant, config) in enumerate( zip(quadrants, self.quadrant_configs) ): angle, conf = self.analyze_moire_pattern( quadrant, config["angle2"] ) quadrant_angles.append(angle) quadrant_confidences.append(conf) quadrant_data.append({ "quadrant": i + 1, "expected_angle": config["angle2"], "measured_angle": angle, "confidence": conf }) azimuth, elevation = self.compute_gaze_direction(quadrant_angles) overall_confidence = np.mean(quadrant_confidences) return { "gaze": (azimuth, elevation), "confidence": overall_confidence, "lens_detected": True, "quadrant_data": quadrant_data }
if __name__ == "__main__": tracker = MoireEyeTracker() image = cv2.imread("eye_with_lens.jpg") if image is not None: result = tracker.track(image) print("=== 眼动追踪结果 ===") print(f"检测到镜片: {result['lens_detected']}") print(f"视线方向: 方位角={result['gaze'][0]:.1f}°, 俯仰角={result['gaze'][1]:.1f}°") print(f"总体置信度: {result['confidence']:.2f}") print("\n=== 四个象限详细数据 ===") for qd in result['quadrant_data']: print(f"象限{qd['quadrant']}: 预期角度={qd['expected_angle']}°, " f"测量角度={qd['measured_angle']:.1f}°, 置信度={qd['confidence']:.2f}") else: print("未找到测试图像,请提供 eye_with_lens.jpg")
|