-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathBilateralLayer.py
274 lines (208 loc) · 10.6 KB
/
BilateralLayer.py
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
import torch
import argparse
import numpy as np
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torchvision import datasets
import sys
import BilateralGrid as bs
##############################################################################
REQUIRES_CONF_GRAD = True
##############################################################################
class BilateralFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, image, pred, confidence, grid_params_arr, bs_params_arr ):
batch_size, channel_num, height, width = pred.size()
output = np.zeros((batch_size, height, width, channel_num), np.float32)
yhat_list = []
image_np = image.cpu().numpy().swapaxes(1, 2).swapaxes(2, 3)
pred_np = pred.cpu().numpy().swapaxes(1, 2).swapaxes(2, 3)
conf_np = confidence.cpu().numpy().squeeze(1)
grid_params = {}
grid_params['sigma_luma'] = grid_params_arr[0].data.item()
grid_params['sigma_chroma'] = grid_params_arr[1].data.item()
grid_params['sigma_spatial'] = grid_params_arr[2].data.item()
bs_params = {}
bs_params['lam'] = bs_params_arr[0].data.item()
bs_params['A_diag_min'] = bs_params_arr[1].data.item()
bs_params['cg_tol'] = bs_params_arr[2].data.item()
bs_params['cg_maxiter'] = bs_params_arr[2].data.item()
for i in range(batch_size):
curr_image = image_np[i, :, :, :]
curr_pred = pred_np[i, :, :, :]
curr_conf = conf_np[i, :, :]
im_shape = curr_pred.shape
grid = bs.BilateralGrid(curr_image*255.0, **grid_params)
curr_result, yhat = bs.solve(grid, curr_pred, curr_conf, bs_params, im_shape)
output[i, :, :, :] = curr_result
# print yhat.shape
yhat_list.append(yhat)
ctx.save_for_backward(image, pred, confidence, grid_params_arr, bs_params_arr)
ctx.intermediate_results = yhat_list
output = output.swapaxes(3, 2).swapaxes(2, 1)
return torch.Tensor(output).cuda(), confidence
@staticmethod
def backward(ctx, grad_output, grad_not_used ):
image, pred, confidence, grid_params_arr, bs_params_arr = ctx.saved_variables
grid_params = {}
grid_params['sigma_luma'] = grid_params_arr[0].data.item()
grid_params['sigma_chroma'] = grid_params_arr[1].data.item()
grid_params['sigma_spatial'] = grid_params_arr[2].data.item()
bs_params = {}
bs_params['lam'] = bs_params_arr[0].data.item()
bs_params['A_diag_min'] = bs_params_arr[1].data.item()
bs_params['cg_tol'] = bs_params_arr[2].data.item()
bs_params['cg_maxiter'] = bs_params_arr[2].data.item()
yhat_list = ctx.intermediate_results
batch_size, channel_num, height, width = pred.size()
# output gradient
pred_grad = np.zeros((batch_size, height, width, channel_num),
np.float32)
conf_grad = np.zeros((batch_size, height, width), np.float32)
image_np = image.data.cpu().numpy().swapaxes(1, 2).swapaxes(2, 3)
pred_np = pred.data.cpu().numpy().swapaxes(1, 2).swapaxes(2, 3)
conf_np = confidence.data.cpu().numpy().squeeze()
grad_output_np = grad_output.data.cpu().numpy().swapaxes(1, 2).swapaxes(2, 3)
for i in range(batch_size):
curr_image = image_np[i, :, :, :]
curr_grad = grad_output_np[i, :, :, :]
curr_conf = conf_np[i, :, :]
curr_yhat = yhat_list[i]
curr_pred = pred_np[i, :, :, :]
im_shape = curr_pred.shape
grid = bs.BilateralGrid(curr_image*255.0, **grid_params)
curr_pred_grad, curr_conf_grad = bs.solveForGrad(grid,
curr_grad, curr_conf, bs_params, im_shape,
curr_yhat, curr_pred)
pred_grad[i, :, :, :] = curr_pred_grad
if REQUIRES_CONF_GRAD == True:
conf_grad[i, :, :] = curr_conf_grad
pred_grad = pred_grad.swapaxes(3, 2).swapaxes(2, 1)
pred_grad = torch.Tensor(pred_grad).cuda()
pred_grad = Variable(pred_grad )
if REQUIRES_CONF_GRAD == True:
conf_grad = torch.Tensor(conf_grad).cuda().unsqueeze(1)
conf_grad = Variable(conf_grad)
else:
conf_grad = None
return None, pred_grad, conf_grad, None, None
class BilateralLayer(nn.Module):
def __init__(self, mode = 0, isCuda = True, gpuId = 0 ):
super(BilateralLayer, self).__init__()
if mode == 0:
# bilateral solver for albedo
self.grid_params = {
'sigma_luma' : 8, #Brightness bandwidth
'sigma_chroma': 2, # Color bandwidth
'sigma_spatial': 7# Spatial bandwidth
}
self.bs_params = {
'lam': 200, # The strength of the smoothness parameter
'A_diag_min': 1e-5, # Clamp the diagonal of the A diagonal in the Jacobi preconditioner.
'cg_tol': 1e-5, # The tolerance on the convergence in PCG
'cg_maxiter': 12 # The number of PCG iterations
}
elif mode == 1:
# bilateral solver for normal
self.grid_params = {
'sigma_luma' : 0.5, #Brightness bandwidth
'sigma_chroma': 0.5, # Color bandwidth
'sigma_spatial': 0.5# Spatial bandwidth
}
self.bs_params = {
'lam': 5, # The strength of the smoothness parameter
'A_diag_min': 1e-5, # Clamp the diagonal of the A diagonal in the Jacobi preconditioner.
'cg_tol': 1e-5, # The tolerance on the convergence in PCG
'cg_maxiter': 10 # The number of PCG iterations
}
elif mode == 2:
# bilateral solver for roughness
self.grid_params = {
'sigma_luma' : 8, #Brightness bandwidth
'sigma_chroma': 2, # Color bandwidth
'sigma_spatial': 8# Spatial bandwidth
}
self.bs_params = {
'lam': 300, # The strength of the smoothness parameter
'A_diag_min': 1e-5, # Clamp the diagonal of the A diagonal in the Jacobi preconditioner.
'cg_tol': 1e-5, # The tolerance on the convergence in PCG
'cg_maxiter': 10 # The number of PCG iterations
}
elif mode == 4:
# bilateral solver for normal
self.grid_params = {
'sigma_luma' : 4, #Brightness bandwidth
'sigma_chroma': 2, # Color bandwidth
'sigma_spatial': 4# Spatial bandwidth
}
self.bs_params = {
'lam': 100, # The strength of the smoothness parameter
'A_diag_min': 1e-5, # Clamp the diagonal of the A diagonal in the Jacobi preconditioner.
'cg_tol': 1e-5, # The tolerance on the convergence in PCG
'cg_maxiter': 10 # The number of PCG iterations
}
self.grid_params_arr = Variable(torch.FloatTensor(3) )
self.bs_params_arr = Variable(torch.FloatTensor(4) )
self.grid_params_arr[0] = self.grid_params['sigma_luma']
self.grid_params_arr[1] = self.grid_params['sigma_chroma']
self.grid_params_arr[2] = self.grid_params['sigma_spatial']
self.bs_params_arr[0] = self.bs_params['lam']
self.bs_params_arr[1] = self.bs_params['A_diag_min']
self.bs_params_arr[2] = self.bs_params['cg_tol']
self.bs_params_arr[3] = self.bs_params['cg_maxiter']
if isCuda:
self.grid_params_arr = self.grid_params_arr.cuda(gpuId )
self.bs_params_arr = self.bs_params_arr.cuda(gpuId )
self.grid_params_arr.requires_grad = False
self.bs_params_arr.requires_grad = False
self.pad1 = nn.ReplicationPad2d(1)
if mode == 2 or mode == 4:
self.conv1 = nn.Conv2d(in_channels = 4, out_channels=16, kernel_size=4, stride = 2, bias=True)
else:
self.conv1 = nn.Conv2d(in_channels = 6, out_channels = 16, kernel_size=4, stride = 2, bias=True)
self.gn1 = nn.GroupNorm(num_groups=2, num_channels = 16)
self.pad2 = nn.ReplicationPad2d(1)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=4, stride=2, bias=True)
self.gn2 = nn.GroupNorm(num_groups=2, num_channels=16)
self.dconv1 = nn.Conv2d(in_channels=16, out_channels=16,
kernel_size=3, stride=1, padding = 1, bias=True )
self.dgn1 = nn.GroupNorm(num_groups=2, num_channels=16 )
self.dconv2 = nn.Conv2d(in_channels=32, out_channels=16, kernel_size=3,
stride=1, padding = 1, bias=True)
self.dgn2 = nn.GroupNorm(num_groups=2, num_channels = 16 )
self.dpad3 = nn.ReplicationPad2d(1)
self.dconvFinal = nn.Conv2d(in_channels = 16, out_channels = 1, kernel_size = 3, stride=1, bias=True)
def computePadding(self, os, ns):
assert(os <= ns )
gap = ns - os
if gap % 2 == 0:
return [int(gap/2), int(gap / 2) ]
else:
return [int((gap+1) / 2), int((gap-1) / 2) ]
def forward(self, image, feature, pred ):
scale, _ = torch.max(image, dim=1, keepdim = True)
scale, _ = torch.max(scale, dim=2, keepdim = True)
scale, _ = torch.max(scale, dim=3, keepdim = True)
scale = torch.clamp(scale, 1e-5, 1)
image = image / scale.expand_as(image )
scale, _ = torch.max(feature, dim=1, keepdim = True)
scale, _ = torch.max(scale, dim=2, keepdim = True)
scale, _ = torch.max(scale, dim=3, keepdim = True)
scale = torch.clamp(scale, 1e-5, 1)
feature = feature / scale.expand_as(image )
inputBatch = torch.cat([image, pred ], dim=1).detach()
x1 = F.relu(self.gn1(self.conv1(self.pad1(inputBatch) ) ), True)
x2 = F.relu(self.gn2(self.conv2(self.pad2(x1) ) ), True)
dx1 = F.relu(self.dgn1(self.dconv1(x2 ) ), True)
dx1 = F.interpolate(dx1, [x1.size(2), x1.size(3)], mode='bilinear')
xin2 = torch.cat([dx1, x1], dim=1)
dx2 = F.relu(self.dgn2(self.dconv2(xin2 ) ), True)
dx2 = F.interpolate(dx2, [inputBatch.size(2), inputBatch.size(3)],
mode='bilinear' )
conf = 0.5* (torch.tanh(self.dconvFinal(self.dpad3(dx2) ) ) + 1 )
conf = conf / torch.clamp(conf.max(), min = 1e-5)
return BilateralFunction.apply(feature.detach(), pred, conf, self.grid_params_arr, self.bs_params_arr )