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
| import torch import torch.nn as nn import torch.nn.functional as F
class SeatbeltDetector(nn.Module): """ 安全带检测器 基于YOLOv7架构,优化用于安全带误用检测 改进点: 1. 多尺度特征融合 2. 小目标检测增强 3. 细长目标(安全带)优化 """ def __init__(self, num_classes: int = 6, anchors: torch.Tensor = None): """ 初始化 Args: num_classes: 类别数 anchors: 锚框尺寸 """ super().__init__() self.num_classes = num_classes if anchors is None: anchors = torch.tensor([ [[10, 13], [16, 30], [33, 23]], [[30, 61], [62, 45], [59, 119]], [[116, 90], [156, 198], [373, 326]] ], dtype=torch.float32) self.anchors = anchors self.backbone = CSPDarknet() self.neck = PANet() self.head = DetectionHead(num_classes, anchors) def forward(self, x: torch.Tensor) -> List[torch.Tensor]: """ 前向传播 Args: x: 输入图像 (B, 3, H, W) Returns: outputs: 检测输出列表 """ features = self.backbone(x) fused_features = self.neck(features) outputs = self.head(fused_features) return outputs
class CSPDarknet(nn.Module): """CSPDarknet骨干网络""" def __init__(self, in_channels: int = 3): super().__init__() self.stem = ConvBlock(in_channels, 32, 3, 1) self.stage1 = self._make_stage(32, 64, 1) self.stage2 = self._make_stage(64, 128, 2) self.stage3 = self._make_stage(128, 256, 8) self.stage4 = self._make_stage(256, 512, 8) self.stage5 = self._make_stage(512, 1024, 4) def _make_stage(self, in_channels, out_channels, num_blocks): layers = [ ConvBlock(in_channels, out_channels, 3, 2), ] for _ in range(num_blocks): layers.append(ResidualBlock(out_channels, out_channels // 2)) return nn.Sequential(*layers) def forward(self, x): x = self.stem(x) c3 = self.stage3(x) c4 = self.stage4(c3) c5 = self.stage5(c4) return [c3, c4, c5]
class PANet(nn.Module): """PANet颈部网络""" def __init__(self): super().__init__() self.up1 = Upsample(1024, 512) self.up2 = Upsample(512, 256) self.down1 = ConvBlock(256 + 256, 256, 3, 2) self.down2 = ConvBlock(256 + 512, 512, 3, 2) def forward(self, features): c3, c4, c5 = features p5 = c5 p4 = self.up1(p5) + c4 p3 = self.up2(p4) + c3 n3 = p3 n4 = self.down1(n3) + p4 n5 = self.down2(n4) + p5 return [n3, n4, n5]
class DetectionHead(nn.Module): """检测头""" def __init__(self, num_classes, anchors): super().__init__() self.num_classes = num_classes self.anchors = anchors self.heads = nn.ModuleList([ nn.Sequential( ConvBlock(256, 256, 3, 1), ConvBlock(256, 3 * (5 + num_classes), 1, 1, activation=False) ), nn.Sequential( ConvBlock(512, 512, 3, 1), ConvBlock(512, 3 * (5 + num_classes), 1, 1, activation=False) ), nn.Sequential( ConvBlock(1024, 1024, 3, 1), ConvBlock(1024, 3 * (5 + num_classes), 1, 1, activation=False) ) ]) def forward(self, features): outputs = [] for i, (feat, head) in enumerate(zip(features, self.heads)): output = head(feat) outputs.append(output) return outputs
class ConvBlock(nn.Module): """卷积块""" def __init__(self, in_channels, out_channels, kernel_size, stride, activation=True): super().__init__() padding = kernel_size // 2 layers = [ nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.BatchNorm2d(out_channels) ] if activation: layers.append(nn.SiLU()) self.block = nn.Sequential(*layers) def forward(self, x): return self.block(x)
class ResidualBlock(nn.Module): """残差块""" def __init__(self, in_channels, hidden_channels): super().__init__() self.block = nn.Sequential( ConvBlock(in_channels, hidden_channels, 1, 1), ConvBlock(hidden_channels, in_channels, 3, 1) ) def forward(self, x): return x + self.block(x)
class Upsample(nn.Module): """上采样""" def __init__(self, in_channels, out_channels): super().__init__() self.conv = ConvBlock(in_channels, out_channels, 1, 1) def forward(self, x): x = self.conv(x) x = F.interpolate(x, scale_factor=2, mode='nearest') return x
if __name__ == "__main__": model = SeatbeltDetector() x = torch.randn(2, 3, 640, 640) outputs = model(x) print("模型输出:") for i, out in enumerate(outputs): print(f" P{i+3}: {out.shape}")
|