-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdataset.py
executable file
·150 lines (113 loc) · 4.85 KB
/
dataset.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
"""
@Author: Pengfei Li
@File: dataset.py
@Description:
@Date: 2021/08/06
"""
import math
import os
import numpy as np
import torch
from torch.utils.data import Dataset
from IPython import embed
class PointCloud(Dataset):
def __init__(self, point_cloud, on_surface_points, keep_aspect_ratio=True):
super().__init__()
coords = point_cloud[:, :3]
self.normals = point_cloud[:, 3:]
# Reshape point cloud such that it lies in bounding box of (-1, 1)
self.coords = (coords - 0) / (255 - 0)
self.coords -= 0.5
self.coords *= 2.
self.on_surface_points = on_surface_points
def __len__(self):
return self.coords.shape[0] // self.on_surface_points
def __getitem__(self, idx):
point_cloud_size = self.coords.shape[0]
off_surface_samples = self.on_surface_points # **2
total_samples = self.on_surface_points + off_surface_samples
# Random coords
rand_idcs = np.random.choice(point_cloud_size, size=self.on_surface_points)
on_surface_coords = self.coords[rand_idcs, :]
on_surface_normals = self.normals[rand_idcs, :]
off_surface_coords = np.random.uniform(-1, 1, size=(off_surface_samples, 3))
# off_surface_coords = np.random.uniform(-2, 2, size=(off_surface_samples, 3))
off_surface_normals = np.ones((off_surface_samples, 3)) * -1
sdf = np.zeros((total_samples, 1)) # on-surface = 0
sdf[self.on_surface_points:, :] = -1 # off-surface = -1
coords = np.concatenate((on_surface_coords, off_surface_coords), axis=0)
normals = np.concatenate((on_surface_normals, off_surface_normals), axis=0)
return {'coords': torch.from_numpy(coords).float()}, {'sdf': torch.from_numpy(sdf).float(),
'normals': torch.from_numpy(normals).float()}
def get_mgrid(sidelen, dim=2):
'''Generates a flattened grid of (x,y,...) coordinates in a range of -1 to 1.'''
if isinstance(sidelen, int):
sidelen = dim * (sidelen,)
if dim == 2:
pixel_coords = np.stack(np.mgrid[:sidelen[0], :sidelen[1]], axis=-1)[None, ...].astype(np.float32)
pixel_coords[0, :, :, 0] = pixel_coords[0, :, :, 0] / (sidelen[0] - 1)
pixel_coords[0, :, :, 1] = pixel_coords[0, :, :, 1] / (sidelen[1] - 1)
elif dim == 3:
pixel_coords = np.stack(np.mgrid[:sidelen[0], :sidelen[1], :sidelen[2]], axis=-1)[None, ...].astype(np.float32)
pixel_coords[..., 0] = pixel_coords[..., 0] / max(sidelen[0] - 1, 1)
pixel_coords[..., 1] = pixel_coords[..., 1] / (sidelen[1] - 1)
pixel_coords[..., 2] = pixel_coords[..., 2] / (sidelen[2] - 1)
else:
raise NotImplementedError('Not implemented for dim=%d' % dim)
pixel_coords -= 0.5
pixel_coords *= 2.
pixel_coords = torch.Tensor(pixel_coords).view(-1, dim)
return pixel_coords
def lin2img(tensor, image_resolution=None):
batch_size, num_samples, channels = tensor.shape
if image_resolution is None:
width = np.sqrt(num_samples).astype(int)
height = width
else:
height = image_resolution[0]
width = image_resolution[1]
return tensor.permute(0, 2, 1).view(batch_size, channels, height, width)
def grads2img(gradients):
mG = gradients.detach().squeeze(0).permute(-2, -1, -3).cpu()
# assumes mG is [row,cols,2]
nRows = mG.shape[0]
nCols = mG.shape[1]
mGr = mG[:, :, 0]
mGc = mG[:, :, 1]
mGa = np.arctan2(mGc, mGr)
mGm = np.hypot(mGc, mGr)
mGhsv = np.zeros((nRows, nCols, 3), dtype=np.float32)
mGhsv[:, :, 0] = (mGa + math.pi) / (2. * math.pi)
mGhsv[:, :, 1] = 1.
nPerMin = np.percentile(mGm, 5)
nPerMax = np.percentile(mGm, 95)
mGm = (mGm - nPerMin) / (nPerMax - nPerMin)
mGm = np.clip(mGm, 0, 1)
mGhsv[:, :, 2] = mGm
mGrgb = colors.hsv_to_rgb(mGhsv)
return torch.from_numpy(mGrgb).permute(2, 0, 1)
def rescale_img(x, mode='scale', perc=None, tmax=1.0, tmin=0.0):
if (mode == 'scale'):
if perc is None:
xmax = torch.max(x)
xmin = torch.min(x)
else:
xmin = np.percentile(x.detach().cpu().numpy(), perc)
xmax = np.percentile(x.detach().cpu().numpy(), 100 - perc)
x = torch.clamp(x, xmin, xmax)
if xmin == xmax:
return 0.5 * torch.ones_like(x) * (tmax - tmin) + tmin
x = ((x - xmin) / (xmax - xmin)) * (tmax - tmin) + tmin
elif (mode == 'clamp'):
x = torch.clamp(x, 0, 1)
return x
def to_uint8(x):
return (255. * x).astype(np.uint8)
def to_numpy(x):
return x.detach().cpu().numpy()
def gaussian(x, mu=[0, 0], sigma=1e-4, d=2):
x = x.numpy()
if isinstance(mu, torch.Tensor):
mu = mu.numpy()
q = -0.5 * ((x - mu) ** 2).sum(1)
return torch.from_numpy(1 / np.sqrt(sigma ** d * (2 * np.pi) ** d) * np.exp(q / sigma)).float()