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
| import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, List
class TDGHYOLOv7(nn.Module): """ TDGH-YOLOv7: Transformer Detection of Gaze and Head 基于 YOLOv7 的驾驶员头部姿态和眼动检测模型 参考: "AI-enabled driver assistance: monitoring head and gaze movements for enhanced safety" Complex & Intelligent Systems, 2025 """ def __init__(self, num_head_poses: int = 9, num_gaze_directions: int = 9): super().__init__() self.backbone = self._build_backbone() self.neck = self._build_neck() self.head = self._build_head(num_head_poses, num_gaze_directions) def _build_backbone(self) -> nn.Module: """构建 Backbone""" layers = [] layers.extend([ nn.Conv2d(3, 32, 3, stride=1, padding=1), nn.BatchNorm2d(32), nn.SiLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.SiLU(), ]) layers.extend([ self._make_elan_block(64, 64, expand_ratio=2), nn.Conv2d(128, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.SiLU(), ]) layers.extend([ self._make_elan_block(128, 128, expand_ratio=2), nn.Conv2d(256, 256, 3, stride=2, padding=1), nn.BatchNorm2d(256), nn.SiLU(), ]) layers.extend([ self._make_elan_block(256, 256, expand_ratio=2), ]) return nn.Sequential(*layers) def _make_elan_block(self, in_channels: int, out_channels: int, expand_ratio: int = 2) -> nn.Module: """构建 E-ELAN 模块""" hidden_channels = in_channels * expand_ratio return nn.Sequential( nn.Conv2d(in_channels, hidden_channels, 1), nn.BatchNorm2d(hidden_channels), nn.SiLU(), nn.Conv2d(hidden_channels, hidden_channels, 3, padding=1), nn.BatchNorm2d(hidden_channels), nn.SiLU(), nn.Conv2d(hidden_channels, out_channels, 1), nn.BatchNorm2d(out_channels), nn.SiLU(), ) def _build_neck(self) -> nn.Module: """构建 Neck(包含 Transformer)""" return TransformerNeck( in_channels=512, hidden_dim=256, num_heads=8, num_layers=3 ) def _build_head(self, num_poses: int, num_gazes: int) -> nn.Module: """构建多任务检测头""" return MultiTaskHead( in_channels=256, num_head_poses=num_poses, num_gaze_directions=num_gazes ) def forward(self, x: torch.Tensor) -> dict: """ 前向传播 Args: x: 输入图像, shape=(batch, 3, H, W) Returns: outputs: 检测结果 """ features = self.backbone(x) enhanced_features = self.neck(features) outputs = self.head(enhanced_features) return outputs
class TransformerNeck(nn.Module): """ Transformer Neck 使用 Transformer 增强特征提取能力,特别是小目标(眼睛)检测 """ def __init__(self, in_channels: int, hidden_dim: int, num_heads: int, num_layers: int): super().__init__() self.in_channels = in_channels self.hidden_dim = hidden_dim self.input_proj = nn.Conv2d(in_channels, hidden_dim, 1) encoder_layer = nn.TransformerEncoderLayer( d_model=hidden_dim, nhead=num_heads, dim_feedforward=hidden_dim * 4, dropout=0.1, activation='gelu', batch_first=True ) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers) self.output_proj = nn.Conv2d(hidden_dim, hidden_dim, 1) self.bpfe = BPFE(hidden_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入特征, shape=(batch, C, H, W) Returns: output: 增强特征 """ batch, C, H, W = x.shape x = self.input_proj(x) x_flat = x.flatten(2).transpose(1, 2) x_transformed = self.transformer(x_flat) x_out = x_transformed.transpose(1, 2).reshape(batch, self.hidden_dim, H, W) x_out = self.bpfe(x_out) x_out = self.output_proj(x_out) return x_out
class BPFE(nn.Module): """ Binary Pattern Feature Extraction 提取纹理特征用于面部区域检测 """ def __init__(self, channels: int): super().__init__() self.conv1 = nn.Conv2d(channels, channels, 3, padding=1) self.conv2 = nn.Conv2d(channels, channels, 3, padding=1) self.bn = nn.BatchNorm2d(channels) self.act = nn.SiLU() def forward(self, x: torch.Tensor) -> torch.Tensor: x1 = self.conv1(x) x2 = self.conv2(x) x_out = x + self.act(self.bn(x1 + x2)) return x_out
class MultiTaskHead(nn.Module): """ 多任务检测头 同时检测: - 人脸边界框 - 头部姿态类别 - 眼对边界框 - 注视方向类别 """ def __init__(self, in_channels: int, num_head_poses: int, num_gaze_directions: int): super().__init__() self.shared_conv = nn.Sequential( nn.Conv2d(in_channels, 128, 3, padding=1), nn.BatchNorm2d(128), nn.SiLU(), ) self.face_det = nn.Conv2d(128, 5, 1) self.head_pose_cls = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, num_head_poses) ) self.eye_det = nn.Conv2d(128, 10, 1) self.gaze_cls = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, num_gaze_directions) ) def forward(self, x: torch.Tensor) -> dict: """ 前向传播 Args: x: 输入特征, shape=(batch, C, H, W) Returns: outputs: 多任务输出 """ shared = self.shared_conv(x) face_bbox = self.face_det(shared) head_pose = self.head_pose_cls(shared) eye_bbox = self.eye_det(shared) gaze_dir = self.gaze_cls(shared) return { 'face_bbox': face_bbox, 'head_pose': head_pose, 'eye_bbox': eye_bbox, 'gaze_direction': gaze_dir }
|