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
| import torch import torch.nn as nn
class GazeEstimationCNN(nn.Module): """ 传统CNN视线估计 输入: 人眼图像 输出: 视线向量 (pitch, yaw) """ def __init__(self): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, 11, stride=4, padding=2), nn.ReLU(), nn.MaxPool2d(3, stride=2), nn.Conv2d(64, 192, 5, padding=2), nn.ReLU(), nn.MaxPool2d(3, stride=2), nn.Conv2d(192, 384, 3, padding=1), nn.ReLU(), nn.Conv2d(384, 256, 3, padding=1), nn.ReLU(), nn.Conv2d(256, 128, 3, padding=1), nn.ReLU() ) self.regressor = nn.Sequential( nn.Linear(128 * 6 * 6, 4096), nn.ReLU(), nn.Dropout(), nn.Linear(4096, 2) ) def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.regressor(x) return x
class GazeEstimationTransformer(nn.Module): """ Transformer视线估计 更强的长距离依赖建模 """ def __init__(self, dim=256, num_heads=8): super().__init__() self.patch_embed = nn.Conv2d(3, dim, 16, 16) self.transformer = nn.TransformerEncoder( nn.TransformerEncoderLayer(dim, num_heads, dim*4), num_layers=6 ) self.head = nn.Linear(dim, 2) def forward(self, x): x = self.patch_embed(x) x = x.flatten(2).transpose(0, 1) x = self.transformer(x) x = x.mean(dim=0) x = self.head(x) return x
class MultiTaskGazeEstimation(nn.Module): """ 多任务视线估计 同时预测视线、头部姿态、眨眼 """ def __init__(self): super().__init__() self.encoder = nn.Sequential( nn.Conv2d(3, 64, 7, stride=2, padding=3), 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.gaze_head = nn.Linear(256, 2) self.pose_head = nn.Linear(256, 3) self.blink_head = nn.Linear(256, 2) def forward(self, x): feat = self.encoder(x) feat = feat.mean(dim=[2, 3]) gaze = self.gaze_head(feat) pose = self.pose_head(feat) blink = self.blink_head(feat) return { 'gaze': gaze, 'pose': pose, 'blink': blink }
if __name__ == "__main__": x = torch.randn(8, 3, 224, 224) cnn = GazeEstimationCNN() gaze_cnn = cnn(x) print(f"CNN输出: {gaze_cnn.shape}") trans = GazeEstimationTransformer() gaze_trans = trans(x) print(f"Transformer输出: {gaze_trans.shape}") multi = MultiTaskGazeEstimation() result = multi(x) print(f"多任务输出:") print(f" 视线: {result['gaze'].shape}") print(f" 头部姿态: {result['pose'].shape}") print(f" 眨眼: {result['blink'].shape}")
|