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
| """ GazeCapsNet轻量级视线估计 """ import torch import torch.nn as nn import numpy as np
class CapsuleLayer(nn.Module): """胶囊层""" def __init__(self, in_capsules: int, out_capsules: int, in_dim: int, out_dim: int): super().__init__() self.in_capsules = in_capsules self.out_capsules = out_capsules self.in_dim = in_dim self.out_dim = out_dim self.weight = nn.Parameter( torch.randn(in_capsules, out_capsules, in_dim, out_dim) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入胶囊 (B, in_capsules, in_dim) Returns: out: 输出胶囊 (B, out_capsules, out_dim) """ predictions = torch.einsum('bci,ciop->bcop', x, self.weight) out = self._dynamic_routing(predictions) return out def _dynamic_routing(self, predictions: torch.Tensor, iterations: int = 3) -> torch.Tensor: """动态路由算法""" batch_size = predictions.shape[0] coupling = torch.zeros(batch_size, self.in_capsules, self.out_capsules) for _ in range(iterations): attn = torch.softmax(coupling, dim=-1) s = torch.sum(attn.unsqueeze(-1) * predictions, dim=1) v = self._squash(s) coupling = coupling + torch.sum(predictions * v.unsqueeze(1), dim=-1) return v def _squash(self, x: torch.Tensor) -> torch.Tensor: """Squash激活函数""" norm = torch.norm(x, dim=-1, keepdim=True) return (norm ** 2 / (1 + norm ** 2)) * x / (norm + 1e-8)
class GazeCapsNet(nn.Module): """GazeCapsNet视线估计网络""" def __init__(self): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.ReLU() ) self.primary_caps = CapsuleLayer( in_capsules=256, out_capsules=32, in_dim=1, out_dim=8 ) self.gaze_caps = CapsuleLayer( in_capsules=32, out_capsules=1, in_dim=8, out_dim=3 ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入图像 (B, 3, H, W) Returns: gaze: 视线向量 (B, 3) """ features = self.features(x) batch_size = features.shape[0] capsules = features.view(batch_size, 256, -1).mean(dim=-1) capsules = capsules.unsqueeze(-1) primary = self.primary_caps(capsules.squeeze(-1)) gaze = self.gaze_caps(primary) return gaze.squeeze(1) def predict_gaze(self, image: np.ndarray) -> dict: """预测视线""" x = self._preprocess(image) with torch.no_grad(): gaze = self.forward(x) pitch = gaze[0, 0].item() yaw = gaze[0, 1].item() confidence = gaze[0, 2].item() return { 'pitch': pitch, 'yaw': yaw, 'confidence': confidence } def _preprocess(self, image: np.ndarray) -> torch.Tensor: """图像预处理""" from PIL import Image img = Image.fromarray(image).resize((224, 224)) x = np.array(img).astype(np.float32) / 255.0 x = torch.from_numpy(x).permute(2, 0, 1).unsqueeze(0) return x
if __name__ == "__main__": model = GazeCapsNet() model.eval() dummy = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = model.predict_gaze(dummy) print(f"视线估计: pitch={result['pitch']:.1f}°, yaw={result['yaw']:.1f}°") print(f"置信度: {result['confidence']:.2f}")
|