rabbitKabbit commited on
Commit
fb29fbc
·
verified ·
1 Parent(s): 93504d6

Add mast3r_mesh_gpu.py: mast3r_mesh.py with TSDF fusion on CUDA:0 when available (used for I87X meshes)

Browse files
Bedroom1/MasterSlam1_ScanVideo1/mast3r_mesh_gpu.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ mast3r_mesh.py - textured room mesh from a MASt3R-SLAM run, by TSDF fusion.
4
+
5
+ myenv/bin/python mast3r_mesh.py # run dir = this folder
6
+ myenv/bin/python mast3r_mesh.py --video ../ScanVideos/Video1.mp4 # texture from full-res video
7
+ myenv/bin/python mast3r_mesh.py RUN_DIR -o out.obj --voxel 0.008
8
+
9
+ Why not Poisson on scan.ply (ply2obj.py --mesh): an uncalibrated monocular SLAM cloud has
10
+ drift (walls in 2-3 offset layers), floaters and no reliable normals; Poisson turns that
11
+ into blobs, and colours averaged from points are blurry. This script does what RGB-D
12
+ mappers like RTAB-Map do instead:
13
+
14
+ 1. Rebuild each keyframe's depth map. MASt3R-SLAM writes scan.ply keyframe by keyframe in
15
+ pixel (raster) order, with each point's colour copied from keyframes/<t>.png, so a
16
+ greedy colour match recovers the keyframe + pixel of every point.
17
+ 2. Fit a pinhole camera per keyframe (scan.txt pose + pixel <-> point), drop points that
18
+ don't reproject (colour coincidences) and flying pixels at depth edges.
19
+ 2b. Refine keyframe poses like RTAB-Map's graph optimisation: ICP between overlapping
20
+ keyframes, then a pose graph solve, so SLAM drift doesn't leave doubled surfaces.
21
+ 3. Fuse all depth maps in a TSDF volume (Open3D) and extract the surface. Offset layers
22
+ closer than --trunc merge into one surface.
23
+ 4. UV-unwrap (xatlas) and texture each texel from the camera images that see it
24
+ (z-tested against the mesh, weighted by viewing angle and distance). With --video the
25
+ full-resolution frames are used instead of the 512 px keyframes.
26
+
27
+ Inputs (in RUN_DIR): scan.ply, scan.txt, keyframes/scan/<timestamp>.png
28
+ Outputs: <out>.obj, <out>.mtl, <out>.png. Same coordinate frame as scan.ply.
29
+ Needs numpy, scipy, open3d, xatlas; --video also needs ffmpeg/ffprobe on PATH.
30
+ """
31
+ import argparse
32
+ import os
33
+ import subprocess
34
+ import sys
35
+
36
+ import numpy as np
37
+
38
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
39
+ from ply2obj import read_ply, write_rows # noqa: E402
40
+
41
+
42
+ def log(*a):
43
+ print("[mast3r_mesh]", *a, file=sys.stderr, flush=True)
44
+
45
+
46
+ def quat_to_R(qx, qy, qz, qw):
47
+ n = np.sqrt(qx * qx + qy * qy + qz * qz + qw * qw)
48
+ x, y, z, w = qx / n, qy / n, qz / n, qw / n
49
+ return np.array([
50
+ [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
51
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
52
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
53
+ ])
54
+
55
+
56
+ def read_rgb(path):
57
+ import open3d as o3d
58
+ a = np.asarray(o3d.io.read_image(path))
59
+ if a.ndim == 2:
60
+ a = np.repeat(a[..., None], 3, axis=2)
61
+ return np.ascontiguousarray(a[..., :3]).astype(np.uint8)
62
+
63
+
64
+ def pack(rgb):
65
+ rgb = rgb.astype(np.int64)
66
+ return (rgb[..., 0] << 16) | (rgb[..., 1] << 8) | rgb[..., 2]
67
+
68
+
69
+ # ----------------------------------------------------------------------------- 1. load + assign
70
+ def load_run(run_dir):
71
+ _, data, _ = read_ply(os.path.join(run_dir, "scan.ply"))
72
+ v = data["vertex"]
73
+ P = np.stack([v["x"], v["y"], v["z"]], 1).astype(np.float64)
74
+ rgb = np.stack([v["red"], v["green"], v["blue"]], 1)
75
+ if rgb.dtype != np.uint8:
76
+ raise ValueError("expected uchar colours in scan.ply (MASt3R-SLAM output)")
77
+ traj = np.loadtxt(os.path.join(run_dir, "scan.txt"), ndmin=2)
78
+ kdir = os.path.join(run_dir, "keyframes", "scan")
79
+ by_t = {float(f[:-4]): f for f in os.listdir(kdir) if f.endswith(".png")}
80
+ imgs = []
81
+ for t in traj[:, 0]:
82
+ name = by_t.get(float(t))
83
+ if name is None:
84
+ raise FileNotFoundError(f"no keyframe image for timestamp {t} in {kdir}")
85
+ imgs.append(read_rgb(os.path.join(kdir, name)))
86
+ log(f"{len(P):,} points, {len(imgs)} keyframes {imgs[0].shape[1]}x{imgs[0].shape[0]}")
87
+ return P, rgb, traj, imgs
88
+
89
+
90
+ def assign_pixels(rgb, imgs):
91
+ """Greedy subsequence match of point colours against keyframe pixels in raster order."""
92
+ cols = pack(rgb).tolist()
93
+ n, p = len(cols), 0
94
+ pix = np.full(n, -1, np.int64)
95
+ kf = np.full(n, -1, np.int64)
96
+ for k, im in enumerate(imgs):
97
+ start = p
98
+ for i, c in enumerate(pack(im).reshape(-1).tolist()):
99
+ if p < n and cols[p] == c:
100
+ pix[p] = i
101
+ p += 1
102
+ kf[start:p] = k
103
+ if p != n:
104
+ raise ValueError(f"only {p:,} of {n:,} points matched keyframe pixels: scan.ply is not in "
105
+ "MASt3R-SLAM keyframe/raster order, or keyframes/ is from another run")
106
+ return pix, kf
107
+
108
+
109
+ # ----------------------------------------------------------------------------- 2. cameras + depth
110
+ def fit_camera(X, pix, W, thresh):
111
+ u, v, z = (pix % W).astype(np.float64), (pix // W).astype(np.float64), X[:, 2]
112
+ ok = z > 1e-6
113
+ for th in (50.0, 10.0, thresh):
114
+ a = X[ok, 0] / z[ok]
115
+ b = X[ok, 1] / z[ok]
116
+ fx, cx = np.linalg.lstsq(np.stack([a, np.ones_like(a)], 1), u[ok], rcond=None)[0]
117
+ fy, cy = np.linalg.lstsq(np.stack([b, np.ones_like(b)], 1), v[ok], rcond=None)[0]
118
+ with np.errstate(divide="ignore", invalid="ignore"):
119
+ r = np.hypot(fx * X[:, 0] / z + cx - u, fy * X[:, 1] / z + cy - v)
120
+ ok = (z > 1e-6) & (r < th)
121
+ return np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]), ok
122
+
123
+
124
+ def drop_depth_edges(D, rel):
125
+ pad = np.pad(D, 1, mode="edge")
126
+ bad = np.zeros(D.shape, bool)
127
+ for nb in (pad[:-2, 1:-1], pad[2:, 1:-1], pad[1:-1, :-2], pad[1:-1, 2:]):
128
+ bad |= (nb > 0) & (np.abs(nb - D) > rel * D)
129
+ D = D.copy()
130
+ D[bad] = 0
131
+ return D
132
+
133
+
134
+ def build_cameras(P, traj, imgs, pix, kf, reproj, edge):
135
+ H, W = imgs[0].shape[:2]
136
+ cams = []
137
+ for k in range(len(imgs)):
138
+ m = kf == k
139
+ R = quat_to_R(*traj[k, 4:8])
140
+ t = traj[k, 1:4]
141
+ X = (P[m] - t) @ R # world -> camera (scan.txt drops the Sim3 scale; depth stays in world units)
142
+ cam = {"R": R, "t": t, "img": imgs[k], "depth": np.zeros((H, W), np.float32)}
143
+ if m.sum() < 100:
144
+ log(f"keyframe {k}: only {m.sum()} points, skipped")
145
+ cam["K"] = None
146
+ cams.append(cam)
147
+ continue
148
+ K, ok = fit_camera(X, pix[m], W, reproj)
149
+ D = np.zeros(H * W, np.float32)
150
+ D[pix[m][ok]] = X[ok, 2]
151
+ D = drop_depth_edges(D.reshape(H, W), edge)
152
+ cam["K"], cam["depth"] = K, D
153
+ cams.append(cam)
154
+ if k % 10 == 0 or k == len(imgs) - 1:
155
+ log(f"keyframe {k}: f={K[0, 0]:.0f} c=({K[0, 2]:.0f},{K[1, 2]:.0f}), "
156
+ f"{int((D > 0).sum()):,}/{int(m.sum()):,} depth px kept")
157
+ return cams
158
+
159
+
160
+ # ----------------------------------------------------------------------------- 2b. pose refinement
161
+ def cam_to_world(c):
162
+ T = np.eye(4)
163
+ T[:3, :3] = c["R"]
164
+ T[:3, 3] = c["t"]
165
+ return T
166
+
167
+
168
+ def cam_cloud(c, voxel):
169
+ """Keyframe depth map -> downsampled cloud with normals, in camera coordinates."""
170
+ import open3d as o3d
171
+ D, K = c["depth"], c["K"]
172
+ v, u = np.nonzero(D > 0)
173
+ z = D[v, u].astype(np.float64)
174
+ X = np.stack([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z], 1)
175
+ pc = o3d.geometry.PointCloud(o3d.utility.Vector3dVector(X))
176
+ pc = pc.voxel_down_sample(voxel)
177
+ pc.estimate_normals(o3d.geometry.KDTreeSearchParamHybrid(radius=voxel * 3, max_nn=30))
178
+ pc.orient_normals_towards_camera_location(np.zeros(3))
179
+ return pc
180
+
181
+
182
+ def refine_poses(cams, voxel, max_dist, min_overlap):
183
+ """What RTAB-Map does after odometry: register overlapping views (ICP), add those as
184
+ loop-closure constraints, and solve the pose graph so drift is spread out instead of
185
+ showing up as doubled walls. Depth maps stay as they are; only the keyframe poses move."""
186
+ import open3d as o3d
187
+ from scipy.spatial import cKDTree
188
+ reg = o3d.pipelines.registration
189
+ ids = [k for k, c in enumerate(cams) if c["K"] is not None]
190
+ clouds = {k: cam_cloud(cams[k], voxel) for k in ids}
191
+ T = {k: cam_to_world(cams[k]) for k in ids}
192
+ world = {k: np.asarray(clouds[k].points) @ T[k][:3, :3].T + T[k][:3, 3] for k in ids}
193
+ trees = {k: cKDTree(world[k]) for k in ids}
194
+ node = {k: i for i, k in enumerate(ids)}
195
+ graph = reg.PoseGraph()
196
+ for k in ids:
197
+ graph.nodes.append(reg.PoseGraphNode(T[k]))
198
+
199
+ n_odo = n_loop = n_fail = 0
200
+ for i, s in enumerate(ids):
201
+ for t in ids[i + 1:]:
202
+ consecutive = t == ids[i + 1]
203
+ d, _ = trees[t].query(world[s][::4], distance_upper_bound=max_dist)
204
+ if np.isfinite(d).mean() < min_overlap and not consecutive:
205
+ continue
206
+ init = np.linalg.inv(T[t]) @ T[s] # source (s) camera -> target (t) camera
207
+ tf = init
208
+ for md in (max_dist, max_dist / 2, max_dist / 4):
209
+ res = reg.registration_icp(
210
+ clouds[s], clouds[t], md, tf,
211
+ reg.TransformationEstimationPointToPlane(reg.TukeyLoss(k=md)),
212
+ reg.ICPConvergenceCriteria(max_iteration=30))
213
+ tf = res.transformation
214
+ ok = res.fitness >= min_overlap
215
+ if not ok:
216
+ if not consecutive:
217
+ continue
218
+ tf = init # keep the SLAM odometry so the graph stays connected
219
+ n_fail += 1
220
+ info = reg.get_information_matrix_from_point_clouds(clouds[s], clouds[t], max_dist / 4, tf)
221
+ graph.edges.append(reg.PoseGraphEdge(node[s], node[t], tf, info, uncertain=not consecutive))
222
+ n_odo += consecutive
223
+ n_loop += not consecutive
224
+ log(f"refine: {n_odo} odometry edges ({n_fail} kept SLAM pose, ICP failed), {n_loop} loop edges")
225
+
226
+ o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Error)
227
+ reg.global_optimization(
228
+ graph, reg.GlobalOptimizationLevenbergMarquardt(), reg.GlobalOptimizationConvergenceCriteria(),
229
+ reg.GlobalOptimizationOption(max_correspondence_distance=max_dist / 4,
230
+ edge_prune_threshold=0.25, reference_node=0))
231
+ moved = []
232
+ for k in ids:
233
+ P = np.asarray(graph.nodes[node[k]].pose)
234
+ moved.append(np.linalg.norm(P[:3, 3] - cams[k]["t"]))
235
+ cams[k]["R"], cams[k]["t"] = P[:3, :3].copy(), P[:3, 3].copy()
236
+ log(f"refine: keyframes moved median {np.median(moved):.3f}, max {np.max(moved):.3f} (scene units)")
237
+
238
+
239
+ # ----------------------------------------------------------------------------- 3. TSDF
240
+ def fuse(cams, voxel, trunc, min_weight):
241
+ # Tensor VoxelBlockGrid: the legacy ScalableTSDFVolume extracts an empty mesh in Open3D 0.20 (macOS arm64)
242
+ import open3d as o3d
243
+ core = o3d.core
244
+ DEV = core.Device("CUDA:0" if core.cuda.is_available() else "CPU:0") # GPU patch (server run)
245
+ log(f"tsdf device: {DEV}")
246
+ vbg = o3d.t.geometry.VoxelBlockGrid(
247
+ attr_names=("tsdf", "weight", "color"), attr_dtypes=(core.float32, core.float32, core.float32),
248
+ attr_channels=((1), (1), (3)), voxel_size=voxel, block_resolution=8, block_count=50000,
249
+ device=DEV)
250
+ for c in cams:
251
+ if c["K"] is None:
252
+ continue
253
+ K = core.Tensor(c["K"], core.float64)
254
+ E = core.Tensor(world_to_cam(c), core.float64)
255
+ depth = o3d.t.geometry.Image(core.Tensor(c["depth"])).to(DEV)
256
+ color = o3d.t.geometry.Image(core.Tensor(c["img"].astype(np.float32))).to(DEV)
257
+ blocks = vbg.compute_unique_block_coordinates(depth, K, E, 1.0, 1e6, trunc_voxel_multiplier=trunc / voxel)
258
+ vbg.integrate(blocks, depth, color, K, K, E, 1.0, 1e6, trunc_voxel_multiplier=trunc / voxel)
259
+ tm = vbg.extract_triangle_mesh(weight_threshold=min_weight)
260
+ mesh = tm.cpu().to_legacy()
261
+ if mesh.has_vertex_colors():
262
+ mesh.vertex_colors = o3d.utility.Vector3dVector(np.asarray(mesh.vertex_colors).clip(0, 255) / 255)
263
+ log(f"tsdf: {len(mesh.vertices):,} verts, {len(mesh.triangles):,} tris "
264
+ f"(voxel {voxel:.4g}, trunc {trunc:.4g}, min weight {min_weight})")
265
+ return mesh
266
+
267
+
268
+ def world_to_cam(c):
269
+ E = np.eye(4)
270
+ E[:3, :3] = c["R"].T
271
+ E[:3, 3] = -c["R"].T @ c["t"]
272
+ return E
273
+
274
+
275
+ def clean_mesh(mesh, min_cluster, tris):
276
+ tri_cluster, n_tri, _ = mesh.cluster_connected_triangles()
277
+ tri_cluster, n_tri = np.asarray(tri_cluster), np.asarray(n_tri)
278
+ small = n_tri[tri_cluster] < min_cluster * len(tri_cluster)
279
+ mesh.remove_triangles_by_mask(small)
280
+ mesh.remove_unreferenced_vertices()
281
+ log(f"clean: removed {int(small.sum()):,} tris in {int((n_tri < min_cluster * len(tri_cluster)).sum()):,} "
282
+ f"small pieces")
283
+ if len(mesh.triangles) > tris:
284
+ mesh = mesh.simplify_quadric_decimation(target_number_of_triangles=tris)
285
+ mesh.remove_degenerate_triangles()
286
+ mesh.remove_unreferenced_vertices()
287
+ mesh.compute_vertex_normals()
288
+ log(f"clean: {len(mesh.vertices):,} verts, {len(mesh.triangles):,} tris")
289
+ return mesh
290
+
291
+
292
+ # ----------------------------------------------------------------------------- 4. colour sources
293
+ def video_size(path):
294
+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
295
+ "stream=width,height:stream_side_data=rotation", "-of", "default=nw=1", path],
296
+ capture_output=True, text=True, check=True).stdout
297
+ kv = dict(l.split("=", 1) for l in out.split() if "=" in l)
298
+ w, h = int(kv["width"]), int(kv["height"])
299
+ if abs(int(float(kv.get("rotation", 0)))) % 180 == 90: # ffmpeg auto-rotates on decode
300
+ w, h = h, w
301
+ return w, h
302
+
303
+
304
+ def video_frames(path):
305
+ vw, vh = video_size(path)
306
+ proc = subprocess.Popen(["ffmpeg", "-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
307
+ stdout=subprocess.PIPE)
308
+ n = vw * vh * 3
309
+ while True:
310
+ buf = proc.stdout.read(n)
311
+ if len(buf) < n:
312
+ break
313
+ yield np.frombuffer(buf, np.uint8).reshape(vh, vw, 3)
314
+ proc.wait()
315
+
316
+
317
+ def attach_video(cams, path, max_err):
318
+ """Find each keyframe's source frame (best match after MASt3R's resize + centre crop)."""
319
+ H, W = cams[0]["img"].shape[:2]
320
+ vw, vh = video_size(path)
321
+ s = min(vw / W, vh / H)
322
+ ox, oy = (vw - W * s) / 2, (vh - H * s) / 2
323
+ step = 4
324
+ ref = np.stack([c["img"][::step, ::step] for c in cams]).astype(np.float32)
325
+ ys = np.clip(((np.arange(0, H, step) + 0.5) * s - 0.5 + oy).round().astype(int), 0, vh - 1)
326
+ xs = np.clip(((np.arange(0, W, step) + 0.5) * s - 0.5 + ox).round().astype(int), 0, vw - 1)
327
+ best = np.full(len(cams), np.inf)
328
+ keep = [None] * len(cams)
329
+ log(f"video: {path} {vw}x{vh}, matching {len(cams)} keyframes (scale {s:.3g})")
330
+ for fr in video_frames(path):
331
+ # box-average around each sample so a 3.75x downscale compares like with like
332
+ r = max(int(s // 2), 0)
333
+ sm = np.zeros((len(ys), len(xs), 3), np.float32)
334
+ for dy in range(-r, r + 1):
335
+ for dx in range(-r, r + 1):
336
+ sm += fr[np.clip(ys + dy, 0, vh - 1)][:, np.clip(xs + dx, 0, vw - 1)]
337
+ sm /= (2 * r + 1) ** 2
338
+ err = np.abs(ref - sm).mean(axis=(1, 2, 3))
339
+ better = err < best
340
+ for k in np.nonzero(better)[0]:
341
+ best[k], keep[k] = err[k], fr.copy()
342
+ used = 0
343
+ for k, c in enumerate(cams):
344
+ if keep[k] is None or best[k] > max_err:
345
+ log(f"video: keyframe {k} best match error {best[k]:.1f} > {max_err}, using keyframe image")
346
+ continue
347
+ c["src"] = keep[k]
348
+ c["src_K"] = scale_K(c["K"], s, ox, oy) if c["K"] is not None else None
349
+ used += 1
350
+ log(f"video: {used}/{len(cams)} keyframes textured from video (match error median {np.median(best):.2f})")
351
+
352
+
353
+ def scale_K(K, s, ox, oy):
354
+ K2 = K.copy()
355
+ K2[0, 0] *= s
356
+ K2[1, 1] *= s
357
+ K2[0, 2] = (K[0, 2] + 0.5) * s - 0.5 + ox
358
+ K2[1, 2] = (K[1, 2] + 0.5) * s - 0.5 + oy
359
+ return K2
360
+
361
+
362
+ def bilinear(img, u, v):
363
+ h, w = img.shape[:2]
364
+ u = np.clip(u, 0, w - 1.001)
365
+ v = np.clip(v, 0, h - 1.001)
366
+ x0, y0 = u.astype(np.int64), v.astype(np.int64)
367
+ fx, fy = (u - x0)[:, None], (v - y0)[:, None]
368
+ a = img[y0, x0].astype(np.float32)
369
+ b = img[y0, x0 + 1].astype(np.float32)
370
+ c = img[y0 + 1, x0].astype(np.float32)
371
+ d = img[y0 + 1, x0 + 1].astype(np.float32)
372
+ return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy
373
+
374
+
375
+ def render_depths(mesh, cams):
376
+ """Depth of the fused mesh seen from each keyframe camera, for occlusion tests."""
377
+ import open3d as o3d
378
+ scene = o3d.t.geometry.RaycastingScene()
379
+ scene.add_triangles(o3d.t.geometry.TriangleMesh.from_legacy(mesh))
380
+ for c in cams:
381
+ if c["K"] is None:
382
+ continue
383
+ H, W = c["depth"].shape
384
+ rays = scene.create_rays_pinhole(o3d.core.Tensor(c["K"]), o3d.core.Tensor(world_to_cam(c)), W, H)
385
+ hit = scene.cast_rays(rays)["t_hit"].numpy()
386
+ r = rays.numpy()
387
+ pts = r[..., :3] + r[..., 3:] * hit[..., None]
388
+ z = ((pts - c["t"]) @ c["R"])[..., 2]
389
+ z[~np.isfinite(hit)] = np.inf
390
+ c["zbuf"] = z.astype(np.float32)
391
+
392
+
393
+ def colour_texels(P, N, cams, voxel, power, chunk=1_000_000):
394
+ acc = np.zeros((len(P), 3), np.float32)
395
+ wsum = np.zeros(len(P), np.float32)
396
+ for c in cams:
397
+ if c["K"] is None:
398
+ continue
399
+ K, R, t, zb = c["K"], c["R"], c["t"], c["zbuf"]
400
+ H, W = zb.shape
401
+ src = c.get("src", c["img"])
402
+ sK = c.get("src_K", K) if "src" in c else K
403
+ border = 0.08 * W
404
+ for i in range(0, len(P), chunk):
405
+ p, n = P[i:i + chunk], N[i:i + chunk]
406
+ X = (p - t) @ R
407
+ z = X[:, 2]
408
+ with np.errstate(divide="ignore", invalid="ignore"):
409
+ u = K[0, 0] * X[:, 0] / z + K[0, 2]
410
+ v = K[1, 1] * X[:, 1] / z + K[1, 2]
411
+ inb = (z > 1e-6) & (u >= 0) & (u <= W - 1) & (v >= 0) & (v <= H - 1)
412
+ idx = np.nonzero(inb)[0]
413
+ if not len(idx):
414
+ continue
415
+ zr = zb[v[idx].round().astype(int), u[idx].round().astype(int)]
416
+ vis = np.abs(z[idx] - zr) < np.maximum(2 * voxel, 0.02 * z[idx])
417
+ idx = idx[vis]
418
+ if not len(idx):
419
+ continue
420
+ view = t - p[idx]
421
+ dist = np.linalg.norm(view, axis=1)
422
+ cos = np.einsum("ij,ij->i", n[idx], view) / np.maximum(dist, 1e-9)
423
+ edge = np.minimum.reduce([u[idx], W - 1 - u[idx], v[idx], H - 1 - v[idx]]) / border
424
+ w = (np.clip(cos, 0, 1) * np.clip(edge, 0, 1) / np.maximum(dist, 1e-6)) ** power
425
+ good = w > 0
426
+ idx, w = idx[good], w[good].astype(np.float32)
427
+ Xs = X[idx]
428
+ us = sK[0, 0] * Xs[:, 0] / Xs[:, 2] + sK[0, 2]
429
+ vs = sK[1, 1] * Xs[:, 1] / Xs[:, 2] + sK[1, 2]
430
+ acc[i + idx] += w[:, None] * bilinear(src, us, vs)
431
+ wsum[i + idx] += w
432
+ seen = wsum > 0
433
+ acc[seen] /= wsum[seen, None]
434
+ return acc, seen
435
+
436
+
437
+ # ----------------------------------------------------------------------------- textured OBJ
438
+ def write_textured(mesh, cams, dst, size, voxel, power):
439
+ import open3d as o3d
440
+ import xatlas
441
+ from scipy import ndimage
442
+
443
+ V = np.asarray(mesh.vertices)
444
+ T = np.asarray(mesh.triangles)
445
+ N = np.asarray(mesh.vertex_normals)
446
+ C = np.asarray(mesh.vertex_colors) if mesh.has_vertex_colors() else np.full_like(V, 0.5)
447
+ log(f"texture: unwrapping {len(T):,} tris with xatlas (slow: ~30 s per 60k tris)")
448
+ atlas = xatlas.Atlas()
449
+ atlas.add_mesh(V.astype(np.float32), T.astype(np.uint32))
450
+ chart = xatlas.ChartOptions()
451
+ chart.max_iterations = 1
452
+ pack_opt = xatlas.PackOptions()
453
+ pack_opt.resolution = size
454
+ pack_opt.padding = 4
455
+ atlas.generate(chart, pack_opt)
456
+ vmap, idx, uv = atlas[0]
457
+ if uv.max() > 1.5: # older xatlas wheels return texel units
458
+ uv = uv / np.array([atlas.width, atlas.height])
459
+ idx = idx.astype(np.int64)
460
+
461
+ tm = o3d.t.geometry.TriangleMesh()
462
+ tm.vertex.positions = o3d.core.Tensor(V[vmap].astype(np.float32))
463
+ tm.vertex.normals = o3d.core.Tensor(N[vmap].astype(np.float32))
464
+ tm.vertex.colors = o3d.core.Tensor(C[vmap].astype(np.float32))
465
+ tm.triangle.indices = o3d.core.Tensor(idx.astype(np.int32))
466
+ tm.triangle.texture_uvs = o3d.core.Tensor(uv[idx].astype(np.float32))
467
+ maps = tm.bake_vertex_attr_textures(size, {"positions", "normals", "colors"}, 8, -1e6, False)
468
+ pos, nrm, col = (maps[k].numpy() for k in ("positions", "normals", "colors"))
469
+ valid = pos[..., 0] > -1e5
470
+ P = pos[valid].astype(np.float64)
471
+ Nn = nrm[valid].astype(np.float64)
472
+ Nn /= np.maximum(np.linalg.norm(Nn, axis=1, keepdims=True), 1e-9)
473
+ log(f"texture: colouring {len(P):,} texels from {sum(c['K'] is not None for c in cams)} views")
474
+ render_depths(mesh, cams)
475
+ rgb, seen = colour_texels(P, Nn, cams, voxel, power)
476
+ rgb[~seen] = col[valid][~seen] * 255 # never seen unoccluded: fall back to TSDF colour
477
+ log(f"texture: {int(seen.sum()):,} texels from images, {int((~seen).sum()):,} from TSDF colour")
478
+
479
+ tex = np.zeros((size, size, 3), np.uint8)
480
+ tex[valid] = rgb.clip(0, 255).astype(np.uint8)
481
+ # bleed chart colours into the gutters so mipmapping doesn't pull in black seams
482
+ _, (iy, ix) = ndimage.distance_transform_edt(~valid, return_indices=True)
483
+ tex = tex[iy, ix]
484
+
485
+ base = os.path.splitext(dst)[0]
486
+ name = os.path.basename(base)
487
+ os.makedirs(os.path.dirname(os.path.abspath(dst)), exist_ok=True)
488
+ o3d.io.write_image(base + ".png", o3d.geometry.Image(np.ascontiguousarray(tex))) # row 0 = v 1, as OBJ expects
489
+ with open(base + ".mtl", "w") as m:
490
+ m.write(f"newmtl material0\nKd 1 1 1\nmap_Kd {name}.png\n")
491
+ with open(dst, "w", buffering=1 << 20) as fh:
492
+ fh.write(f"# textured TSDF mesh by mast3r_mesh.py\nmtllib {name}.mtl\n")
493
+ write_rows(fh, V[vmap], "v %.7g %.7g %.7g")
494
+ write_rows(fh, N[vmap], "vn %.6g %.6g %.6g")
495
+ write_rows(fh, uv, "vt %.6g %.6g")
496
+ fh.write("usemtl material0\n")
497
+ # v, vt and vn share one index (xatlas splits vertices), so each corner is i/i/i
498
+ write_rows(fh, np.repeat(idx + 1, 3, axis=1), "f %d/%d/%d %d/%d/%d %d/%d/%d")
499
+ log(f"done: {dst}, {base}.png ({size}x{size}), {len(vmap):,} verts, {len(idx):,} tris")
500
+
501
+
502
+ def main():
503
+ here = os.path.dirname(os.path.abspath(__file__))
504
+ ap = argparse.ArgumentParser(description="Textured TSDF mesh from a MASt3R-SLAM run")
505
+ ap.add_argument("run_dir", nargs="?", default=here, help="folder with scan.ply, scan.txt, keyframes/ (default: script folder)")
506
+ ap.add_argument("-o", "--output", help="default: <run_dir>/scan_tsdf.obj")
507
+ ap.add_argument("--video", help="source video of the run: texture from its full-res frames instead of 512 px keyframes")
508
+ ap.add_argument("--voxel", type=float, default=0, help="TSDF voxel size in scene units (default: 2x median pixel footprint)")
509
+ ap.add_argument("--trunc", type=float, default=0, help="TSDF truncation; offset layers closer than this merge (default 5x voxel)")
510
+ ap.add_argument("--min-weight", type=float, default=1.5, help="keep surface seen in at least this many keyframes (default 1.5, i.e. 2)")
511
+ ap.add_argument("--reproj", type=float, default=8.0, help="drop points that reproject worse than this many px (default 8)")
512
+ ap.add_argument("--no-refine", action="store_true", help="skip ICP + pose-graph refinement of keyframe poses")
513
+ ap.add_argument("--icp-dist", type=float, default=0, help="refine: max ICP correspondence distance (default 10x voxel)")
514
+ ap.add_argument("--edge", type=float, default=0.05, help="drop depth px differing from a neighbour by > this fraction (default 0.05)")
515
+ ap.add_argument("--min-cluster", type=float, default=0.002, help="remove mesh pieces smaller than this fraction of all tris (default 0.002)")
516
+ ap.add_argument("--tris", type=int, default=300000, help="max triangles after decimation (default 300000)")
517
+ ap.add_argument("--tex-size", type=int, default=4096, help="texture size in pixels (default 4096)")
518
+ ap.add_argument("--blend", type=float, default=4.0, help="view blending sharpness; higher = closer to best-view-only (default 4)")
519
+ ap.add_argument("--video-max-err", type=float, default=6.0, help="max mean abs error (0-255) for a video frame to count as a keyframe's source")
520
+ a = ap.parse_args()
521
+ out = a.output or os.path.join(a.run_dir, "scan_tsdf.obj")
522
+
523
+ P, rgb, traj, imgs = load_run(a.run_dir)
524
+ pix, kf = assign_pixels(rgb, imgs)
525
+ cams = build_cameras(P, traj, imgs, pix, kf, a.reproj, a.edge)
526
+ del P, rgb, pix, kf
527
+
528
+ zs = np.concatenate([c["depth"][c["depth"] > 0] / c["K"][0, 0] for c in cams if c["K"] is not None])
529
+ voxel = a.voxel or 2 * float(np.median(zs))
530
+ trunc = a.trunc or 5 * voxel
531
+ if not a.no_refine:
532
+ refine_poses(cams, 2 * voxel, a.icp_dist or 10 * voxel, 0.3)
533
+ mesh = fuse(cams, voxel, trunc, a.min_weight)
534
+ mesh = clean_mesh(mesh, a.min_cluster, a.tris)
535
+ if a.video:
536
+ attach_video(cams, a.video, a.video_max_err)
537
+ write_textured(mesh, cams, out, a.tex_size, voxel, a.blend)
538
+
539
+
540
+ if __name__ == "__main__":
541
+ main()