Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathutils.py
More file actions
Latest commit
249 lines (204 loc) · 7.8 KB
/
Copy pathutils.py
File metadata and controls
249 lines (204 loc) · 7.8 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
importcv2,torch,math
importnumpyasnp
fromPILimportImage
importtorchvision.transformsasT
importtorch.nn.functionalasF
importscipy.signal
mse2psnr=lambdax : -10.*torch.log(x) /torch.log(torch.Tensor([10.]))
defvisualize_depth_numpy(depth, minmax=None, cmap=cv2.COLORMAP_JET):
"""
depth: (H, W)
"""
x=np.nan_to_num(depth) # change nan to 0
ifminmaxisNone:
mi=np.min(x[x>0]) # get minimum positive depth (ignore background)
ma=np.max(x)
else:
mi,ma=minmax
x= (x-mi)/(ma-mi+1e-8) # normalize to 0~1
x= (255*x).astype(np.uint8)
x_=cv2.applyColorMap(x, cmap)
returnx_, [mi,ma]
definit_log(log, keys):
forkeyinkeys:
log[key] =torch.tensor([0.0], dtype=float)
returnlog
defvisualize_depth(depth, minmax=None, cmap=cv2.COLORMAP_JET):
"""
depth: (H, W)
"""
iftype(depth) isnotnp.ndarray:
depth=depth.cpu().numpy()
x=np.nan_to_num(depth) # change nan to 0
ifminmaxisNone:
mi=np.min(x[x>0]) # get minimum positive depth (ignore background)
ma=np.max(x)
else:
mi,ma=minmax
x= (x-mi)/(ma-mi+1e-8) # normalize to 0~1
x= (255*x).astype(np.uint8)
x_=Image.fromarray(cv2.applyColorMap(x, cmap))
x_=T.ToTensor()(x_) # (3, H, W)
returnx_, [mi,ma]
defN_to_reso(n_voxels, bbox):
xyz_min, xyz_max=bbox
dim=len(xyz_min)
voxel_size= ((xyz_max-xyz_min).prod() /n_voxels).pow(1/dim)
returntorch.round((xyz_max-xyz_min) /voxel_size).long().tolist()
defN_to_vm_reso(n_voxels, bbox):
xyz_min, xyz_max=bbox
dim=len(xyz_min)
voxel_size= ((xyz_max-xyz_min).prod() /n_voxels).pow(1/dim)
reso= (xyz_max-xyz_min) /voxel_size
assertlen(reso)==3
n_mat=reso[0]*reso[1] +reso[0]*reso[2] +reso[1]*reso[2]
scale=math.sqrt(n_voxels/n_mat)
returntorch.round(reso*scale).long().tolist()
defcal_n_samples(reso, step_ratio=0.5):
returnint(np.linalg.norm(reso)/step_ratio)
classSimpleSampler:
def__init__(self, total, batch):
self.total=total
self.batch=batch
self.curr=total
self.ids=None
defnextids(self):
self.curr+=self.batch
ifself.curr+self.batch>self.total:
self.ids=torch.LongTensor(np.random.permutation(self.total))
self.curr=0
returnself.ids[self.curr:self.curr+self.batch]
__LPIPS__= {}
definit_lpips(net_name, device):
assertnet_namein ['alex', 'vgg']
importlpips
print(f'init_lpips: lpips_{net_name}')
returnlpips.LPIPS(net=net_name, version='0.1').eval().to(device)
defrgb_lpips(np_gt, np_im, net_name, device):
ifnet_namenotin__LPIPS__:
__LPIPS__[net_name] =init_lpips(net_name, device)
gt=torch.from_numpy(np_gt).permute([2, 0, 1]).contiguous().to(device)
im=torch.from_numpy(np_im).permute([2, 0, 1]).contiguous().to(device)
return__LPIPS__[net_name](gt, im, normalize=True).item()
deffindItem(items, target):
foroneinitems:
ifone[:len(target)]==target:
returnone
returnNone
''' Evaluation metrics (ssim, lpips)
'''
defrgb_ssim(img0, img1, max_val,
filter_size=11,
filter_sigma=1.5,
k1=0.01,
k2=0.03,
return_map=False):
# Modified from https://github.com/google/mipnerf/blob/16e73dfdb52044dcceb47cda5243a686391a6e0f/internal/math.py#L58
assertlen(img0.shape) ==3
assertimg0.shape[-1] ==3
assertimg0.shape==img1.shape
# Construct a 1D Gaussian blur filter.
hw=filter_size//2
shift= (2*hw-filter_size+1) /2
f_i= ((np.arange(filter_size) -hw+shift) /filter_sigma)**2
filt=np.exp(-0.5*f_i)
filt/=np.sum(filt)
# Blur in x and y (faster than the 2D convolution).
defconvolve2d(z, f):
returnscipy.signal.convolve2d(z, f, mode='valid')
filt_fn=lambdaz: np.stack([
convolve2d(convolve2d(z[...,i], filt[:, None]), filt[None, :])
foriinrange(z.shape[-1])], -1)
mu0=filt_fn(img0)
mu1=filt_fn(img1)
mu00=mu0*mu0
mu11=mu1*mu1
mu01=mu0*mu1
sigma00=filt_fn(img0**2) -mu00
sigma11=filt_fn(img1**2) -mu11
sigma01=filt_fn(img0*img1) -mu01
# Clip the variances and covariances to valid values.
# Variance must be non-negative:
sigma00=np.maximum(0., sigma00)
sigma11=np.maximum(0., sigma11)
sigma01=np.sign(sigma01) *np.minimum(
np.sqrt(sigma00*sigma11), np.abs(sigma01))
c1= (k1*max_val)**2
c2= (k2*max_val)**2
numer= (2*mu01+c1) * (2*sigma01+c2)
denom= (mu00+mu11+c1) * (sigma00+sigma11+c2)
ssim_map=numer/denom
ssim=np.mean(ssim_map)
returnssim_mapifreturn_mapelsessim
importtorch.nnasnn
classTVLoss(nn.Module):
def__init__(self,TVLoss_weight=1):
super(TVLoss,self).__init__()
self.TVLoss_weight=TVLoss_weight
defforward(self,x):
batch_size=x.size()[0]
h_x=x.size()[2]
w_x=x.size()[3]
count_h=self._tensor_size(x[:,:,1:,:])
count_w=self._tensor_size(x[:,:,:,1:])
h_tv=torch.pow((x[:,:,1:,:]-x[:,:,:h_x-1,:]),2).sum()
w_tv=torch.pow((x[:,:,:,1:]-x[:,:,:,:w_x-1]),2).sum()
returnself.TVLoss_weight*2*(h_tv/count_h+w_tv/count_w)/batch_size
def_tensor_size(self,t):
returnt.size()[1]*t.size()[2]*t.size()[3]
defmarchcude_to_world(vertices, reso_WHD):
returnvertices/(np.array(reso_WHD)-1)
importplyfile
importskimage.measure
defconvert_sdf_samples_to_ply(
pytorch_3d_sdf_tensor,
ply_filename_out,
bbox,
level=0.5,
offset=None,
scale=None,
):
"""
Convert sdf samples to .ply
:param pytorch_3d_sdf_tensor: a torch.FloatTensor of shape (n,n,n)
:voxel_grid_origin: a list of three floats: the bottom, left, down origin of the voxel grid
:voxel_size: float, the size of the voxels
:ply_filename_out: string, path of the filename to save to
This function adapted from: https://github.com/RobotLocomotion/spartan
"""
numpy_3d_sdf_tensor=pytorch_3d_sdf_tensor.numpy()
# voxel_size = list((bbox[1]-bbox[0]) / np.array(pytorch_3d_sdf_tensor.shape))
verts, faces, normals, values=skimage.measure.marching_cubes(
numpy_3d_sdf_tensor, level=level
)
reso_WHD=numpy_3d_sdf_tensor.shape
print(bbox)
verts=marchcude_to_world(verts, reso_WHD)
faces=faces[...,::-1] # inverse face orientation
# transform from voxel coordinates to camera coordinates
# note x and y are flipped in the output of marching_cubes
mesh_points=np.zeros_like(verts)
bbox=bbox.numpy()
mesh_points[:, 0] =bbox[0,2] +verts[:, 0]*(bbox[1,2]-bbox[0,2])
mesh_points[:, 1] =bbox[0,1] +verts[:, 1]*(bbox[1,1]-bbox[0,1])
mesh_points[:, 2] =bbox[0,0] +verts[:, 2]*(bbox[1,0]-bbox[0,0])
# # apply additional offset and scale
# if scale is not None:
# mesh_points = mesh_points / scale
# if offset is not None:
# mesh_points = mesh_points - offset
# try writing to the ply file
num_verts=verts.shape[0]
num_faces=faces.shape[0]
verts_tuple=np.zeros((num_verts,), dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
foriinrange(0, num_verts):
verts_tuple[i] =tuple(mesh_points[i, :])
faces_building= []
foriinrange(0, num_faces):
faces_building.append(((faces[i, :].tolist(),)))
faces_tuple=np.array(faces_building, dtype=[("vertex_indices", "i4", (3,))])
el_verts=plyfile.PlyElement.describe(verts_tuple, "vertex")
el_faces=plyfile.PlyElement.describe(faces_tuple, "face")
ply_data=plyfile.PlyData([el_verts, el_faces])
print("saving mesh to %s"% (ply_filename_out))
ply_data.write(ply_filename_out)