Repository navigation
Expand file tree
/
Copy pathdfnet.py
More file actions
executable file
·273 lines (230 loc) · 10.7 KB
/
Copy pathdfnet.py
File metadata and controls
executable file
·273 lines (230 loc) · 10.7 KB
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
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import models
from typing import List
# VGG-16 Layer Names and Channels
vgg16_layers = {
"conv1_1": 64,
"relu1_1": 64,
"conv1_2": 64,
"relu1_2": 64,
"pool1": 64,
"conv2_1": 128,
"relu2_1": 128,
"conv2_2": 128,
"relu2_2": 128,
"pool2": 128,
"conv3_1": 256,
"relu3_1": 256,
"conv3_2": 256,
"relu3_2": 256,
"conv3_3": 256,
"relu3_3": 256,
"pool3": 256,
"conv4_1": 512,
"relu4_1": 512,
"conv4_2": 512,
"relu4_2": 512,
"conv4_3": 512,
"relu4_3": 512,
"pool4": 512,
"conv5_1": 512,
"relu5_1": 512,
"conv5_2": 512,
"relu5_2": 512,
"conv5_3": 512,
"relu5_3": 512,
"pool5": 512,
}
class AdaptLayers(nn.Module):
"""Small adaptation layers.
"""
def __init__(self, hypercolumn_layers: List[str], output_dim: int = 128):
"""Initialize one adaptation layer for every extraction point.
Args:
hypercolumn_layers: The list of the hypercolumn layer names.
output_dim: The output channel dimension.
"""
super(AdaptLayers, self).__init__()
self.layers = []
channel_sizes = [vgg16_layers[name] for name in hypercolumn_layers]
for i, l in enumerate(channel_sizes):
layer = nn.Sequential(
nn.Conv2d(l, 64, kernel_size=1, stride=1, padding=0),
nn.ReLU(),
nn.Conv2d(64, output_dim, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(output_dim),
)
self.layers.append(layer)
self.add_module("adapt_layer_{}".format(i), layer) # ex: adapt_layer_0
def forward(self, features: List[torch.tensor]):
"""Apply adaptation layers. # here is list of three levels of features
"""
for i, _ in enumerate(features):
features[i] = getattr(self, "adapt_layer_{}".format(i))(features[i])
return features
class DFNet(nn.Module):
''' DFNet implementation '''
default_conf = {
'hypercolumn_layers': ["conv1_2", "conv3_3", "conv5_3"],
'output_dim': 128,
}
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
def __init__(self, feat_dim=12, places365_model_path=''):
super(DFNet, self).__init__()
self.layer_to_index = {k: v for v, k in enumerate(vgg16_layers.keys())}
self.hypercolumn_indices = [self.layer_to_index[n] for n in self.default_conf['hypercolumn_layers']] # [2, 14, 28]
# Initialize architecture
vgg16 = models.vgg16(pretrained=True)
self.encoder = nn.Sequential(*list(vgg16.features.children()))
self.scales = []
current_scale = 0
for i, layer in enumerate(self.encoder):
if isinstance(layer, torch.nn.MaxPool2d):
current_scale += 1
if i in self.hypercolumn_indices:
self.scales.append(2**current_scale)
## adaptation layers, see off branches from fig.3 in S2DNet paper
self.adaptation_layers = AdaptLayers(self.default_conf['hypercolumn_layers'], self.default_conf['output_dim'])
# pose regression layers
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.fc_pose = nn.Linear(512, feat_dim)
def forward(self, x, return_feature=False, isSingleStream=False, return_pose=True, upsampleH=240, upsampleW=427):
'''
inference DFNet. It can regress camera pose as well as extract intermediate layer features.
:param x: image blob (2B x C x H x W) two stream or (B x C x H x W) single stream
:param return_feature: whether to return features as output
:param isSingleStream: whether it's an single stream inference or siamese network inference
:param upsampleH: feature upsample size H
:param upsampleW: feature upsample size W
:return feature_maps: (2, [B, C, H, W]) or (1, [B, C, H, W]) or None
:return predict: [2B, 12] or [B, 12]
'''
# normalize input data
mean, std = x.new_tensor(self.mean), x.new_tensor(self.std)
x = (x - mean[:, None, None]) / std[:, None, None]
### encoder ###
feature_maps = []
for i in range(len(self.encoder)):
x = self.encoder[i](x)
if i in self.hypercolumn_indices:
feature = x.clone()
feature_maps.append(feature)
if i==self.hypercolumn_indices[-1]:
if return_pose==False:
predict = None
break
### extract and process intermediate features ###
if return_feature:
feature_maps = self.adaptation_layers(feature_maps) # (3, [B, C, H', W']), H', W' are different in each layer
if isSingleStream: # not siamese network style inference
feature_stacks = []
for f in feature_maps:
feature_stacks.append(torch.nn.UpsamplingBilinear2d(size=(upsampleH, upsampleW))(f))
feature_maps = [torch.stack(feature_stacks)] # (1, [3, B, C, H, W])
else: # siamese network style inference
feature_stacks_t = []
feature_stacks_r = []
for f in feature_maps:
# split real and nerf batches
batch = f.shape[0] # should be target batch_size + rgb batch_size
feature_t = f[:batch//2]
feature_r = f[batch//2:]
feature_stacks_t.append(torch.nn.UpsamplingBilinear2d(size=(upsampleH, upsampleW))(feature_t)) # GT img
feature_stacks_r.append(torch.nn.UpsamplingBilinear2d(size=(upsampleH, upsampleW))(feature_r)) # render img
feature_stacks_t = torch.stack(feature_stacks_t) # [3, B, C, H, W]
feature_stacks_r = torch.stack(feature_stacks_r) # [3, B, C, H, W]
feature_maps = [feature_stacks_t, feature_stacks_r] # (2, [3, B, C, H, W])
else:
feature_maps = None
if return_pose==False:
return feature_maps, predict
### pose regression head ###
x = self.avgpool(x)
x = x.reshape(x.size(0), -1)
predict = self.fc_pose(x)
return feature_maps, predict
class DFNet_s(nn.Module):
''' A slight accelerated version of DFNet, we experimentally found this version's performance is similar to original DFNet but inferences faster '''
default_conf = {
'hypercolumn_layers': ["conv1_2"],
'output_dim': 128,
}
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
def __init__(self, feat_dim=12, places365_model_path=''):
super(DFNet_s, self).__init__()
self.layer_to_index = {k: v for v, k in enumerate(vgg16_layers.keys())}
self.hypercolumn_indices = [self.layer_to_index[n] for n in self.default_conf['hypercolumn_layers']] # [2, 14, 28]
# Initialize architecture
vgg16 = models.vgg16(pretrained=True)
self.encoder = nn.Sequential(*list(vgg16.features.children()))
self.scales = []
current_scale = 0
for i, layer in enumerate(self.encoder):
if isinstance(layer, torch.nn.MaxPool2d):
current_scale += 1
if i in self.hypercolumn_indices:
self.scales.append(2**current_scale)
## adaptation layers, see off branches from fig.3 in S2DNet paper
self.adaptation_layers = AdaptLayers(self.default_conf['hypercolumn_layers'], self.default_conf['output_dim'])
# pose regression layers
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.fc_pose = nn.Linear(512, feat_dim)
def forward(self, x, return_feature=False, isSingleStream=False, return_pose=True, upsampleH=240, upsampleW=427):
'''
inference DFNet_s. It can regress camera pose as well as extract intermediate layer features.
:param x: image blob (2B x C x H x W) two stream or (B x C x H x W) single stream
:param return_feature: whether to return features as output
:param isSingleStream: whether it's an single stream inference or siamese network inference
:param upsampleH: feature upsample size H
:param upsampleW: feature upsample size W
:return feature_maps: (2, [B, C, H, W]) or (1, [B, C, H, W]) or None
:return predict: [2B, 12] or [B, 12]
'''
# normalize input data
mean, std = x.new_tensor(self.mean), x.new_tensor(self.std)
x = (x - mean[:, None, None]) / std[:, None, None]
### encoder ###
feature_maps = []
for i in range(len(self.encoder)):
x = self.encoder[i](x)
if i in self.hypercolumn_indices:
feature = x.clone()
feature_maps.append(feature)
if i==self.hypercolumn_indices[-1]:
if return_pose==False:
predict = None
break
### extract and process intermediate features ###
if return_feature:
feature_maps = self.adaptation_layers(feature_maps) # (3, [B, C, H', W']), H', W' are different in each layer
if isSingleStream: # not siamese network style inference
feature_stacks = []
for f in feature_maps:
feature_stacks.append(torch.nn.UpsamplingBilinear2d(size=(upsampleH, upsampleW))(f))
feature_maps = [torch.stack(feature_stacks)] # (1, [3, B, C, H, W])
else: # siamese network style inference
feature_stacks_t = []
feature_stacks_r = []
for f in feature_maps:
# split real and nerf batches
batch = f.shape[0] # should be target batch_size + rgb batch_size
feature_t = f[:batch//2]
feature_r = f[batch//2:]
feature_stacks_t.append(torch.nn.UpsamplingBilinear2d(size=(upsampleH, upsampleW))(feature_t)) # GT img
feature_stacks_r.append(torch.nn.UpsamplingBilinear2d(size=(upsampleH, upsampleW))(feature_r)) # render img
feature_stacks_t = torch.stack(feature_stacks_t) # [3, B, C, H, W]
feature_stacks_r = torch.stack(feature_stacks_r) # [3, B, C, H, W]
feature_maps = [feature_stacks_t, feature_stacks_r] # (2, [3, B, C, H, W])
else:
feature_maps = None
if return_pose==False:
return feature_maps, predict
### pose regression head ###
x = self.avgpool(x)
x = x.reshape(x.size(0), -1)
predict = self.fc_pose(x)
return feature_maps, predict