-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdf_sample.py
179 lines (138 loc) · 6.48 KB
/
sdf_sample.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
import numpy as np
import igl
from common import normalize, normalize_aabb
from joblib import Parallel, delayed
import multiprocessing
from glob import glob
from tqdm import tqdm
import os
import open3d as o3d
from icecream import ic
import polyscope as ps
class SDFSampler:
def __init__(self,
model_path,
normalize=False,
surface_ratio=0.6,
close_sample_ratio=0.3,
sigma=5e-2):
V, F = igl.read_triangle_mesh(model_path)
if normalize:
V = normalize_aabb(V)
self.V = V
self.F = F
self.surface_ratio = surface_ratio
self.close_sample_ratio = close_sample_ratio
self.sigma = sigma
def sample_sdf_igl(self, x):
return igl.signed_distance(x, self.V, self.F)[0]
def sample_importance(self, sample_size, multiplier=10., beta=1.5):
sample_size_full = int(sample_size * multiplier)
n_surface = int(sample_size_full * self.surface_ratio)
n_close = int(sample_size_full * self.close_sample_ratio)
n_free = sample_size_full - (n_surface + n_close)
bary, f_id = igl.random_points_on_mesh(n_surface, self.V, self.F)
surface_samples = np.sum(bary[..., None] * self.V[self.F[f_id]], 1)
degen_n = normalize(np.array([1., 1., 1.]))[None, ...]
FN = igl.per_face_normals(self.V, self.F, np.float64(degen_n))
surface_samples += self.sigma * np.random.normal(size=(n_surface,
1)) * FN[f_id]
bary, f_id = igl.random_points_on_mesh(n_close, self.V, self.F)
close_samples = np.sum(
bary[..., None] * self.V[self.F[f_id]],
1) + 2. * self.sigma * np.random.normal(size=(n_close, 3))
free_samples = np.random.uniform(low=-1.0, high=1.0, size=(n_free, 3))
# Reference: https://github.com/nmwsharp/neural-implicit-queries/blob/c17e4b54f216cefb02d00ddba25c4f15b9873278/src/geometry.py#LL43C1-L43C1
samples_full = np.vstack([surface_samples, close_samples, free_samples])
dist_sq, _, _ = igl.point_mesh_squared_distance(samples_full, self.V,
self.F)
weight = np.exp(-beta * np.sqrt(dist_sq))
weight = weight / np.sum(weight)
sample_indices = np.random.choice(np.arange(sample_size_full),
size=sample_size,
p=weight,
replace=False)
samples = samples_full[sample_indices]
sdf_vals, _, _ = igl.signed_distance(np.array(samples), self.V, self.F)
return samples, np.array(sdf_vals)
def sample_surface(self, sample_size):
bary, f_id = igl.random_points_on_mesh(sample_size, self.V, self.F)
surface_samples = np.sum(bary[..., None] * self.V[self.F[f_id]], 1)
z = normalize(np.array([1, 1, 1]))
FN = igl.per_face_normals(self.V, self.F, np.float64(z[None, :]))
return surface_samples, FN[f_id]
# Random seed managed by numpy
def sample_surface_fixed_seed(self, sample_size):
dbl_area = igl.doublearea(self.V, self.F)
prob = dbl_area / dbl_area.sum()
fid = np.arange(len(self.F))
fid_pick = np.random.choice(fid, sample_size, p=prob)
# https://mathworld.wolfram.com/TrianglePointPicking.html
sample_bary = np.random.uniform(0, 1, (sample_size, 2))
# https://mathworld.wolfram.com/TriangleInterior.html
sample_outside_mask = sample_bary.sum(-1) > 1
sample_bary[sample_outside_mask] -= 1
sample_bary = np.abs(sample_bary)
sample_per_face_vertices = self.V[self.F[fid_pick]]
A = sample_per_face_vertices[:, 0]
B = sample_per_face_vertices[:, 1]
C = sample_per_face_vertices[:, 2]
samples_on_sur = C + (A - C) * sample_bary[:, 0][:, None] + (
B - C) * sample_bary[:, 1][:, None]
FN = np.cross(B - A, C - A)
FN = normalize(FN)
return samples_on_sur, FN
def sample_dense(self, res=512):
line = np.linspace(-1.0, 1.0, res)
samples = np.stack(np.meshgrid(line, line, line), -1).reshape(-1, 3)
splits = len(samples) // 100000
sdf_vals = Parallel(
n_jobs=multiprocessing.cpu_count() - 2, backend='multiprocessing')(
delayed(self.sample_sdf_igl)(sample_split)
for sample_split in np.array_split(samples, splits, axis=0))
sdf_vals = np.concatenate(sdf_vals)
return samples, np.array(sdf_vals)
if __name__ == '__main__':
import argparse
# Arguments
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', type=str, help='Path to input model.')
parser.add_argument('--subfolder',
type=str,
default='',
help='Subfolder path.')
parser.add_argument('--sample_size',
type=int,
default=10000,
help='Number of samples.')
args = parser.parse_args()
model_base_folder_path = 'data/mesh'
subfolder = args.subfolder
if args.model_path is not None:
subfolder = '/'.join(args.model_path.split('/')[2:-1])
model_path_list = [args.model_path]
else:
model_folder_path = os.path.join(model_base_folder_path, subfolder)
model_path_list = sorted(
glob(os.path.join(model_folder_path, '*.obj')) +
glob(os.path.join(model_folder_path, '*.ply')))
# Fix the random seed
np.random.seed(0)
sample_size = args.sample_size
if args.model_path is not None:
sdf_base_path = os.path.join('data/sdf', subfolder)
else:
sdf_base_path = os.path.join('data/sdf', subfolder, str(sample_size))
if not os.path.exists(sdf_base_path):
os.makedirs(sdf_base_path)
for model_path in tqdm(model_path_list):
model_name = model_path.split('/')[-1].split('.')[0]
model_out_path = os.path.join(sdf_base_path,
f'{model_name}_{sample_size}.ply')
sampler = SDFSampler(model_path)
samples_on_sur, normals_on_sur = sampler.sample_surface_fixed_seed(
sample_size)
pc_o3d = o3d.geometry.PointCloud()
pc_o3d.points = o3d.utility.Vector3dVector(samples_on_sur)
pc_o3d.normals = o3d.utility.Vector3dVector(normals_on_sur)
o3d.io.write_point_cloud(model_out_path, pc_o3d)