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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn
|
2 |
+
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import torch
|
5 |
+
import cv2
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
from models.resnet import resnet34
|
9 |
+
from models.layers.residual import Res2dBlock,Res1dBlock,DownRes2dBlock
|
10 |
+
|
11 |
+
from sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d
|
12 |
+
|
13 |
+
|
14 |
+
def myres2Dblock(indim,outdim,k_size = 3,padding = 1, normalize = "batch",nonlinearity = "relu",order = "NACNAC"):
|
15 |
+
return Res2dBlock(indim,outdim,k_size,padding,activation_norm_type=normalize,nonlinearity=nonlinearity,inplace_nonlinearity=True,order = order)
|
16 |
+
|
17 |
+
def myres1Dblock(indim,outdim,k_size = 3,padding = 1, normalize = "batch",nonlinearity = "relu",order = "NACNAC"):
|
18 |
+
return Res1dBlock(indim,outdim,k_size,padding,activation_norm_type=normalize,nonlinearity=nonlinearity,inplace_nonlinearity=True,order = order)
|
19 |
+
|
20 |
+
def mydownres2Dblock(indim,outdim,k_size = 3,padding = 1, normalize = "batch",nonlinearity = "leakyrelu",order = "NACNAC"):
|
21 |
+
return DownRes2dBlock(indim,outdim,k_size,padding=padding,activation_norm_type=normalize,nonlinearity=nonlinearity,inplace_nonlinearity=True,order = order)
|
22 |
+
|
23 |
+
def gaussian2kp(heatmap):
|
24 |
+
"""
|
25 |
+
Extract the mean and from a heatmap
|
26 |
+
"""
|
27 |
+
shape = heatmap.shape
|
28 |
+
heatmap = heatmap.unsqueeze(-1)
|
29 |
+
grid = make_coordinate_grid(shape[2:], heatmap.type()).unsqueeze_(0).unsqueeze_(0)
|
30 |
+
value = (heatmap * grid).sum(dim=(2, 3))
|
31 |
+
kp = {'value': value}
|
32 |
+
|
33 |
+
return kp
|
34 |
+
|
35 |
+
def kp2gaussian(kp, spatial_size, kp_variance):
|
36 |
+
"""
|
37 |
+
Transform a keypoint into gaussian like representation
|
38 |
+
"""
|
39 |
+
mean = kp['value'] #bs*numkp*2
|
40 |
+
|
41 |
+
coordinate_grid = make_coordinate_grid(spatial_size, mean.type()) #h*w*2
|
42 |
+
number_of_leading_dimensions = len(mean.shape) - 1
|
43 |
+
shape = (1,) * number_of_leading_dimensions + coordinate_grid.shape #1*1*h*w*2
|
44 |
+
coordinate_grid = coordinate_grid.view(*shape)
|
45 |
+
repeats = mean.shape[:number_of_leading_dimensions] + (1, 1, 1)
|
46 |
+
coordinate_grid = coordinate_grid.repeat(*repeats) #bs*numkp*h*w*2
|
47 |
+
|
48 |
+
# Preprocess kp shape
|
49 |
+
shape = mean.shape[:number_of_leading_dimensions] + (1, 1, 2)
|
50 |
+
mean = mean.view(*shape)
|
51 |
+
|
52 |
+
mean_sub = (coordinate_grid - mean)
|
53 |
+
|
54 |
+
out = torch.exp(-0.5 * (mean_sub ** 2).sum(-1) / kp_variance)
|
55 |
+
|
56 |
+
return out
|
57 |
+
|
58 |
+
|
59 |
+
def make_coordinate_grid(spatial_size, type):
|
60 |
+
"""
|
61 |
+
Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
|
62 |
+
"""
|
63 |
+
h, w = spatial_size
|
64 |
+
x = torch.arange(w).type(type)
|
65 |
+
y = torch.arange(h).type(type)
|
66 |
+
|
67 |
+
x = (2 * (x / (w - 1)) - 1)
|
68 |
+
y = (2 * (y / (h - 1)) - 1)
|
69 |
+
|
70 |
+
yy = y.view(-1, 1).repeat(1, w)
|
71 |
+
xx = x.view(1, -1).repeat(h, 1)
|
72 |
+
|
73 |
+
meshed = torch.cat([xx.unsqueeze_(2), yy.unsqueeze_(2)], 2)
|
74 |
+
|
75 |
+
return meshed
|
76 |
+
|
77 |
+
|
78 |
+
class ResBlock2d(nn.Module):
|
79 |
+
"""
|
80 |
+
Res block, preserve spatial resolution.
|
81 |
+
"""
|
82 |
+
|
83 |
+
def __init__(self, in_features, kernel_size, padding):
|
84 |
+
super(ResBlock2d, self).__init__()
|
85 |
+
self.conv1 = nn.Conv2d(in_channels=in_features, out_channels=in_features, kernel_size=kernel_size,
|
86 |
+
padding=padding)
|
87 |
+
self.conv2 = nn.Conv2d(in_channels=in_features, out_channels=in_features, kernel_size=kernel_size,
|
88 |
+
padding=padding)
|
89 |
+
self.norm1 = BatchNorm2d(in_features, affine=True)
|
90 |
+
self.norm2 = BatchNorm2d(in_features, affine=True)
|
91 |
+
|
92 |
+
def forward(self, x):
|
93 |
+
out = self.norm1(x)
|
94 |
+
out = F.relu(out,inplace=True)
|
95 |
+
out = self.conv1(out)
|
96 |
+
out = self.norm2(out)
|
97 |
+
out = F.relu(out,inplace=True)
|
98 |
+
out = self.conv2(out)
|
99 |
+
out += x
|
100 |
+
return out
|
101 |
+
|
102 |
+
|
103 |
+
class UpBlock2d(nn.Module):
|
104 |
+
"""
|
105 |
+
Upsampling block for use in decoder.
|
106 |
+
"""
|
107 |
+
|
108 |
+
def __init__(self, in_features, out_features, kernel_size=3, padding=1, groups=1):
|
109 |
+
super(UpBlock2d, self).__init__()
|
110 |
+
|
111 |
+
self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size,
|
112 |
+
padding=padding, groups=groups)
|
113 |
+
self.norm = BatchNorm2d(out_features, affine=True)
|
114 |
+
|
115 |
+
def forward(self, x):
|
116 |
+
out = F.interpolate(x, scale_factor=2)
|
117 |
+
del x
|
118 |
+
out = self.conv(out)
|
119 |
+
out = self.norm(out)
|
120 |
+
out = F.relu(out,inplace=True)
|
121 |
+
return out
|
122 |
+
|
123 |
+
|
124 |
+
class DownBlock2d(nn.Module):
|
125 |
+
"""
|
126 |
+
Downsampling block for use in encoder.
|
127 |
+
"""
|
128 |
+
|
129 |
+
def __init__(self, in_features, out_features, kernel_size=3, padding=1, groups=1):
|
130 |
+
super(DownBlock2d, self).__init__()
|
131 |
+
self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size,
|
132 |
+
padding=padding, groups=groups)
|
133 |
+
self.norm = BatchNorm2d(out_features, affine=True)
|
134 |
+
self.pool = nn.AvgPool2d(kernel_size=(2, 2))
|
135 |
+
|
136 |
+
def forward(self, x):
|
137 |
+
out = self.conv(x)
|
138 |
+
del x
|
139 |
+
out = self.norm(out)
|
140 |
+
out = F.relu(out,inplace=True)
|
141 |
+
out = self.pool(out)
|
142 |
+
return out
|
143 |
+
|
144 |
+
|
145 |
+
class SameBlock2d(nn.Module):
|
146 |
+
"""
|
147 |
+
Simple block, preserve spatial resolution.
|
148 |
+
"""
|
149 |
+
|
150 |
+
def __init__(self, in_features, out_features, groups=1, kernel_size=3, padding=1):
|
151 |
+
super(SameBlock2d, self).__init__()
|
152 |
+
self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features,
|
153 |
+
kernel_size=kernel_size, padding=padding, groups=groups)
|
154 |
+
self.norm = BatchNorm2d(out_features, affine=True)
|
155 |
+
|
156 |
+
def forward(self, x):
|
157 |
+
out = self.conv(x)
|
158 |
+
out = self.norm(out)
|
159 |
+
out = F.relu(out,inplace=True)
|
160 |
+
return out
|
161 |
+
|
162 |
+
|
163 |
+
class Encoder(nn.Module):
|
164 |
+
"""
|
165 |
+
Hourglass Encoder
|
166 |
+
"""
|
167 |
+
|
168 |
+
def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256):
|
169 |
+
super(Encoder, self).__init__()
|
170 |
+
|
171 |
+
down_blocks = []
|
172 |
+
for i in range(num_blocks):
|
173 |
+
down_blocks.append(DownBlock2d(in_features if i == 0 else min(max_features, block_expansion * (2 ** i)),
|
174 |
+
min(max_features, block_expansion * (2 ** (i + 1))),
|
175 |
+
kernel_size=3, padding=1))
|
176 |
+
self.down_blocks = nn.ModuleList(down_blocks)
|
177 |
+
|
178 |
+
def forward(self, x):
|
179 |
+
outs = [x]
|
180 |
+
for down_block in self.down_blocks:
|
181 |
+
outs.append(down_block(outs[-1]))
|
182 |
+
return outs
|
183 |
+
|
184 |
+
class Decoder(nn.Module):
|
185 |
+
"""
|
186 |
+
Hourglass Decoder
|
187 |
+
"""
|
188 |
+
|
189 |
+
def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256):
|
190 |
+
super(Decoder, self).__init__()
|
191 |
+
|
192 |
+
up_blocks = []
|
193 |
+
|
194 |
+
for i in range(num_blocks)[::-1]:
|
195 |
+
in_filters = (1 if i == num_blocks - 1 else 2) * min(max_features, block_expansion * (2 ** (i + 1)))
|
196 |
+
out_filters = min(max_features, block_expansion * (2 ** i))
|
197 |
+
up_blocks.append(UpBlock2d(in_filters, out_filters, kernel_size=3, padding=1))
|
198 |
+
|
199 |
+
self.up_blocks = nn.ModuleList(up_blocks)
|
200 |
+
self.out_filters = block_expansion + in_features
|
201 |
+
|
202 |
+
def forward(self, x):
|
203 |
+
out = x.pop()
|
204 |
+
for up_block in self.up_blocks:
|
205 |
+
out = up_block(out)
|
206 |
+
skip = x.pop()
|
207 |
+
out = torch.cat([out, skip], dim=1)
|
208 |
+
return out
|
209 |
+
|
210 |
+
class Hourglass(nn.Module):
|
211 |
+
"""
|
212 |
+
Hourglass architecture.
|
213 |
+
"""
|
214 |
+
|
215 |
+
def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256):
|
216 |
+
super(Hourglass, self).__init__()
|
217 |
+
self.encoder = Encoder(block_expansion, in_features, num_blocks, max_features)
|
218 |
+
self.decoder = Decoder(block_expansion, in_features, num_blocks, max_features)
|
219 |
+
self.out_filters = self.decoder.out_filters
|
220 |
+
|
221 |
+
def forward(self, x):
|
222 |
+
return self.decoder(self.encoder(x))
|
223 |
+
|
224 |
+
class AntiAliasInterpolation2d(nn.Module):
|
225 |
+
"""
|
226 |
+
Band-limited downsampling, for better preservation of the input signal.
|
227 |
+
"""
|
228 |
+
def __init__(self, channels, scale):
|
229 |
+
super(AntiAliasInterpolation2d, self).__init__()
|
230 |
+
sigma = (1 / scale - 1) / 2
|
231 |
+
kernel_size = 2 * round(sigma * 4) + 1
|
232 |
+
self.ka = kernel_size // 2
|
233 |
+
self.kb = self.ka - 1 if kernel_size % 2 == 0 else self.ka
|
234 |
+
|
235 |
+
|
236 |
+
kernel_size = [kernel_size, kernel_size]
|
237 |
+
sigma = [sigma, sigma]
|
238 |
+
# The gaussian kernel is the product of the
|
239 |
+
# gaussian function of each dimension.
|
240 |
+
kernel = 1
|
241 |
+
meshgrids = torch.meshgrid(
|
242 |
+
[
|
243 |
+
torch.arange(size, dtype=torch.float32)
|
244 |
+
for size in kernel_size
|
245 |
+
]
|
246 |
+
)
|
247 |
+
for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
|
248 |
+
mean = (size - 1) / 2
|
249 |
+
kernel *= torch.exp(-(mgrid - mean) ** 2 / (2 * std ** 2))
|
250 |
+
|
251 |
+
# Make sure sum of values in gaussian kernel equals 1.
|
252 |
+
kernel = kernel / torch.sum(kernel)
|
253 |
+
# Reshape to depthwise convolutional weight
|
254 |
+
kernel = kernel.view(1, 1, *kernel.size())
|
255 |
+
kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
|
256 |
+
|
257 |
+
self.register_buffer('weight', kernel)
|
258 |
+
self.groups = channels
|
259 |
+
self.scale = scale
|
260 |
+
|
261 |
+
def forward(self, input):
|
262 |
+
if self.scale == 1.0:
|
263 |
+
return input
|
264 |
+
|
265 |
+
out = F.pad(input, (self.ka, self.kb, self.ka, self.kb))
|
266 |
+
out = F.conv2d(out, weight=self.weight, groups=self.groups)
|
267 |
+
out = F.interpolate(out, scale_factor=(self.scale, self.scale))
|
268 |
+
|
269 |
+
return out
|
270 |
+
|
271 |
+
def draw_annotation_box( image, rotation_vector, translation_vector, color=(255, 255, 255), line_width=2):
|
272 |
+
"""Draw a 3D box as annotation of pose"""
|
273 |
+
|
274 |
+
camera_matrix = np.array(
|
275 |
+
[[233.333, 0, 128],
|
276 |
+
[0, 233.333, 128],
|
277 |
+
[0, 0, 1]], dtype="double")
|
278 |
+
|
279 |
+
dist_coeefs = np.zeros((4, 1))
|
280 |
+
|
281 |
+
point_3d = []
|
282 |
+
rear_size = 75
|
283 |
+
rear_depth = 0
|
284 |
+
point_3d.append((-rear_size, -rear_size, rear_depth))
|
285 |
+
point_3d.append((-rear_size, rear_size, rear_depth))
|
286 |
+
point_3d.append((rear_size, rear_size, rear_depth))
|
287 |
+
point_3d.append((rear_size, -rear_size, rear_depth))
|
288 |
+
point_3d.append((-rear_size, -rear_size, rear_depth))
|
289 |
+
|
290 |
+
front_size = 100
|
291 |
+
front_depth = 100
|
292 |
+
point_3d.append((-front_size, -front_size, front_depth))
|
293 |
+
point_3d.append((-front_size, front_size, front_depth))
|
294 |
+
point_3d.append((front_size, front_size, front_depth))
|
295 |
+
point_3d.append((front_size, -front_size, front_depth))
|
296 |
+
point_3d.append((-front_size, -front_size, front_depth))
|
297 |
+
point_3d = np.array(point_3d, dtype=np.float64).reshape(-1, 3)
|
298 |
+
|
299 |
+
# Map to 2d image points
|
300 |
+
(point_2d, _) = cv2.projectPoints(point_3d,
|
301 |
+
rotation_vector,
|
302 |
+
translation_vector,
|
303 |
+
camera_matrix,
|
304 |
+
dist_coeefs)
|
305 |
+
point_2d = np.int32(point_2d.reshape(-1, 2))
|
306 |
+
|
307 |
+
# Draw all the lines
|
308 |
+
cv2.polylines(image, [point_2d], True, color, line_width, cv2.LINE_AA)
|
309 |
+
cv2.line(image, tuple(point_2d[1]), tuple(
|
310 |
+
point_2d[6]), color, line_width, cv2.LINE_AA)
|
311 |
+
cv2.line(image, tuple(point_2d[2]), tuple(
|
312 |
+
point_2d[7]), color, line_width, cv2.LINE_AA)
|
313 |
+
cv2.line(image, tuple(point_2d[3]), tuple(
|
314 |
+
point_2d[8]), color, line_width, cv2.LINE_AA)
|
315 |
+
|
316 |
+
|
317 |
+
|
318 |
+
class up_sample(nn.Module):
|
319 |
+
def __init__(self, scale_factor):
|
320 |
+
super(up_sample, self).__init__()
|
321 |
+
self.interp = nn.functional.interpolate
|
322 |
+
self.scale_factor = scale_factor
|
323 |
+
|
324 |
+
def forward(self, x):
|
325 |
+
x = self.interp(x, scale_factor=self.scale_factor,mode = 'linear',align_corners = True)
|
326 |
+
return x
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
+
class MyResNet34(nn.Module):
|
331 |
+
def __init__(self,embedding_dim,input_channel = 3):
|
332 |
+
super(MyResNet34, self).__init__()
|
333 |
+
self.resnet = resnet34(norm_layer = BatchNorm2d,num_classes=embedding_dim,input_channel = input_channel)
|
334 |
+
def forward(self, x):
|
335 |
+
return self.resnet(x)
|
336 |
+
|
337 |
+
|
338 |
+
|
339 |
+
class ImagePyramide(torch.nn.Module):
|
340 |
+
"""
|
341 |
+
Create image pyramide for computing pyramide perceptual loss. See Sec 3.3
|
342 |
+
"""
|
343 |
+
def __init__(self, scales, num_channels):
|
344 |
+
super(ImagePyramide, self).__init__()
|
345 |
+
downs = {}
|
346 |
+
for scale in scales:
|
347 |
+
downs[str(scale).replace('.', '-')] = AntiAliasInterpolation2d(num_channels, scale)
|
348 |
+
self.downs = nn.ModuleDict(downs)
|
349 |
+
|
350 |
+
def forward(self, x):
|
351 |
+
out_dict = {}
|
352 |
+
for scale, down_module in self.downs.items():
|
353 |
+
out_dict['prediction_' + str(scale).replace('-', '.')] = down_module(x)
|
354 |
+
return out_dict
|