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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Two-stage optimization:
|
| 3 |
+
1. SDF learning from point cloud
|
| 4 |
+
2. Vertex generation + Delaunay meshing
|
| 5 |
+
|
| 6 |
+
All pure PyTorch, no compiled extensions.
|
| 7 |
+
"""
|
| 8 |
+
import os
|
| 9 |
+
import math
|
| 10 |
+
import time
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import numpy as np
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
|
| 16 |
+
from .sdfnet import SDFNetwork
|
| 17 |
+
from .vgnet import VGNetwork
|
| 18 |
+
from . import losses as loss_utils
|
| 19 |
+
from . import meshing as mesh_utils
|
| 20 |
+
from .io_utils import (
|
| 21 |
+
load_pointcloud,
|
| 22 |
+
normalize_pointcloud,
|
| 23 |
+
denormalize_pointcloud,
|
| 24 |
+
estimate_normals,
|
| 25 |
+
fps_sample,
|
| 26 |
+
build_sigma_knn,
|
| 27 |
+
save_mesh_ply,
|
| 28 |
+
save_mesh_obj,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Runner:
|
| 33 |
+
def __init__(self,
|
| 34 |
+
pointcloud_path,
|
| 35 |
+
out_dir='./output',
|
| 36 |
+
device='cpu',
|
| 37 |
+
sdf_iters=20_000,
|
| 38 |
+
vg_iters=8_000,
|
| 39 |
+
sdf_lr=1e-3,
|
| 40 |
+
vg_lr=1e-3,
|
| 41 |
+
sdf_batch=5_000,
|
| 42 |
+
vg_batch=3_400,
|
| 43 |
+
vertices_size=3_400,
|
| 44 |
+
update_size=5,
|
| 45 |
+
update_ratio=1.2,
|
| 46 |
+
k_samples=21,
|
| 47 |
+
multires=8,
|
| 48 |
+
queries_size=1_000_000,
|
| 49 |
+
surface_queries=200_000,
|
| 50 |
+
project_sdf_level=0.0,
|
| 51 |
+
save_freq=2_000,
|
| 52 |
+
loss_weights_sdf=None,
|
| 53 |
+
loss_weights_vg=None,
|
| 54 |
+
):
|
| 55 |
+
self.device = torch.device(device)
|
| 56 |
+
self.out_dir = out_dir
|
| 57 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 58 |
+
|
| 59 |
+
# Load & normalize point cloud
|
| 60 |
+
print("Loading point cloud...")
|
| 61 |
+
raw_pts = load_pointcloud(pointcloud_path)
|
| 62 |
+
self.raw_pts = raw_pts
|
| 63 |
+
self.points, self.loc, self.scale = normalize_pointcloud(raw_pts)
|
| 64 |
+
print(f" Points: {len(self.points)} Scale: {self.scale:.4f}")
|
| 65 |
+
|
| 66 |
+
# Preprocess: build sigma + query samples for SDF training
|
| 67 |
+
print("Preprocessing queries for SDF training...")
|
| 68 |
+
self._preprocess_sdf_queries(queries_size)
|
| 69 |
+
|
| 70 |
+
# Config
|
| 71 |
+
self.sdf_iters = sdf_iters
|
| 72 |
+
self.vg_iters = vg_iters
|
| 73 |
+
self.sdf_lr = sdf_lr
|
| 74 |
+
self.vg_lr = vg_lr
|
| 75 |
+
self.sdf_batch = sdf_batch
|
| 76 |
+
self.vg_batch = vg_batch
|
| 77 |
+
self.vertices_size = vertices_size
|
| 78 |
+
self.update_size = update_size
|
| 79 |
+
self.update_ratio = update_ratio
|
| 80 |
+
self.k_samples = k_samples
|
| 81 |
+
self.project_sdf_level = project_sdf_level
|
| 82 |
+
self.save_freq = save_freq
|
| 83 |
+
|
| 84 |
+
self.loss_weights_sdf = loss_weights_sdf or [1.0, 0.1, 0.001, 0.0]
|
| 85 |
+
self.loss_weights_vg = loss_weights_vg or [100.0, 1.0, 1.0, 1.0, 100.0]
|
| 86 |
+
|
| 87 |
+
# Networks
|
| 88 |
+
self.sdf_net = SDFNetwork(
|
| 89 |
+
d_in=3, d_out=1, d_hidden=256, n_layers=8,
|
| 90 |
+
skip_in=(4,), multires=multires,
|
| 91 |
+
bias=0.5, scale=1.0,
|
| 92 |
+
geometric_init=True, weight_norm=True,
|
| 93 |
+
).to(self.device)
|
| 94 |
+
self.vg_net = VGNetwork(
|
| 95 |
+
d_in=3, d_out=3, d_hidden=256, n_layers=8,
|
| 96 |
+
skip_in=(4,), multires=multires,
|
| 97 |
+
scale=1.0, geometric_init=True, weight_norm=True,
|
| 98 |
+
).to(self.device)
|
| 99 |
+
|
| 100 |
+
self.sdf_optimizer = torch.optim.Adam(self.sdf_net.parameters(), lr=self.sdf_lr)
|
| 101 |
+
self.vg_optimizer = torch.optim.Adam(self.vg_net.parameters(), lr=self.vg_lr)
|
| 102 |
+
|
| 103 |
+
self.iter_step = 0
|
| 104 |
+
|
| 105 |
+
# ------------------------------------------------------------------
|
| 106 |
+
# SDF preprocessing
|
| 107 |
+
# ------------------------------------------------------------------
|
| 108 |
+
def _preprocess_sdf_queries(self, queries_size):
|
| 109 |
+
pts = self.points
|
| 110 |
+
point_num = len(pts)
|
| 111 |
+
point_num_gt = (point_num // 60) * 60
|
| 112 |
+
if point_num_gt == 0:
|
| 113 |
+
point_num_gt = point_num
|
| 114 |
+
query_each = max(queries_size // point_num_gt, 1)
|
| 115 |
+
|
| 116 |
+
# subsample to ~1/60
|
| 117 |
+
if point_num > point_num_gt:
|
| 118 |
+
idx = np.random.choice(point_num, point_num_gt, replace=False)
|
| 119 |
+
else:
|
| 120 |
+
idx = np.arange(point_num)
|
| 121 |
+
subsample = pts[idx]
|
| 122 |
+
|
| 123 |
+
sigmas = build_sigma_knn(subsample, k=min(51, len(subsample)))
|
| 124 |
+
|
| 125 |
+
sample = []
|
| 126 |
+
sample_near = []
|
| 127 |
+
scale = 0.25 * np.sqrt(max(point_num_gt, 1) / 20000.0)
|
| 128 |
+
for _ in range(query_each):
|
| 129 |
+
tt = subsample + scale * sigmas[:, None] * np.random.normal(0.0, 1.0, size=subsample.shape)
|
| 130 |
+
sample.append(tt)
|
| 131 |
+
sample_near.append(subsample)
|
| 132 |
+
|
| 133 |
+
sample = np.concatenate(sample, axis=0).astype(np.float32)
|
| 134 |
+
sample_near = np.concatenate(sample_near, axis=0).astype(np.float32)
|
| 135 |
+
n_uniform = max(sample.shape[0] // 10, 1)
|
| 136 |
+
sample_uniform = 1.1 * (np.random.rand(n_uniform, 3).astype(np.float32) - 0.5)
|
| 137 |
+
sample_uniform_near = subsample[np.random.choice(len(subsample), n_uniform, replace=True)]
|
| 138 |
+
|
| 139 |
+
self.sample = torch.from_numpy(sample).to(self.device)
|
| 140 |
+
self.sample_near = torch.from_numpy(sample_near).to(self.device)
|
| 141 |
+
self.sample_uniform = torch.from_numpy(sample_uniform).to(self.device)
|
| 142 |
+
self.sample_uniform_near = torch.from_numpy(sample_uniform_near).to(self.device)
|
| 143 |
+
self.point_gt = torch.from_numpy(subsample).to(self.device)
|
| 144 |
+
self.surface_queries_size = min(200_000, len(subsample))
|
| 145 |
+
|
| 146 |
+
# bbox
|
| 147 |
+
self.bbox_min = subsample.min(axis=0) - 0.05
|
| 148 |
+
self.bbox_max = subsample.max(axis=0) + 0.05
|
| 149 |
+
|
| 150 |
+
# ------------------------------------------------------------------
|
| 151 |
+
# SDF stage
|
| 152 |
+
# ------------------------------------------------------------------
|
| 153 |
+
def train_sdf(self):
|
| 154 |
+
print("\n=== Stage 1: SDF Learning ===")
|
| 155 |
+
self.sdf_net.train()
|
| 156 |
+
pbar = tqdm(range(self.sdf_iters), desc="SDF")
|
| 157 |
+
for iter_i in pbar:
|
| 158 |
+
self.update_lr(self.sdf_optimizer, iter_i, self.sdf_iters, self.sdf_lr, warm_up_end=1000)
|
| 159 |
+
|
| 160 |
+
# Sample batch
|
| 161 |
+
n_near = self.sdf_batch
|
| 162 |
+
idx_near = np.random.choice(len(self.sample), n_near, replace=False)
|
| 163 |
+
idx_uniform = np.random.choice(len(self.sample_uniform), max(n_near // 2, 1), replace=False)
|
| 164 |
+
|
| 165 |
+
sample_near = self.sample[idx_near]
|
| 166 |
+
points_near = self.sample_near[idx_near]
|
| 167 |
+
sample_uniform = self.sample_uniform[idx_uniform]
|
| 168 |
+
points_uniform = self.sample_uniform_near[idx_uniform]
|
| 169 |
+
|
| 170 |
+
samples = torch.cat([sample_near, sample_uniform], dim=0)
|
| 171 |
+
gradients_samples, sdf_samples = self.sdf_net.gradient(samples)
|
| 172 |
+
gradients_samples_norm = F.normalize(gradients_samples, dim=-1)
|
| 173 |
+
samples_moved = samples - gradients_samples_norm * sdf_samples
|
| 174 |
+
|
| 175 |
+
# Gradient consistency
|
| 176 |
+
move_pos = samples_moved.detach()
|
| 177 |
+
grad_moved, _ = self.sdf_net.gradient(move_pos)
|
| 178 |
+
grad_moved_norm = F.normalize(grad_moved, dim=-1)
|
| 179 |
+
loss_grad_consis = (1.0 - F.cosine_similarity(grad_moved_norm, gradients_samples_norm, dim=-1)).mean()
|
| 180 |
+
|
| 181 |
+
points = torch.cat([points_near, points_uniform], dim=0)
|
| 182 |
+
sdf_points = self.sdf_net.sdf(points)
|
| 183 |
+
|
| 184 |
+
loss_pull = torch.linalg.norm((points - samples_moved), ord=2, dim=-1).mean()
|
| 185 |
+
loss_sdf = torch.abs(sdf_points).mean()
|
| 186 |
+
loss_inter = torch.exp(-100.0 * torch.abs(sdf_samples)).mean()
|
| 187 |
+
loss_normal = torch.zeros(1, device=self.device)
|
| 188 |
+
loss_eik = loss_utils.eikonal_loss(gradients_samples)
|
| 189 |
+
loss_div = loss_utils.div_loss(samples, gradients_samples)
|
| 190 |
+
|
| 191 |
+
w = self.loss_weights_sdf
|
| 192 |
+
loss = (w[0] * loss_pull +
|
| 193 |
+
w[1] * loss_sdf +
|
| 194 |
+
w[2] * loss_grad_consis +
|
| 195 |
+
w[3] * loss_inter +
|
| 196 |
+
0.01 * loss_normal +
|
| 197 |
+
0.005 * loss_eik +
|
| 198 |
+
0.001 * loss_div)
|
| 199 |
+
|
| 200 |
+
self.sdf_optimizer.zero_grad()
|
| 201 |
+
loss.backward()
|
| 202 |
+
self.sdf_optimizer.step()
|
| 203 |
+
|
| 204 |
+
if (iter_i + 1) % 500 == 0:
|
| 205 |
+
pbar.set_postfix(loss=f"{loss.item():.4f}")
|
| 206 |
+
if (iter_i + 1) % self.save_freq == 0:
|
| 207 |
+
self.save_sdf_checkpoint(iter_i + 1)
|
| 208 |
+
|
| 209 |
+
print("SDF training complete.")
|
| 210 |
+
self.save_sdf_checkpoint('final')
|
| 211 |
+
|
| 212 |
+
def update_lr(self, optimizer, iter_step, max_iter, init_lr, warm_up_end=1000):
|
| 213 |
+
if iter_step < warm_up_end:
|
| 214 |
+
lr = (iter_step / warm_up_end) * init_lr
|
| 215 |
+
else:
|
| 216 |
+
lr = 0.5 * (math.cos((iter_step - warm_up_end) / (max_iter - warm_up_end) * math.pi) + 1) * init_lr
|
| 217 |
+
for g in optimizer.param_groups:
|
| 218 |
+
g['lr'] = lr
|
| 219 |
+
|
| 220 |
+
def save_sdf_checkpoint(self, tag):
|
| 221 |
+
ckpt = {
|
| 222 |
+
'iter_step': self.iter_step,
|
| 223 |
+
'sdf_network': self.sdf_net.state_dict(),
|
| 224 |
+
}
|
| 225 |
+
os.makedirs(os.path.join(self.out_dir, 'sdf_checkpoints'), exist_ok=True)
|
| 226 |
+
torch.save(ckpt, os.path.join(self.out_dir, 'sdf_checkpoints', f'sdf_{tag}.pth'))
|
| 227 |
+
|
| 228 |
+
def load_sdf_checkpoint(self, path):
|
| 229 |
+
ckpt = torch.load(path, map_location=self.device)
|
| 230 |
+
self.sdf_net.load_state_dict(ckpt['sdf_network'])
|
| 231 |
+
self.iter_step = ckpt.get('iter_step', 0)
|
| 232 |
+
|
| 233 |
+
# ------------------------------------------------------------------
|
| 234 |
+
# VG stage helpers
|
| 235 |
+
# ------------------------------------------------------------------
|
| 236 |
+
@torch.no_grad()
|
| 237 |
+
def get_surface_queries(self, noisy_pts=False):
|
| 238 |
+
"""Project point_gt onto the learned SDF surface."""
|
| 239 |
+
sdf_level = self.project_sdf_level
|
| 240 |
+
queries = self.point_gt.clone()
|
| 241 |
+
if noisy_pts or sdf_level != 0.0:
|
| 242 |
+
queries = self.project_queries(queries, sdf_level)
|
| 243 |
+
|
| 244 |
+
n = len(queries)
|
| 245 |
+
target = min(self.surface_queries_size, n + len(self.sample))
|
| 246 |
+
if target > n:
|
| 247 |
+
pad_size = target - n
|
| 248 |
+
# Use FPS on projected samples
|
| 249 |
+
pad_queries = self.sample.clone()
|
| 250 |
+
pad_queries = self.project_queries(pad_queries, sdf_level)
|
| 251 |
+
idx = fps_sample(pad_queries.cpu().numpy(), pad_size)
|
| 252 |
+
pad_queries = pad_queries[idx]
|
| 253 |
+
queries = torch.cat([queries, pad_queries], dim=0)
|
| 254 |
+
return queries.detach()
|
| 255 |
+
|
| 256 |
+
@torch.no_grad()
|
| 257 |
+
def project_queries(self, queries, sdf_level):
|
| 258 |
+
batch_size = 100_000
|
| 259 |
+
out = []
|
| 260 |
+
for i in range(0, len(queries), batch_size):
|
| 261 |
+
batch = queries[i:i + batch_size]
|
| 262 |
+
for _ in range(10):
|
| 263 |
+
grad, sdf = self.sdf_net.gradient(batch)
|
| 264 |
+
grad = F.normalize(grad, dim=-1)
|
| 265 |
+
batch = batch - grad * (sdf - sdf_level)
|
| 266 |
+
out.append(batch)
|
| 267 |
+
return torch.cat(out, dim=0)
|
| 268 |
+
|
| 269 |
+
# ------------------------------------------------------------------
|
| 270 |
+
# VG stage
|
| 271 |
+
# ------------------------------------------------------------------
|
| 272 |
+
def train_vg(self, vertices_size=None):
|
| 273 |
+
if vertices_size is None:
|
| 274 |
+
vertices_size = self.vertices_size
|
| 275 |
+
print(f"\n=== Stage 2: Vertex Generation ({vertices_size} vertices) ===")
|
| 276 |
+
self.vg_net.train()
|
| 277 |
+
self.sdf_net.eval()
|
| 278 |
+
|
| 279 |
+
# Build target surface queries
|
| 280 |
+
print("Projecting surface queries...")
|
| 281 |
+
point_gt = self.get_surface_queries()
|
| 282 |
+
print(f" Surface queries: {len(point_gt)}")
|
| 283 |
+
|
| 284 |
+
# Sample initial vertices via FPS
|
| 285 |
+
sample_points = self.fps_select_vertices(point_gt, vertices_size)
|
| 286 |
+
sample_normal, _ = self.sdf_net.gradient(sample_points)
|
| 287 |
+
sample_normal = F.normalize(sample_normal.detach(), dim=-1)
|
| 288 |
+
|
| 289 |
+
# Curvature on surface
|
| 290 |
+
normal_gt, _ = self.sdf_net.gradient(point_gt)
|
| 291 |
+
normal_gt = F.normalize(normal_gt.detach(), dim=-1)
|
| 292 |
+
curvature_surface = loss_utils.cal_curvature_with_normal(
|
| 293 |
+
point_gt, normal_gt, knn=min(16, len(point_gt) - 1)).detach()
|
| 294 |
+
|
| 295 |
+
# Generate curriculum sizes
|
| 296 |
+
batch_sizes = self.generate_list_with_ratio(vertices_size)
|
| 297 |
+
print(f" Curriculum sizes: {batch_sizes}")
|
| 298 |
+
|
| 299 |
+
cur_size_idx = 0
|
| 300 |
+
current_batch_size = batch_sizes[cur_size_idx]
|
| 301 |
+
sample_points = self.fps_select_vertices(point_gt, current_batch_size)
|
| 302 |
+
sample_normal, _ = self.sdf_net.gradient(sample_points)
|
| 303 |
+
sample_normal = F.normalize(sample_normal.detach(), dim=-1)
|
| 304 |
+
|
| 305 |
+
pbar = tqdm(range(self.vg_iters), desc="VG")
|
| 306 |
+
size_update_freq = self.vg_iters // (self.update_size + 1)
|
| 307 |
+
if size_update_freq == 0:
|
| 308 |
+
size_update_freq = self.vg_iters
|
| 309 |
+
|
| 310 |
+
nearest_clamp = self.cal_nearest_clamp(sample_points)
|
| 311 |
+
|
| 312 |
+
for iter_i in pbar:
|
| 313 |
+
generated = self.vg_net(sample_points, sample_normal)
|
| 314 |
+
vertices_grad, _ = self.sdf_net.gradient(generated)
|
| 315 |
+
|
| 316 |
+
loss = loss_utils.cal_vg_loss(
|
| 317 |
+
point_gt, normal_gt, curvature_surface,
|
| 318 |
+
generated, vertices_grad,
|
| 319 |
+
self.loss_weights_vg, nearest_clamp)
|
| 320 |
+
|
| 321 |
+
self.vg_optimizer.zero_grad()
|
| 322 |
+
loss.backward(retain_graph=True)
|
| 323 |
+
self.vg_optimizer.step()
|
| 324 |
+
|
| 325 |
+
if (iter_i + 1) % 500 == 0:
|
| 326 |
+
pbar.set_postfix(loss=f"{loss.item():.4f}")
|
| 327 |
+
|
| 328 |
+
# Curriculum: increase vertex count
|
| 329 |
+
if (iter_i + 1) % size_update_freq == 0:
|
| 330 |
+
cur_size_idx += 1
|
| 331 |
+
if cur_size_idx < len(batch_sizes):
|
| 332 |
+
current_batch_size = batch_sizes[cur_size_idx]
|
| 333 |
+
moved = self.move_to_surface(generated)
|
| 334 |
+
curv = loss_utils.cal_curvature_with_normal(
|
| 335 |
+
moved, F.normalize(vertices_grad.detach(), dim=-1),
|
| 336 |
+
knn=min(16, len(moved) - 1))
|
| 337 |
+
sample_points = self.upsample(curv, moved, point_gt, current_batch_size)
|
| 338 |
+
sample_points = sample_points.detach()
|
| 339 |
+
sn, _ = self.sdf_net.gradient(sample_points)
|
| 340 |
+
sample_normal = F.normalize(sn.detach(), dim=-1)
|
| 341 |
+
nearest_clamp = self.cal_nearest_clamp(sample_points)
|
| 342 |
+
|
| 343 |
+
# Final projection to surface
|
| 344 |
+
final_vertices = self.move_to_surface(generated).detach().cpu().numpy()
|
| 345 |
+
print(f" Generated {len(final_vertices)} vertices.")
|
| 346 |
+
return final_vertices
|
| 347 |
+
|
| 348 |
+
def generate_list_with_ratio(self, final_size):
|
| 349 |
+
"""Build curriculum vertex counts."""
|
| 350 |
+
sizes = [int(final_size / (self.update_ratio ** (self.update_size - i)))
|
| 351 |
+
for i in range(self.update_size)]
|
| 352 |
+
sizes.append(final_size)
|
| 353 |
+
# Ensure monotonic
|
| 354 |
+
for i in range(1, len(sizes)):
|
| 355 |
+
sizes[i] = max(sizes[i], sizes[i - 1] + 1)
|
| 356 |
+
return sizes
|
| 357 |
+
|
| 358 |
+
def fps_select_vertices(self, point_gt, batch_size):
|
| 359 |
+
idx = fps_sample(point_gt.cpu().numpy(), min(batch_size, len(point_gt)))
|
| 360 |
+
return point_gt[idx].detach()
|
| 361 |
+
|
| 362 |
+
def cal_nearest_clamp(self, sample_pts):
|
| 363 |
+
pts_np = sample_pts.detach().cpu().numpy()
|
| 364 |
+
from scipy.spatial import KDTree
|
| 365 |
+
tree = KDTree(pts_np)
|
| 366 |
+
_, idx = tree.query(pts_np, k=2)
|
| 367 |
+
idx = torch.from_numpy(idx[:, 1]).long().to(sample_pts.device)
|
| 368 |
+
neigh = sample_pts[idx]
|
| 369 |
+
dist = torch.linalg.norm(neigh - sample_pts, ord=2, dim=-1) ** 2
|
| 370 |
+
return dist.mean().item()
|
| 371 |
+
|
| 372 |
+
def move_to_surface(self, generated, step=10):
|
| 373 |
+
for _ in range(step):
|
| 374 |
+
grad, sdf = self.sdf_net.gradient(generated)
|
| 375 |
+
grad = F.normalize(grad.detach(), dim=-1)
|
| 376 |
+
generated = generated - grad * (sdf.detach() - self.project_sdf_level)
|
| 377 |
+
return generated.detach()
|
| 378 |
+
|
| 379 |
+
def upsample(self, curvature, pts, point_gt, sample_size):
|
| 380 |
+
"""Upsample to target size by adding high-curvature neighbors."""
|
| 381 |
+
if len(pts) >= sample_size:
|
| 382 |
+
return pts[:sample_size]
|
| 383 |
+
up = sample_size - len(pts)
|
| 384 |
+
topk = min(up, len(pts))
|
| 385 |
+
_, top_idx = torch.topk(curvature.view(-1), k=topk, largest=True)
|
| 386 |
+
best = pts[top_idx]
|
| 387 |
+
from scipy.spatial import KDTree
|
| 388 |
+
tree = KDTree(point_gt.cpu().numpy())
|
| 389 |
+
_, idx = tree.query(best.cpu().numpy(), k=1)
|
| 390 |
+
idx = torch.from_numpy(idx).long().to(pts.device)
|
| 391 |
+
added = point_gt[idx]
|
| 392 |
+
return torch.cat([pts, added], dim=0)
|
| 393 |
+
|
| 394 |
+
# ------------------------------------------------------------------
|
| 395 |
+
# Meshing
|
| 396 |
+
# ------------------------------------------------------------------
|
| 397 |
+
def generate_mesh(self, vertices, save_path=None):
|
| 398 |
+
print("\n=== Meshing ===")
|
| 399 |
+
v, f = mesh_utils.delaunay_meshing(
|
| 400 |
+
vertices, self.sdf_net,
|
| 401 |
+
sdf_threshold=self.project_sdf_level,
|
| 402 |
+
k_samples=self.k_samples,
|
| 403 |
+
device=self.device)
|
| 404 |
+
|
| 405 |
+
if len(f) > 0:
|
| 406 |
+
v, f = mesh_utils.add_mid_vertices(v, f)
|
| 407 |
+
|
| 408 |
+
# Denormalize
|
| 409 |
+
v = denormalize_pointcloud(v, self.loc, self.scale)
|
| 410 |
+
|
| 411 |
+
if save_path:
|
| 412 |
+
if save_path.endswith('.obj'):
|
| 413 |
+
save_mesh_obj(save_path, v, f)
|
| 414 |
+
else:
|
| 415 |
+
save_mesh_ply(save_path, v, f)
|
| 416 |
+
print(f"Saved mesh to {save_path}")
|
| 417 |
+
return v, f
|
| 418 |
+
|
| 419 |
+
# ------------------------------------------------------------------
|
| 420 |
+
# End-to-end
|
| 421 |
+
# ------------------------------------------------------------------
|
| 422 |
+
def run(self, mesh_path=None):
|
| 423 |
+
self.train_sdf()
|
| 424 |
+
vertices = self.train_vg()
|
| 425 |
+
v, f = self.generate_mesh(vertices, save_path=mesh_path)
|
| 426 |
+
return v, f
|