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from __future__ import division
|
| 3 |
+
from __future__ import print_function
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
+
from typing import List, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import cv2
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
import torchvision.transforms as T
|
| 16 |
+
import torchvision.transforms.functional as f
|
| 17 |
+
from pydantic import BaseModel
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class BoundingBox(BaseModel):
|
| 24 |
+
x1: int
|
| 25 |
+
y1: int
|
| 26 |
+
x2: int
|
| 27 |
+
y2: int
|
| 28 |
+
cls_id: int
|
| 29 |
+
conf: float
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TVFrameResult(BaseModel):
|
| 33 |
+
frame_id: int
|
| 34 |
+
boxes: list[BoundingBox]
|
| 35 |
+
keypoints: list[tuple[int, int]]
|
| 36 |
+
|
| 37 |
+
BatchNorm2d = nn.BatchNorm2d
|
| 38 |
+
BN_MOMENTUM = 0.1
|
| 39 |
+
|
| 40 |
+
def conv3x3(in_planes, out_planes, stride=1):
|
| 41 |
+
"""3x3 convolution with padding"""
|
| 42 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3,
|
| 43 |
+
stride=stride, padding=1, bias=False)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class BasicBlock(nn.Module):
|
| 47 |
+
expansion = 1
|
| 48 |
+
|
| 49 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
| 50 |
+
super(BasicBlock, self).__init__()
|
| 51 |
+
self.conv1 = conv3x3(inplanes, planes, stride)
|
| 52 |
+
self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
|
| 53 |
+
self.relu = nn.ReLU(inplace=True)
|
| 54 |
+
self.conv2 = conv3x3(planes, planes)
|
| 55 |
+
self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
|
| 56 |
+
self.downsample = downsample
|
| 57 |
+
self.stride = stride
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
residual = x
|
| 61 |
+
|
| 62 |
+
out = self.conv1(x)
|
| 63 |
+
out = self.bn1(out)
|
| 64 |
+
out = self.relu(out)
|
| 65 |
+
|
| 66 |
+
out = self.conv2(out)
|
| 67 |
+
out = self.bn2(out)
|
| 68 |
+
|
| 69 |
+
if self.downsample is not None:
|
| 70 |
+
residual = self.downsample(x)
|
| 71 |
+
|
| 72 |
+
out += residual
|
| 73 |
+
out = self.relu(out)
|
| 74 |
+
|
| 75 |
+
return out
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Bottleneck(nn.Module):
|
| 79 |
+
expansion = 4
|
| 80 |
+
|
| 81 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
| 82 |
+
super(Bottleneck, self).__init__()
|
| 83 |
+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
|
| 84 |
+
self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
|
| 85 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
|
| 86 |
+
padding=1, bias=False)
|
| 87 |
+
self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
|
| 88 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
|
| 89 |
+
bias=False)
|
| 90 |
+
self.bn3 = BatchNorm2d(planes * self.expansion,
|
| 91 |
+
momentum=BN_MOMENTUM)
|
| 92 |
+
self.relu = nn.ReLU(inplace=True)
|
| 93 |
+
self.downsample = downsample
|
| 94 |
+
self.stride = stride
|
| 95 |
+
|
| 96 |
+
def forward(self, x):
|
| 97 |
+
residual = x
|
| 98 |
+
|
| 99 |
+
out = self.conv1(x)
|
| 100 |
+
out = self.bn1(out)
|
| 101 |
+
out = self.relu(out)
|
| 102 |
+
|
| 103 |
+
out = self.conv2(out)
|
| 104 |
+
out = self.bn2(out)
|
| 105 |
+
out = self.relu(out)
|
| 106 |
+
|
| 107 |
+
out = self.conv3(out)
|
| 108 |
+
out = self.bn3(out)
|
| 109 |
+
|
| 110 |
+
if self.downsample is not None:
|
| 111 |
+
residual = self.downsample(x)
|
| 112 |
+
|
| 113 |
+
out += residual
|
| 114 |
+
out = self.relu(out)
|
| 115 |
+
|
| 116 |
+
return out
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class HighResolutionModule(nn.Module):
|
| 120 |
+
def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
|
| 121 |
+
num_channels, fuse_method, multi_scale_output=True):
|
| 122 |
+
super(HighResolutionModule, self).__init__()
|
| 123 |
+
self._check_branches(
|
| 124 |
+
num_branches, blocks, num_blocks, num_inchannels, num_channels)
|
| 125 |
+
|
| 126 |
+
self.num_inchannels = num_inchannels
|
| 127 |
+
self.fuse_method = fuse_method
|
| 128 |
+
self.num_branches = num_branches
|
| 129 |
+
|
| 130 |
+
self.multi_scale_output = multi_scale_output
|
| 131 |
+
|
| 132 |
+
self.branches = self._make_branches(
|
| 133 |
+
num_branches, blocks, num_blocks, num_channels)
|
| 134 |
+
self.fuse_layers = self._make_fuse_layers()
|
| 135 |
+
self.relu = nn.ReLU(inplace=True)
|
| 136 |
+
|
| 137 |
+
def _check_branches(self, num_branches, blocks, num_blocks,
|
| 138 |
+
num_inchannels, num_channels):
|
| 139 |
+
if num_branches != len(num_blocks):
|
| 140 |
+
error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(
|
| 141 |
+
num_branches, len(num_blocks))
|
| 142 |
+
logger.error(error_msg)
|
| 143 |
+
raise ValueError(error_msg)
|
| 144 |
+
|
| 145 |
+
if num_branches != len(num_channels):
|
| 146 |
+
error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(
|
| 147 |
+
num_branches, len(num_channels))
|
| 148 |
+
logger.error(error_msg)
|
| 149 |
+
raise ValueError(error_msg)
|
| 150 |
+
|
| 151 |
+
if num_branches != len(num_inchannels):
|
| 152 |
+
error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(
|
| 153 |
+
num_branches, len(num_inchannels))
|
| 154 |
+
logger.error(error_msg)
|
| 155 |
+
raise ValueError(error_msg)
|
| 156 |
+
|
| 157 |
+
def _make_one_branch(self, branch_index, block, num_blocks, num_channels,
|
| 158 |
+
stride=1):
|
| 159 |
+
downsample = None
|
| 160 |
+
if stride != 1 or \
|
| 161 |
+
self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:
|
| 162 |
+
downsample = nn.Sequential(
|
| 163 |
+
nn.Conv2d(self.num_inchannels[branch_index],
|
| 164 |
+
num_channels[branch_index] * block.expansion,
|
| 165 |
+
kernel_size=1, stride=stride, bias=False),
|
| 166 |
+
BatchNorm2d(num_channels[branch_index] * block.expansion,
|
| 167 |
+
momentum=BN_MOMENTUM),
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
layers = []
|
| 171 |
+
layers.append(block(self.num_inchannels[branch_index],
|
| 172 |
+
num_channels[branch_index], stride, downsample))
|
| 173 |
+
self.num_inchannels[branch_index] = \
|
| 174 |
+
num_channels[branch_index] * block.expansion
|
| 175 |
+
for i in range(1, num_blocks[branch_index]):
|
| 176 |
+
layers.append(block(self.num_inchannels[branch_index],
|
| 177 |
+
num_channels[branch_index]))
|
| 178 |
+
|
| 179 |
+
return nn.Sequential(*layers)
|
| 180 |
+
|
| 181 |
+
def _make_branches(self, num_branches, block, num_blocks, num_channels):
|
| 182 |
+
branches = []
|
| 183 |
+
|
| 184 |
+
for i in range(num_branches):
|
| 185 |
+
branches.append(
|
| 186 |
+
self._make_one_branch(i, block, num_blocks, num_channels))
|
| 187 |
+
|
| 188 |
+
return nn.ModuleList(branches)
|
| 189 |
+
|
| 190 |
+
def _make_fuse_layers(self):
|
| 191 |
+
if self.num_branches == 1:
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
num_branches = self.num_branches
|
| 195 |
+
num_inchannels = self.num_inchannels
|
| 196 |
+
fuse_layers = []
|
| 197 |
+
for i in range(num_branches if self.multi_scale_output else 1):
|
| 198 |
+
fuse_layer = []
|
| 199 |
+
for j in range(num_branches):
|
| 200 |
+
if j > i:
|
| 201 |
+
fuse_layer.append(nn.Sequential(
|
| 202 |
+
nn.Conv2d(num_inchannels[j],
|
| 203 |
+
num_inchannels[i],
|
| 204 |
+
1,
|
| 205 |
+
1,
|
| 206 |
+
0,
|
| 207 |
+
bias=False),
|
| 208 |
+
BatchNorm2d(num_inchannels[i], momentum=BN_MOMENTUM)))
|
| 209 |
+
# nn.Upsample(scale_factor=2**(j-i), mode='nearest')))
|
| 210 |
+
elif j == i:
|
| 211 |
+
fuse_layer.append(None)
|
| 212 |
+
else:
|
| 213 |
+
conv3x3s = []
|
| 214 |
+
for k in range(i - j):
|
| 215 |
+
if k == i - j - 1:
|
| 216 |
+
num_outchannels_conv3x3 = num_inchannels[i]
|
| 217 |
+
conv3x3s.append(nn.Sequential(
|
| 218 |
+
nn.Conv2d(num_inchannels[j],
|
| 219 |
+
num_outchannels_conv3x3,
|
| 220 |
+
3, 2, 1, bias=False),
|
| 221 |
+
BatchNorm2d(num_outchannels_conv3x3, momentum=BN_MOMENTUM)))
|
| 222 |
+
else:
|
| 223 |
+
num_outchannels_conv3x3 = num_inchannels[j]
|
| 224 |
+
conv3x3s.append(nn.Sequential(
|
| 225 |
+
nn.Conv2d(num_inchannels[j],
|
| 226 |
+
num_outchannels_conv3x3,
|
| 227 |
+
3, 2, 1, bias=False),
|
| 228 |
+
BatchNorm2d(num_outchannels_conv3x3,
|
| 229 |
+
momentum=BN_MOMENTUM),
|
| 230 |
+
nn.ReLU(inplace=True)))
|
| 231 |
+
fuse_layer.append(nn.Sequential(*conv3x3s))
|
| 232 |
+
fuse_layers.append(nn.ModuleList(fuse_layer))
|
| 233 |
+
|
| 234 |
+
return nn.ModuleList(fuse_layers)
|
| 235 |
+
|
| 236 |
+
def get_num_inchannels(self):
|
| 237 |
+
return self.num_inchannels
|
| 238 |
+
|
| 239 |
+
def forward(self, x):
|
| 240 |
+
if self.num_branches == 1:
|
| 241 |
+
return [self.branches[0](x[0])]
|
| 242 |
+
|
| 243 |
+
for i in range(self.num_branches):
|
| 244 |
+
x[i] = self.branches[i](x[i])
|
| 245 |
+
|
| 246 |
+
x_fuse = []
|
| 247 |
+
for i in range(len(self.fuse_layers)):
|
| 248 |
+
y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])
|
| 249 |
+
for j in range(1, self.num_branches):
|
| 250 |
+
if i == j:
|
| 251 |
+
y = y + x[j]
|
| 252 |
+
elif j > i:
|
| 253 |
+
y = y + F.interpolate(
|
| 254 |
+
self.fuse_layers[i][j](x[j]),
|
| 255 |
+
size=[x[i].shape[2], x[i].shape[3]],
|
| 256 |
+
mode='bilinear')
|
| 257 |
+
else:
|
| 258 |
+
y = y + self.fuse_layers[i][j](x[j])
|
| 259 |
+
x_fuse.append(self.relu(y))
|
| 260 |
+
|
| 261 |
+
return x_fuse
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
blocks_dict = {
|
| 265 |
+
'BASIC': BasicBlock,
|
| 266 |
+
'BOTTLENECK': Bottleneck
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class HighResolutionNet(nn.Module):
|
| 271 |
+
|
| 272 |
+
def __init__(self, config, **kwargs):
|
| 273 |
+
self.inplanes = 64
|
| 274 |
+
extra = config['MODEL']['EXTRA']
|
| 275 |
+
super(HighResolutionNet, self).__init__()
|
| 276 |
+
|
| 277 |
+
# stem net
|
| 278 |
+
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=2, padding=1,
|
| 279 |
+
bias=False)
|
| 280 |
+
self.bn1 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM)
|
| 281 |
+
self.conv2 = nn.Conv2d(self.inplanes, self.inplanes, kernel_size=3, stride=2, padding=1,
|
| 282 |
+
bias=False)
|
| 283 |
+
self.bn2 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM)
|
| 284 |
+
self.relu = nn.ReLU(inplace=True)
|
| 285 |
+
self.sf = nn.Softmax(dim=1)
|
| 286 |
+
self.layer1 = self._make_layer(Bottleneck, 64, 64, 4)
|
| 287 |
+
|
| 288 |
+
self.stage2_cfg = extra['STAGE2']
|
| 289 |
+
num_channels = self.stage2_cfg['NUM_CHANNELS']
|
| 290 |
+
block = blocks_dict[self.stage2_cfg['BLOCK']]
|
| 291 |
+
num_channels = [
|
| 292 |
+
num_channels[i] * block.expansion for i in range(len(num_channels))]
|
| 293 |
+
self.transition1 = self._make_transition_layer(
|
| 294 |
+
[256], num_channels)
|
| 295 |
+
self.stage2, pre_stage_channels = self._make_stage(
|
| 296 |
+
self.stage2_cfg, num_channels)
|
| 297 |
+
|
| 298 |
+
self.stage3_cfg = extra['STAGE3']
|
| 299 |
+
num_channels = self.stage3_cfg['NUM_CHANNELS']
|
| 300 |
+
block = blocks_dict[self.stage3_cfg['BLOCK']]
|
| 301 |
+
num_channels = [
|
| 302 |
+
num_channels[i] * block.expansion for i in range(len(num_channels))]
|
| 303 |
+
self.transition2 = self._make_transition_layer(
|
| 304 |
+
pre_stage_channels, num_channels)
|
| 305 |
+
self.stage3, pre_stage_channels = self._make_stage(
|
| 306 |
+
self.stage3_cfg, num_channels)
|
| 307 |
+
|
| 308 |
+
self.stage4_cfg = extra['STAGE4']
|
| 309 |
+
num_channels = self.stage4_cfg['NUM_CHANNELS']
|
| 310 |
+
block = blocks_dict[self.stage4_cfg['BLOCK']]
|
| 311 |
+
num_channels = [
|
| 312 |
+
num_channels[i] * block.expansion for i in range(len(num_channels))]
|
| 313 |
+
self.transition3 = self._make_transition_layer(
|
| 314 |
+
pre_stage_channels, num_channels)
|
| 315 |
+
self.stage4, pre_stage_channels = self._make_stage(
|
| 316 |
+
self.stage4_cfg, num_channels, multi_scale_output=True)
|
| 317 |
+
|
| 318 |
+
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
|
| 319 |
+
final_inp_channels = sum(pre_stage_channels) + self.inplanes
|
| 320 |
+
|
| 321 |
+
self.head = nn.Sequential(nn.Sequential(
|
| 322 |
+
nn.Conv2d(
|
| 323 |
+
in_channels=final_inp_channels,
|
| 324 |
+
out_channels=final_inp_channels,
|
| 325 |
+
kernel_size=1),
|
| 326 |
+
BatchNorm2d(final_inp_channels, momentum=BN_MOMENTUM),
|
| 327 |
+
nn.ReLU(inplace=True),
|
| 328 |
+
nn.Conv2d(
|
| 329 |
+
in_channels=final_inp_channels,
|
| 330 |
+
out_channels=config['MODEL']['NUM_JOINTS'],
|
| 331 |
+
kernel_size=extra['FINAL_CONV_KERNEL']),
|
| 332 |
+
nn.Softmax(dim=1)))
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _make_head(self, x, x_skip):
|
| 337 |
+
x = self.upsample(x)
|
| 338 |
+
x = torch.cat([x, x_skip], dim=1)
|
| 339 |
+
x = self.head(x)
|
| 340 |
+
|
| 341 |
+
return x
|
| 342 |
+
|
| 343 |
+
def _make_transition_layer(
|
| 344 |
+
self, num_channels_pre_layer, num_channels_cur_layer):
|
| 345 |
+
num_branches_cur = len(num_channels_cur_layer)
|
| 346 |
+
num_branches_pre = len(num_channels_pre_layer)
|
| 347 |
+
|
| 348 |
+
transition_layers = []
|
| 349 |
+
for i in range(num_branches_cur):
|
| 350 |
+
if i < num_branches_pre:
|
| 351 |
+
if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
|
| 352 |
+
transition_layers.append(nn.Sequential(
|
| 353 |
+
nn.Conv2d(num_channels_pre_layer[i],
|
| 354 |
+
num_channels_cur_layer[i],
|
| 355 |
+
3,
|
| 356 |
+
1,
|
| 357 |
+
1,
|
| 358 |
+
bias=False),
|
| 359 |
+
BatchNorm2d(
|
| 360 |
+
num_channels_cur_layer[i], momentum=BN_MOMENTUM),
|
| 361 |
+
nn.ReLU(inplace=True)))
|
| 362 |
+
else:
|
| 363 |
+
transition_layers.append(None)
|
| 364 |
+
else:
|
| 365 |
+
conv3x3s = []
|
| 366 |
+
for j in range(i + 1 - num_branches_pre):
|
| 367 |
+
inchannels = num_channels_pre_layer[-1]
|
| 368 |
+
outchannels = num_channels_cur_layer[i] \
|
| 369 |
+
if j == i - num_branches_pre else inchannels
|
| 370 |
+
conv3x3s.append(nn.Sequential(
|
| 371 |
+
nn.Conv2d(
|
| 372 |
+
inchannels, outchannels, 3, 2, 1, bias=False),
|
| 373 |
+
BatchNorm2d(outchannels, momentum=BN_MOMENTUM),
|
| 374 |
+
nn.ReLU(inplace=True)))
|
| 375 |
+
transition_layers.append(nn.Sequential(*conv3x3s))
|
| 376 |
+
|
| 377 |
+
return nn.ModuleList(transition_layers)
|
| 378 |
+
|
| 379 |
+
def _make_layer(self, block, inplanes, planes, blocks, stride=1):
|
| 380 |
+
downsample = None
|
| 381 |
+
if stride != 1 or inplanes != planes * block.expansion:
|
| 382 |
+
downsample = nn.Sequential(
|
| 383 |
+
nn.Conv2d(inplanes, planes * block.expansion,
|
| 384 |
+
kernel_size=1, stride=stride, bias=False),
|
| 385 |
+
BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
layers = []
|
| 389 |
+
layers.append(block(inplanes, planes, stride, downsample))
|
| 390 |
+
inplanes = planes * block.expansion
|
| 391 |
+
for i in range(1, blocks):
|
| 392 |
+
layers.append(block(inplanes, planes))
|
| 393 |
+
|
| 394 |
+
return nn.Sequential(*layers)
|
| 395 |
+
|
| 396 |
+
def _make_stage(self, layer_config, num_inchannels,
|
| 397 |
+
multi_scale_output=True):
|
| 398 |
+
num_modules = layer_config['NUM_MODULES']
|
| 399 |
+
num_branches = layer_config['NUM_BRANCHES']
|
| 400 |
+
num_blocks = layer_config['NUM_BLOCKS']
|
| 401 |
+
num_channels = layer_config['NUM_CHANNELS']
|
| 402 |
+
block = blocks_dict[layer_config['BLOCK']]
|
| 403 |
+
fuse_method = layer_config['FUSE_METHOD']
|
| 404 |
+
|
| 405 |
+
modules = []
|
| 406 |
+
for i in range(num_modules):
|
| 407 |
+
# multi_scale_output is only used last module
|
| 408 |
+
if not multi_scale_output and i == num_modules - 1:
|
| 409 |
+
reset_multi_scale_output = False
|
| 410 |
+
else:
|
| 411 |
+
reset_multi_scale_output = True
|
| 412 |
+
modules.append(
|
| 413 |
+
HighResolutionModule(num_branches,
|
| 414 |
+
block,
|
| 415 |
+
num_blocks,
|
| 416 |
+
num_inchannels,
|
| 417 |
+
num_channels,
|
| 418 |
+
fuse_method,
|
| 419 |
+
reset_multi_scale_output)
|
| 420 |
+
)
|
| 421 |
+
num_inchannels = modules[-1].get_num_inchannels()
|
| 422 |
+
|
| 423 |
+
return nn.Sequential(*modules), num_inchannels
|
| 424 |
+
|
| 425 |
+
def forward(self, x):
|
| 426 |
+
# h, w = x.size(2), x.size(3)
|
| 427 |
+
x = self.conv1(x)
|
| 428 |
+
x_skip = x.clone()
|
| 429 |
+
x = self.bn1(x)
|
| 430 |
+
x = self.relu(x)
|
| 431 |
+
x = self.conv2(x)
|
| 432 |
+
x = self.bn2(x)
|
| 433 |
+
x = self.relu(x)
|
| 434 |
+
x = self.layer1(x)
|
| 435 |
+
|
| 436 |
+
x_list = []
|
| 437 |
+
for i in range(self.stage2_cfg['NUM_BRANCHES']):
|
| 438 |
+
if self.transition1[i] is not None:
|
| 439 |
+
x_list.append(self.transition1[i](x))
|
| 440 |
+
else:
|
| 441 |
+
x_list.append(x)
|
| 442 |
+
y_list = self.stage2(x_list)
|
| 443 |
+
|
| 444 |
+
x_list = []
|
| 445 |
+
for i in range(self.stage3_cfg['NUM_BRANCHES']):
|
| 446 |
+
if self.transition2[i] is not None:
|
| 447 |
+
x_list.append(self.transition2[i](y_list[-1]))
|
| 448 |
+
else:
|
| 449 |
+
x_list.append(y_list[i])
|
| 450 |
+
y_list = self.stage3(x_list)
|
| 451 |
+
|
| 452 |
+
x_list = []
|
| 453 |
+
for i in range(self.stage4_cfg['NUM_BRANCHES']):
|
| 454 |
+
if self.transition3[i] is not None:
|
| 455 |
+
x_list.append(self.transition3[i](y_list[-1]))
|
| 456 |
+
else:
|
| 457 |
+
x_list.append(y_list[i])
|
| 458 |
+
x = self.stage4(x_list)
|
| 459 |
+
|
| 460 |
+
# Head Part
|
| 461 |
+
height, width = x[0].size(2), x[0].size(3)
|
| 462 |
+
x1 = F.interpolate(x[1], size=(height, width), mode='bilinear', align_corners=False)
|
| 463 |
+
x2 = F.interpolate(x[2], size=(height, width), mode='bilinear', align_corners=False)
|
| 464 |
+
x3 = F.interpolate(x[3], size=(height, width), mode='bilinear', align_corners=False)
|
| 465 |
+
x = torch.cat([x[0], x1, x2, x3], 1)
|
| 466 |
+
x = self._make_head(x, x_skip)
|
| 467 |
+
|
| 468 |
+
return x
|
| 469 |
+
|
| 470 |
+
def init_weights(self, pretrained=''):
|
| 471 |
+
for m in self.modules():
|
| 472 |
+
if isinstance(m, nn.Conv2d):
|
| 473 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 474 |
+
#nn.init.normal_(m.weight, std=0.001)
|
| 475 |
+
#nn.init.constant_(m.bias, 0)
|
| 476 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 477 |
+
nn.init.constant_(m.weight, 1)
|
| 478 |
+
nn.init.constant_(m.bias, 0)
|
| 479 |
+
if pretrained != '':
|
| 480 |
+
if os.path.isfile(pretrained):
|
| 481 |
+
pretrained_dict = torch.load(pretrained)
|
| 482 |
+
model_dict = self.state_dict()
|
| 483 |
+
pretrained_dict = {k: v for k, v in pretrained_dict.items()
|
| 484 |
+
if k in model_dict.keys()}
|
| 485 |
+
model_dict.update(pretrained_dict)
|
| 486 |
+
self.load_state_dict(model_dict)
|
| 487 |
+
else:
|
| 488 |
+
sys.exit(f'Weights {pretrained} not found.')
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def get_cls_net(config, pretrained='', **kwargs):
|
| 492 |
+
"""Create keypoint detection model with softmax activation"""
|
| 493 |
+
model = HighResolutionNet(config, **kwargs)
|
| 494 |
+
model.init_weights(pretrained)
|
| 495 |
+
return model
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def get_cls_net_l(config, pretrained='', **kwargs):
|
| 499 |
+
"""Create line detection model with sigmoid activation"""
|
| 500 |
+
model = HighResolutionNet(config, **kwargs)
|
| 501 |
+
model.init_weights(pretrained)
|
| 502 |
+
|
| 503 |
+
# After loading weights, replace just the activation function
|
| 504 |
+
# The saved model expects the nested Sequential structure
|
| 505 |
+
inner_seq = model.head[0]
|
| 506 |
+
# Replace softmax (index 4) with sigmoid
|
| 507 |
+
model.head[0][4] = nn.Sigmoid()
|
| 508 |
+
|
| 509 |
+
return model
|
| 510 |
+
|
| 511 |
+
# Simplified utility functions - removed complex Gaussian generation functions
|
| 512 |
+
# These were mainly used for training data generation, not inference
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
# generate_gaussian_array_vectorized_dist_l function removed - not used in current implementation
|
| 517 |
+
@torch.inference_mode()
|
| 518 |
+
def run_inference(model, input_tensor: torch.Tensor, device):
|
| 519 |
+
input_tensor = input_tensor.to(device).to(memory_format=torch.channels_last)
|
| 520 |
+
output = model.module().forward(input_tensor)
|
| 521 |
+
return output
|
| 522 |
+
|
| 523 |
+
def preprocess_batch_fast(frames):
|
| 524 |
+
"""Ultra-fast batch preprocessing using optimized tensor operations"""
|
| 525 |
+
target_size = (540, 960) # H, W format for model input
|
| 526 |
+
batch = []
|
| 527 |
+
for i, frame in enumerate(frames):
|
| 528 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 529 |
+
img = cv2.resize(frame_rgb, (target_size[1], target_size[0]))
|
| 530 |
+
img = img.astype(np.float32) / 255.0
|
| 531 |
+
img = np.transpose(img, (2, 0, 1)) # HWC -> CHW
|
| 532 |
+
batch.append(img)
|
| 533 |
+
batch = torch.from_numpy(np.stack(batch)).float()
|
| 534 |
+
|
| 535 |
+
return batch
|
| 536 |
+
|
| 537 |
+
def extract_keypoints_from_heatmap(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1):
|
| 538 |
+
"""Optimized keypoint extraction from heatmaps"""
|
| 539 |
+
batch_size, n_channels, height, width = heatmap.shape
|
| 540 |
+
|
| 541 |
+
# Find local maxima using max pooling (keep on GPU)
|
| 542 |
+
kernel = 3
|
| 543 |
+
pad = 1
|
| 544 |
+
max_pooled = F.max_pool2d(heatmap, kernel, stride=1, padding=pad)
|
| 545 |
+
local_maxima = (max_pooled == heatmap)
|
| 546 |
+
heatmap = heatmap * local_maxima
|
| 547 |
+
|
| 548 |
+
# Get top keypoints (keep on GPU longer)
|
| 549 |
+
scores, indices = torch.topk(heatmap.view(batch_size, n_channels, -1), max_keypoints, sorted=False)
|
| 550 |
+
y_coords = torch.div(indices, width, rounding_mode="floor")
|
| 551 |
+
x_coords = indices % width
|
| 552 |
+
|
| 553 |
+
# Optimized tensor operations
|
| 554 |
+
x_coords = x_coords * scale
|
| 555 |
+
y_coords = y_coords * scale
|
| 556 |
+
|
| 557 |
+
# Create result tensor directly on GPU
|
| 558 |
+
results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1)
|
| 559 |
+
|
| 560 |
+
return results
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def extract_keypoints_from_heatmap_fast(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1):
|
| 564 |
+
"""Ultra-fast keypoint extraction optimized for speed"""
|
| 565 |
+
batch_size, n_channels, height, width = heatmap.shape
|
| 566 |
+
|
| 567 |
+
# Simplified local maxima detection (faster but slightly less accurate)
|
| 568 |
+
max_pooled = F.max_pool2d(heatmap, 3, stride=1, padding=1)
|
| 569 |
+
local_maxima = (max_pooled == heatmap)
|
| 570 |
+
|
| 571 |
+
# Apply mask and get top keypoints in one go
|
| 572 |
+
masked_heatmap = heatmap * local_maxima
|
| 573 |
+
flat_heatmap = masked_heatmap.view(batch_size, n_channels, -1)
|
| 574 |
+
scores, indices = torch.topk(flat_heatmap, max_keypoints, dim=-1, sorted=False)
|
| 575 |
+
|
| 576 |
+
# Vectorized coordinate calculation
|
| 577 |
+
y_coords = torch.div(indices, width, rounding_mode="floor") * scale
|
| 578 |
+
x_coords = (indices % width) * scale
|
| 579 |
+
|
| 580 |
+
# Stack results efficiently
|
| 581 |
+
results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1)
|
| 582 |
+
return results
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def process_keypoints_vectorized(kp_coords, kp_threshold, w, h, batch_size):
|
| 586 |
+
"""Ultra-fast vectorized keypoint processing"""
|
| 587 |
+
batch_results = []
|
| 588 |
+
|
| 589 |
+
# Convert to numpy once for faster CPU operations
|
| 590 |
+
kp_np = kp_coords.cpu().numpy()
|
| 591 |
+
|
| 592 |
+
for batch_idx in range(batch_size):
|
| 593 |
+
kp_dict = {}
|
| 594 |
+
# Vectorized threshold check
|
| 595 |
+
valid_kps = kp_np[batch_idx, :, 0, 2] > kp_threshold
|
| 596 |
+
valid_indices = np.where(valid_kps)[0]
|
| 597 |
+
|
| 598 |
+
for ch_idx in valid_indices:
|
| 599 |
+
x = float(kp_np[batch_idx, ch_idx, 0, 0]) / w
|
| 600 |
+
y = float(kp_np[batch_idx, ch_idx, 0, 1]) / h
|
| 601 |
+
p = float(kp_np[batch_idx, ch_idx, 0, 2])
|
| 602 |
+
kp_dict[ch_idx + 1] = {'x': x, 'y': y, 'p': p}
|
| 603 |
+
|
| 604 |
+
batch_results.append(kp_dict)
|
| 605 |
+
|
| 606 |
+
return batch_results
|
| 607 |
+
|
| 608 |
+
def inference_batch(frames, model, kp_threshold, device, batch_size=8):
|
| 609 |
+
"""Optimized batch inference for multiple frames"""
|
| 610 |
+
results = []
|
| 611 |
+
num_frames = len(frames)
|
| 612 |
+
|
| 613 |
+
# Get the device from the model itself
|
| 614 |
+
model_device = next(model.parameters()).device
|
| 615 |
+
|
| 616 |
+
# Process all frames in optimally-sized batches
|
| 617 |
+
for i in range(0, num_frames, batch_size):
|
| 618 |
+
current_batch_size = min(batch_size, num_frames - i)
|
| 619 |
+
batch_frames = frames[i:i + current_batch_size]
|
| 620 |
+
|
| 621 |
+
# Fast preprocessing - create on CPU first
|
| 622 |
+
batch = preprocess_batch_fast(batch_frames)
|
| 623 |
+
b, c, h, w = batch.size()
|
| 624 |
+
|
| 625 |
+
# Move batch to model device
|
| 626 |
+
batch = batch.to(model_device)
|
| 627 |
+
|
| 628 |
+
with torch.no_grad():
|
| 629 |
+
heatmaps = model(batch)
|
| 630 |
+
|
| 631 |
+
# Ultra-fast keypoint extraction
|
| 632 |
+
kp_coords = extract_keypoints_from_heatmap_fast(heatmaps[:,:-1,:,:], scale=2, max_keypoints=1)
|
| 633 |
+
|
| 634 |
+
# Vectorized batch processing - no loops
|
| 635 |
+
batch_results = process_keypoints_vectorized(kp_coords, kp_threshold, 960, 540, current_batch_size)
|
| 636 |
+
results.extend(batch_results)
|
| 637 |
+
|
| 638 |
+
# Minimal cleanup
|
| 639 |
+
del heatmaps, kp_coords, batch
|
| 640 |
+
|
| 641 |
+
return results
|
| 642 |
+
|
| 643 |
+
# Keypoint mapping from detection indices to standard football pitch keypoint IDs
|
| 644 |
+
map_keypoints = {
|
| 645 |
+
1: 1, 2: 14, 3: 25, 4: 2, 5: 10, 6: 18, 7: 26, 8: 3, 9: 7, 10: 23,
|
| 646 |
+
11: 27, 20: 4, 21: 8, 22: 24, 23: 28, 24: 5, 25: 13, 26: 21, 27: 29,
|
| 647 |
+
28: 6, 29: 17, 30: 30, 31: 11, 32: 15, 33: 19, 34: 12, 35: 16, 36: 20,
|
| 648 |
+
45: 9, 50: 31, 52: 32, 57: 22
|
| 649 |
+
}
|
| 650 |
+
|
| 651 |
+
def get_mapped_keypoints(kp_points):
|
| 652 |
+
"""Apply keypoint mapping to detection results"""
|
| 653 |
+
mapped_points = {}
|
| 654 |
+
for key, value in kp_points.items():
|
| 655 |
+
if key in map_keypoints:
|
| 656 |
+
mapped_key = map_keypoints[key]
|
| 657 |
+
mapped_points[mapped_key] = value
|
| 658 |
+
# else:
|
| 659 |
+
# Keep unmapped keypoints with original key
|
| 660 |
+
# mapped_points[key] = value
|
| 661 |
+
return mapped_points
|
| 662 |
+
|
| 663 |
+
def process_batch_input(frames, model, kp_threshold, device, batch_size=16):
|
| 664 |
+
"""Process multiple input images in batch"""
|
| 665 |
+
# Batch inference
|
| 666 |
+
kp_results = inference_batch(frames, model, kp_threshold, device, batch_size)
|
| 667 |
+
kp_results = [get_mapped_keypoints(kp) for kp in kp_results]
|
| 668 |
+
|
| 669 |
+
return kp_results
|