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
| import torch import torch.nn as nn import torch.nn.functional as F
class KPGBeltNet(nn.Module): """ KPGBeltNet: 人体关键点引导的安全带检测网络 架构: 1. Backbone: 轻量级CNN提取特征 2. Keypoint Branch: 检测人体关键点 3. Sampling Module: 关键点引导采样 4. Local-Global Attention: 双路注意力 5. Classification Head: 安全带状态分类 """ def __init__(self, config): super().__init__() self.backbone = MobileNetV3Small(pretrained=True) self.keypoint_head = KeypointHead( in_features=576, num_keypoints=17 ) self.kp_guided_sampling = KeypointGuidedSampling( feature_dim=576, sample_regions=5 ) self.local_attention = LocalAttention( in_channels=256, kernel_size=7 ) self.global_attention = GlobalAttention( in_channels=256, reduction=16 ) self.fusion = nn.Conv2d(512, 256, 1) self.classifier = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Dropout(0.5), nn.Linear(128, 4) ) def forward(self, x): """ Args: x: (B, 3, H, W) 输入图像 Returns: logits: (B, 4) 分类结果 keypoints: (B, 17, 3) 关键点 (x, y, conf) """ features = self.backbone(x) keypoints = self.keypoint_head(features) sampled_features = self.kp_guided_sampling(features, keypoints) local_feat = self.local_attention(sampled_features) global_feat = self.global_attention(sampled_features) fused = self.fusion(torch.cat([local_feat, global_feat], dim=1)) logits = self.classifier(fused) return logits, keypoints
class KeypointGuidedSampling(nn.Module): """ 关键点引导采样模块 原理: - 根据人体关键点定位安全带区域 - 从特征图中采样对应区域的特征 - 聚焦肩部、胸部、髋部三个关键区域 """ def __init__(self, feature_dim, sample_regions): super().__init__() self.feature_dim = feature_dim self.sample_regions = sample_regions self.region_extractors = nn.ModuleList([ nn.Conv2d(feature_dim, 256, 3, padding=1) for _ in range(sample_regions) ]) self.region_aggregator = nn.Sequential( nn.Conv2d(256 * sample_regions, 256, 1), nn.BatchNorm2d(256), nn.ReLU() ) def forward(self, features, keypoints): """ Args: features: (B, C, H, W) 特征图 keypoints: (B, 17, 3) 关键点 Returns: sampled: (B, 256, H, W) 采样特征 """ B, C, H, W = features.shape region_keypoints = [ [5, 6], [11, 12], [11, 12], ] region_features = [] for i, kp_indices in enumerate(region_keypoints[:self.sample_regions]): kp_coords = keypoints[:, kp_indices, :2] region_center = kp_coords.mean(dim=1) grid = self._create_sampling_grid(region_center, H, W) sampled = F.grid_sample(features, grid, align_corners=True) region_feat = self.region_extractors[i](sampled) region_features.append(region_feat) combined = torch.cat(region_features, dim=1) output = self.region_aggregator(combined) return output def _create_sampling_grid(self, centers, H, W, radius=0.3): """ 创建采样网格 Args: centers: (B, 2) 区域中心 (x, y),归一化坐标 H, W: 特征图尺寸 radius: 采样半径(归一化) Returns: grid: (B, H, W, 2) 采样网格 """ B = centers.shape[0] device = centers.device y = torch.linspace(-1, 1, H, device=device) x = torch.linspace(-1, 1, W, device=device) grid_y, grid_x = torch.meshgrid(y, x, indexing='ij') base_grid = torch.stack([grid_x, grid_y], dim=-1).unsqueeze(0).expand(B, -1, -1, -1) offset = centers.view(B, 1, 1, 2) grid = base_grid + offset grid = torch.clamp(grid, -1, 1) return grid
class LocalAttention(nn.Module): """局部注意力(捕捉细节)""" def __init__(self, in_channels, kernel_size=7): super().__init__() self.conv = nn.Conv2d(in_channels, in_channels, kernel_size, padding=kernel_size//2, groups=in_channels) self.bn = nn.BatchNorm2d(in_channels) def forward(self, x): return F.relu(self.bn(self.conv(x)))
class GlobalAttention(nn.Module): """全局注意力(捕捉上下文)""" def __init__(self, in_channels, reduction=16): super().__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(in_channels, in_channels // reduction), nn.ReLU(), nn.Linear(in_channels // reduction, in_channels), nn.Sigmoid() ) def forward(self, x): B, C, _, _ = x.shape y = self.avg_pool(x).view(B, C) y = self.fc(y).view(B, C, 1, 1) return x * y.expand_as(x)
|