-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
315 lines (268 loc) · 12 KB
/
utils.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import torch
import torch.nn as nn
from pointnet2 import pointnet2_utils
import torch.nn.functional as F
from torch.autograd import Variable
from chamfer_loss import *
_EPS = 1e-5
def pairwise_distance_batch(x,y):
"""
pairwise_distance
Args:
x: Input features of source point clouds. Size [B, c, N]
y: Input features of source point clouds. Size [B, c, M]
Returns:
pair_distances: Euclidean distance. Size [B, N, M]
"""
xx = torch.sum(torch.mul(x,x), 1, keepdim = True)#[b,1,n]
yy = torch.sum(torch.mul(y,y),1, keepdim = True) #[b,1,n]
inner = -2*torch.matmul(x.transpose(2,1),y) #[b,n,n]
pair_distance = xx.transpose(2,1) + inner + yy #[b,n,n]
device = torch.device('cuda')
zeros_matrix = torch.zeros_like(pair_distance,device = device)
pair_distance_square = torch.where(pair_distance > 0.0,pair_distance,zeros_matrix)
error_mask = torch.le(pair_distance_square,0.0)
pair_distances = torch.sqrt(pair_distance_square + error_mask.float()*1e-16)
pair_distances = torch.mul(pair_distances,(1.0-error_mask.float()))
return pair_distances
def knn(x, k):
inner = -2 * torch.matmul(x.transpose(2, 1).contiguous(), x)
xx = torch.sum(x ** 2, dim=1, keepdim=True)
pairwise_distance = -xx - inner - xx.transpose(2, 1).contiguous()
idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k)
return idx
def get_graph_feature(x, k):
"""
knn-graph.
Args:
x: Input point clouds. Size [B, 3, N]
k: Number of nearest neighbors.
Returns:
idx: Nearest neighbor indices. Size [B * N * k]
relative_coordinates: Relative coordinates between nearest neighbors and the center point. Size [B, 3, N, K]
knn_points: Coordinates of nearest neighbors. Size[B, N, K, 3].
idx2: Nearest neighbor indices. Size [B, N, k]
"""
idx = knn(x, k=k) # (batch_size, num_points, k)
idx2 = idx
batch_size, num_points, _ = idx.size()
device = torch.device('cuda')
idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points
idx = idx + idx_base
idx = idx.view(-1)
_, num_dims, _ = x.size()
x = x.transpose(2,
1).contiguous() # (batch_size, num_points, num_dims) -> (batch_size*num_points, num_dims) # batch_size * num_points * k + range(0, batch_size*num_points)
knn_points = x.view(batch_size * num_points, -1)[idx, :]
knn_points = knn_points.view(batch_size, num_points, k, num_dims)#[b, n, k, 3],knn
x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1)#[b, n, k, 3],central points
relative_coordinates = (knn_points - x).permute(0, 3, 1, 2)
return idx, relative_coordinates, knn_points, idx2
class PointNet(nn.Module):
def __init__(self):
super(PointNet, self).__init__()
self.conv1 = nn.Conv1d(3, 32, kernel_size=1, bias=False)
self.conv2 = nn.Conv1d(32, 32, kernel_size=1, bias=False)
self.conv3 = nn.Conv1d(32, 64, kernel_size=1, bias=False)
self.conv4 = nn.Conv1d(64, 128, kernel_size=1, bias=False)
self.conv5 = nn.Conv1d(128, 256, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm1d(32)
self.bn2 = nn.BatchNorm1d(32)
self.bn3 = nn.BatchNorm1d(64)
self.bn4 = nn.BatchNorm1d(128)
self.bn5 = nn.BatchNorm1d(256)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = F.relu(self.bn4(self.conv4(x)))
x = F.relu(self.bn5(self.conv5(x)))
return x
class Pointer(nn.Module):
def __init__(self):
super(Pointer, self).__init__()
self.conv1 = nn.Conv1d(512, 256, kernel_size=1, bias=False)
self.conv2 = nn.Conv1d(256, 64, kernel_size=1, bias=False)
self.conv3 = nn.Conv1d(64, 32, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm1d(256)
self.bn2 = nn.BatchNorm1d(64)
self.bn3 = nn.BatchNorm1d(32)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
# x = F.relu(self.bn3(self.conv3(x)))
return x
def get_knn_index(x, k):
"""
knn-graph.
Args:
x: Input point clouds. Size [B, 3, N]
k: Number of nearest neighbors.
Returns:
idx: Nearest neighbor indices. Size [B * N * k]
idx2: Nearest neighbor indices. Size [B, N, k]
"""
idx = knn(x, k=k) # (batch_size, num_points, k)
idx2 = idx
batch_size, num_points, _ = idx.size()
device = torch.device('cuda')
idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points
idx = idx + idx_base
idx = idx.view(-1)
return idx, idx2
def compute_rigid_transformation(src, src_corr, weight):
"""
Compute rigid transforms between two point sets
Args:
src: Source point clouds. Size (B, 3, N)
src_corr: Pseudo target point clouds. Size (B, 3, N)
weights: Inlier confidence. (B, 1, N)
Returns:
R: Rotation. Size (B, 3, 3)
t: translation. Size (B, 3, 1)
"""
src2 = (src * weight).sum(dim = 2, keepdim = True) / weight.sum(dim = 2, keepdim = True)
src_corr2 = (src_corr * weight).sum(dim = 2, keepdim = True)/weight.sum(dim = 2,keepdim = True)
src_centered = src - src2
src_corr_centered = src_corr - src_corr2
H = torch.matmul(src_centered * weight, src_corr_centered.transpose(2, 1).contiguous())
R = []
for i in range(src.size(0)):
u, s, v = torch.svd(H[i])
r = torch.matmul(v, u.transpose(1, 0)).contiguous()
r_det = torch.det(r).item()
diag = torch.from_numpy(np.array([[1.0, 0, 0],
[0, 1.0, 0],
[0, 0, r_det]]).astype('float32')).to(v.device)
r = torch.matmul(torch.matmul(v, diag), u.transpose(1, 0)).contiguous()
R.append(r)
R = torch.stack(R, dim = 0).cuda()
t = torch.matmul(-R, src2.mean(dim = 2, keepdim=True)) + src_corr2.mean(dim = 2, keepdim = True)
return R, t
def get_keypoints(src, src_corr, weight, num_keypoints):
"""
Compute rigid transforms between two point sets
Args:
src: Source point clouds. Size (B, 3, N)
src_corr: Pseudo target point clouds. Size (B, 3, N)
weights: Inlier confidence. (B, 1, N)
num_keypoints: Number of selected keypoints.
Returns:
src_topk_idx: Keypoint indices. Size (B, 1, num_keypoints)
src_keypoints: Keypoints of source point clouds. Size (B, 3, num_keypoints)
tgt_keypoints: Keypoints of target point clouds. Size (B, 3, num_keypoints)
"""
src_topk_idx = torch.topk(weight, k = num_keypoints, dim = 2, sorted=False)[1]
src_keypoints_idx = src_topk_idx.repeat(1, 3, 1)
src_keypoints = torch.gather(src, dim = 2, index = src_keypoints_idx)
tgt_keypoints = torch.gather(src_corr, dim = 2, index = src_keypoints_idx)
return src_topk_idx, src_keypoints, tgt_keypoints
class DGCNN(nn.Module):
def __init__(self, args):
super(DGCNN, self).__init__()
self.emb_dims = args.emb_dims
self.conv1 = nn.Conv2d(3, 32, kernel_size=1, bias=False)
self.conv2 = nn.Conv2d(32, 32, kernel_size=1, bias=False)
self.conv3 = nn.Conv2d(32, 64, kernel_size=1, bias=False)
self.conv4 = nn.Conv2d(64, 128, kernel_size=1, bias=False)
self.conv5 = nn.Conv2d(256, self.emb_dims, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(32)
self.bn2 = nn.BatchNorm2d(32)
self.bn3 = nn.BatchNorm2d(64)
self.bn4 = nn.BatchNorm2d(128)
self.bn5 = nn.BatchNorm2d(self.emb_dims)
self.dp = nn.Dropout(p=0.3)
def forward(self, x):
"""
Simplified DGCNN.
Args:
x: Relative coordinates between nearest neighbors and the center point. Size [B, 3, N, K]
Returns:
x: Features. Size [B, self.emb_dims, N]
"""
batch_size, num_dims, num_points, _ = x.size()
x = F.relu(self.bn1(self.conv1(x)))
x1 = x.max(dim=-1, keepdim=True)[0]
x = F.relu(self.bn2(self.conv2(x)))
x2 = x.max(dim=-1, keepdim=True)[0]
x = F.relu(self.bn3(self.conv3(x)))
x3 = x.max(dim=-1, keepdim=True)[0]
x = F.relu(self.bn4(self.conv4(x)))
x4 = x.max(dim=-1, keepdim=True)[0]
x = torch.cat((x1, x2, x3, x4), dim=1)
x = F.relu(self.bn5(self.conv5(x))).view(batch_size, -1, num_points)
return x
class feature_extractor(nn.Module):
def __init__(self, args):
super(feature_extractor, self).__init__()
self.model = DGCNN(args)
def forward(self, x, k):
"""
feature extraction.
Args:
x: Input point clouds. Size [B, 3, N]
k: Number of nearest neighbors.
Returns:
features: Size [B, C, N]
idx: Nearest neighbor indices. Size [B * N * k]
knn_points: Coordinates of nearest neighbors Size [B, N, K, 3].
idx2: Nearest neighbor indices. Size [B, N, k]
"""
batch_size, num_dims, num_points = x.size()
idx, relative_coordinates, knn_points, idx2 = get_graph_feature(x,k)
features = self.model(relative_coordinates)
return features, idx, knn_points, idx2
class Discriminator(nn.Module):
def __init__(self, args):
super(Discriminator, self).__init__()
self.model1 = nn.Sequential(
nn.Conv2d(3, args.dim, kernel_size=(3,1), bias=True, padding=(1,0)),
nn.BatchNorm2d(args.dim),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(args.dim, args.dim * 2, kernel_size=(3,1), bias=True, padding=(1,0)),
nn.BatchNorm2d(args.dim * 2),
nn.LeakyReLU(0.2, inplace=True))
self.model2 = nn.Sequential(
nn.Conv2d(args.dim * 2, 16, kernel_size=1, bias=True),
nn.BatchNorm2d(16),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(16, 16, kernel_size=1, bias=True),
nn.BatchNorm2d(16),
nn.LeakyReLU(0.2, inplace=True))
self.model3 = nn.Sequential(
nn.Conv2d(args.dim * 2, 16, kernel_size=1, bias=True),
nn.BatchNorm2d(16),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(16, 16, kernel_size=1, bias=True),
nn.BatchNorm2d(16),
nn.LeakyReLU(0.2, inplace=True))
self.model4 = nn.Sequential(
nn.Conv1d(16, 8, kernel_size=1, bias=True),
nn.BatchNorm1d(8),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv1d(8, 1, kernel_size=1, bias=True),
#nn.Tanh(),
)
self.tah = nn.Tanh()
def forward(self, x, y):
"""
Inlier Evaluation.
Args:
x: Source neighborhoods. Size [B, N, K, 3]
y: Pesudo target neighborhoods. Size [B, N, K, 3]
Returns:
x: Inlier confidence. Size [B, 1, N]
"""
b, n, k, _ = x.size()
x_1x3 = self.model1(x.permute(0,3,2,1)).permute(0,1,3,2)
y_1x3 = self.model1(y.permute(0,3,2,1)).permute(0,1,3,2) # [b, n, k, 3]-[b, c, k, n]-->[b, c, n, k]
x2 = x_1x3 - y_1x3 # Eq. (5)
x = self.model2(x2) # [b, c, n, k]
weight = self.model3(x2) # [b, c, n, k]
weight = torch.softmax(weight, dim=-1) # Eq. (6)
x = (x * weight).sum(-1) # [b, c, n]
x = 1 - self.tah(torch.abs(self.model4(x)))
return x