dmytromishkin commited on
Commit
1eac99d
·
1 Parent(s): ac88814

updated for 2026

Browse files
README.md CHANGED
@@ -23,7 +23,12 @@ cd tools2025
23
  pip install -e .
24
  ```
25
 
26
- ### Usage example
 
 
 
 
 
27
 
28
  ```python
29
  from datasets import load_dataset
@@ -41,7 +46,7 @@ def read_colmap_rec(colmap_data):
41
  rec = pycolmap.Reconstruction(tmpdir)
42
  return rec
43
 
44
- ds = load_dataset("usm3d/hoho25k", streaming=True, trust_remote_code=True)
45
  for a in ds['train']:
46
  break
47
 
@@ -50,7 +55,7 @@ fig, ax = plot_all_modalities(a)
50
  ## Now 3d
51
 
52
  fig3d = init_figure()
53
- plot_reconstruction(fig3d, read_colmap_rec(a['colmap_binary']))
54
  plot_wireframe(fig3d, a['wf_vertices'], a['wf_edges'], a['wf_classifications'])
55
  plot_bpo_cameras_from_entry(fig3d, a)
56
  fig3d
@@ -65,7 +70,7 @@ from hoho2025.example_solutions import predict_wireframe
65
  pred_vertices, pred_connections = predict_wireframe(a)
66
 
67
  fig3d = init_figure()
68
- plot_reconstruction(fig3d, read_colmap_rec(a['colmap_binary']))
69
  plot_wireframe(fig3d, pred_vertices, pred_connections, color='rgb(0, 0, 255)')
70
  fig3d
71
  ```
@@ -78,4 +83,10 @@ from hoho2025.metric_helper import hss
78
 
79
  score = hss(pred_vertices, pred_connections, a['wf_vertices'], a['wf_edges'], vert_thresh=0.5, edge_thresh=0.5)
80
  print (score)
81
- ```
 
 
 
 
 
 
 
23
  pip install -e .
24
  ```
25
 
26
+
27
+
28
+ ### Usage example 2026
29
+
30
+
31
+ See in [notebook](notebooks/example_2026.ipynb)
32
 
33
  ```python
34
  from datasets import load_dataset
 
46
  rec = pycolmap.Reconstruction(tmpdir)
47
  return rec
48
 
49
+ ds = load_dataset("usm3d/hoho22k_2026_trainval", streaming=True, trust_remote_code=True)
50
  for a in ds['train']:
51
  break
52
 
 
55
  ## Now 3d
56
 
57
  fig3d = init_figure()
58
+ plot_reconstruction(fig3d, read_colmap_rec(a['colmap']))
59
  plot_wireframe(fig3d, a['wf_vertices'], a['wf_edges'], a['wf_classifications'])
60
  plot_bpo_cameras_from_entry(fig3d, a)
61
  fig3d
 
70
  pred_vertices, pred_connections = predict_wireframe(a)
71
 
72
  fig3d = init_figure()
73
+ plot_reconstruction(fig3d, read_colmap_rec(a['colmap']))
74
  plot_wireframe(fig3d, pred_vertices, pred_connections, color='rgb(0, 0, 255)')
75
  fig3d
76
  ```
 
83
 
84
  score = hss(pred_vertices, pred_connections, a['wf_vertices'], a['wf_edges'], vert_thresh=0.5, edge_thresh=0.5)
85
  print (score)
86
+ ```
87
+
88
+
89
+
90
+ ### Usage example 2025
91
+
92
+ See in [notebooks](notebooks/example_2025.ipynb)
hoho2025/example_solutions.py CHANGED
@@ -26,10 +26,39 @@ def read_colmap_rec(colmap_data):
26
  rec = pycolmap.Reconstruction(tmpdir)
27
  return rec
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def convert_entry_to_human_readable(entry):
30
  out = {}
31
  for k, v in entry.items():
32
- if 'colmap' in k:
33
  out[k] = read_colmap_rec(v)
34
  elif k in ['wf_vertices', 'wf_edges', 'K', 'R', 't', 'depth']:
35
  out[k] = np.array(v)
@@ -272,7 +301,9 @@ def get_uv_depth(vertices: List[dict],
272
 
273
 
274
 
275
- def project_vertices_to_3d(uv: np.ndarray, depth_vert: np.ndarray, col_img: pycolmap.Image) -> np.ndarray:
 
 
276
  """
277
  Projects 2D vertex coordinates with associated depths to 3D world coordinates.
278
 
@@ -283,25 +314,40 @@ def project_vertices_to_3d(uv: np.ndarray, depth_vert: np.ndarray, col_img: pyco
283
  depth_vert : np.ndarray
284
  (N,) array of depth values for each vertex.
285
  col_img : pycolmap.Image
 
 
 
286
 
287
  Returns
288
  -------
289
  vertices_3d : np.ndarray
290
  (N, 3) array of vertex coordinates in 3D world space.
291
  """
 
 
 
 
 
 
 
 
 
 
 
 
292
  # Backproject to 3D local camera coordinates
293
  xy_local = np.ones((len(uv), 3))
294
- K = col_img.camera.calibration_matrix()
295
  xy_local[:, 0] = (uv[:, 0] - K[0, 2]) / K[0, 0]
296
  xy_local[:, 1] = (uv[:, 1] - K[1, 2]) / K[1, 1]
297
- # Get the 3D vertices
298
- vertices_3d_local = xy_local * depth_vert[...,None]
299
-
300
- # Create camera-to-world transformation matrix
301
  world_to_cam = np.eye(4)
302
- world_to_cam[:3] = col_img.cam_from_world.matrix()
 
303
  cam_to_world = np.linalg.inv(world_to_cam)
304
-
305
  # Transform local 3D points to world coordinates
306
  vertices_3d_homogeneous = cv2.convertPointsToHomogeneous(vertices_3d_local)
307
  vertices_3d = cv2.transform(vertices_3d_homogeneous, cam_to_world)
@@ -354,7 +400,7 @@ def create_3d_wireframe_single_image(vertices: List[dict],
354
  uv, depth_vert = get_uv_depth(vertices, depth_fitted, depth_sparse, 10)
355
 
356
  # Backproject to 3D
357
- vertices_3d = project_vertices_to_3d(uv, depth_vert, col_img)
358
 
359
  return vertices_3d
360
 
@@ -536,24 +582,19 @@ def get_sparse_depth(colmap_rec, img_id_substring, depth):
536
 
537
  points_xyz = np.array(points_xyz) # (N, 3)
538
 
539
- # 3) For each point, project via col_img.project_point()
 
540
  uv = []
541
  z_vals = []
542
  for xyz in points_xyz:
543
- proj = found_img.project_point(xyz) # returns (u, v) in image coords or None
544
- if proj is not None:
545
- u_i, v_i = proj
546
- u_i = int(round(u_i))
547
- v_i = int(round(v_i))
548
- # Check in-bounds
549
- if 0 <= u_i < W and 0 <= v_i < H:
550
- uv.append((u_i, v_i))
551
- # We'll compute depth as Z in camera coords
552
- # from the world->cam transform col_img holds
553
- mat4x4 = np.eye(4)
554
- mat4x4[:3, :4] = found_img.cam_from_world.matrix()
555
- p_cam = mat4x4@ np.array([xyz[0], xyz[1], xyz[2], 1.0])
556
- z_vals.append(p_cam[2] / p_cam[3])
557
 
558
  uv = np.array(uv, dtype=int) # shape (M,2)
559
  z_vals = np.array(z_vals) # shape (M,)
@@ -664,7 +705,10 @@ def predict_wireframe(entry) -> Tuple[np.ndarray, List[int]]:
664
  good_entry['image_ids'],
665
  good_entry['ade'] # Added ade20k segmentation
666
  )):
667
- colmap_rec = good_entry['colmap_binary']
 
 
 
668
  K = np.array(K)
669
  R = np.array(R)
670
  t = np.array(t)
 
26
  rec = pycolmap.Reconstruction(tmpdir)
27
  return rec
28
 
29
+
30
+ def _cam_matrix_from_image(img):
31
+ """Return (R 3×3, t 3) from a pycolmap.Image, compatible with all pycolmap versions."""
32
+ cfW = img.cam_from_world
33
+ try:
34
+ R = cfW.rotation.matrix()
35
+ t = cfW.translation
36
+ except AttributeError:
37
+ # Older API: matrix() returns 3×4 [R | t]
38
+ M = np.array(cfW.matrix())
39
+ R, t = M[:, :3], M[:, 3]
40
+ return np.array(R, dtype=np.float64), np.array(t, dtype=np.float64)
41
+
42
+
43
+ def _colmap_project_point(img, cam, xyz):
44
+ """Project a 3-D world point into image pixel coordinates.
45
+
46
+ Returns ``((u, v), depth_z)`` or ``None`` if the point is behind the camera.
47
+ Works with any pycolmap version (replaces the removed ``Image.project_point``).
48
+ """
49
+ R, t = _cam_matrix_from_image(img)
50
+ p_cam = R @ np.asarray(xyz, dtype=np.float64) + t
51
+ if p_cam[2] <= 0:
52
+ return None
53
+ K = cam.calibration_matrix()
54
+ u = p_cam[0] / p_cam[2] * K[0, 0] + K[0, 2]
55
+ v = p_cam[1] / p_cam[2] * K[1, 1] + K[1, 2]
56
+ return (u, v), p_cam[2]
57
+
58
  def convert_entry_to_human_readable(entry):
59
  out = {}
60
  for k, v in entry.items():
61
+ if 'colmap' in k and k!= 'pose_only_in_colmap':
62
  out[k] = read_colmap_rec(v)
63
  elif k in ['wf_vertices', 'wf_edges', 'K', 'R', 't', 'depth']:
64
  out[k] = np.array(v)
 
301
 
302
 
303
 
304
+ def project_vertices_to_3d(uv: np.ndarray, depth_vert: np.ndarray,
305
+ col_img: pycolmap.Image,
306
+ colmap_rec: pycolmap.Reconstruction = None) -> np.ndarray:
307
  """
308
  Projects 2D vertex coordinates with associated depths to 3D world coordinates.
309
 
 
314
  depth_vert : np.ndarray
315
  (N,) array of depth values for each vertex.
316
  col_img : pycolmap.Image
317
+ colmap_rec : pycolmap.Reconstruction, optional
318
+ Required for newer pycolmap versions where ``Image.camera`` no longer
319
+ exists. Ignored if the old ``col_img.camera`` shortcut is available.
320
 
321
  Returns
322
  -------
323
  vertices_3d : np.ndarray
324
  (N, 3) array of vertex coordinates in 3D world space.
325
  """
326
+ # Obtain camera intrinsics — try the old shortcut first, then fall back to
327
+ # looking up the camera through the reconstruction.
328
+ try:
329
+ K = col_img.camera.calibration_matrix()
330
+ except AttributeError:
331
+ if colmap_rec is None:
332
+ raise AttributeError(
333
+ "col_img.camera is not available in this pycolmap version. "
334
+ "Pass colmap_rec to project_vertices_to_3d()."
335
+ )
336
+ K = colmap_rec.cameras[col_img.camera_id].calibration_matrix()
337
+
338
  # Backproject to 3D local camera coordinates
339
  xy_local = np.ones((len(uv), 3))
 
340
  xy_local[:, 0] = (uv[:, 0] - K[0, 2]) / K[0, 0]
341
  xy_local[:, 1] = (uv[:, 1] - K[1, 2]) / K[1, 1]
342
+ vertices_3d_local = xy_local * depth_vert[..., None]
343
+
344
+ # Build 4×4 world-to-cam matrix using the version-agnostic helper.
345
+ R, t = _cam_matrix_from_image(col_img)
346
  world_to_cam = np.eye(4)
347
+ world_to_cam[:3, :3] = R
348
+ world_to_cam[:3, 3] = t
349
  cam_to_world = np.linalg.inv(world_to_cam)
350
+
351
  # Transform local 3D points to world coordinates
352
  vertices_3d_homogeneous = cv2.convertPointsToHomogeneous(vertices_3d_local)
353
  vertices_3d = cv2.transform(vertices_3d_homogeneous, cam_to_world)
 
400
  uv, depth_vert = get_uv_depth(vertices, depth_fitted, depth_sparse, 10)
401
 
402
  # Backproject to 3D
403
+ vertices_3d = project_vertices_to_3d(uv, depth_vert, col_img, colmap_rec=colmap_rec)
404
 
405
  return vertices_3d
406
 
 
582
 
583
  points_xyz = np.array(points_xyz) # (N, 3)
584
 
585
+ # 3) Project each 3D point into the image using the version-agnostic helper.
586
+ cam = colmap_rec.cameras[found_img.camera_id]
587
  uv = []
588
  z_vals = []
589
  for xyz in points_xyz:
590
+ result = _colmap_project_point(found_img, cam, xyz)
591
+ if result is None:
592
+ continue
593
+ (u_f, v_f), depth_z = result
594
+ u_i, v_i = int(round(u_f)), int(round(v_f))
595
+ if 0 <= u_i < W and 0 <= v_i < H:
596
+ uv.append((u_i, v_i))
597
+ z_vals.append(depth_z)
 
 
 
 
 
 
598
 
599
  uv = np.array(uv, dtype=int) # shape (M,2)
600
  z_vals = np.array(z_vals) # shape (M,)
 
705
  good_entry['image_ids'],
706
  good_entry['ade'] # Added ade20k segmentation
707
  )):
708
+ if 'colmap' in good_entry:
709
+ colmap_rec = good_entry['colmap']
710
+ else:
711
+ colmap_rec = good_entry['colmap_binary']
712
  K = np.array(K)
713
  R = np.array(R)
714
  t = np.array(t)
hoho2025/viz3d.py CHANGED
@@ -34,8 +34,17 @@ def to_homogeneous(points):
34
 
35
  ### Plotting functions
36
 
37
- def init_figure(height: int = 800) -> go.Figure:
38
- """Initialize a 3D figure."""
 
 
 
 
 
 
 
 
 
39
  fig = go.FigureWidget()
40
  axes = dict(
41
  visible=False,
@@ -45,13 +54,22 @@ def init_figure(height: int = 800) -> go.Figure:
45
  showticklabels=True,
46
  autorange=True,
47
  )
 
 
 
 
 
 
 
 
 
 
 
 
48
  fig.update_layout(
49
  template="plotly_dark",
50
  height=height,
51
- scene_camera=dict(
52
- eye=dict(x=0., y=-.1, z=-2),
53
- up=dict(x=0, y=-1., z=0),
54
- projection=dict(type="orthographic")),
55
  scene=dict(
56
  xaxis=axes,
57
  yaxis=axes,
@@ -214,7 +232,6 @@ def plot_reconstruction(
214
  rgbs = []
215
  # Iterate over rec.points3D
216
  for k, p3D in rec.points3D.items():
217
- #print (p3D)
218
  xyzs.append(p3D.xyz)
219
  rgbs.append(p3D.color)
220
 
@@ -246,7 +263,7 @@ def plot_wireframe(
246
  color: str = 'rgb(0, 0, 255)',
247
  name: Optional[str] = None,
248
  **kwargs):
249
- """Plot a camera as a cone with camera frustum."""
250
  gt_vertices = np.array(vertices)
251
  gt_connections = np.array(edges)
252
  if gt_vertices is not None:
@@ -267,21 +284,381 @@ def plot_wireframe(
267
  plot_lines_3d(fig, np.array(gt_lines), color, ps=4)
268
 
269
 
270
- def plot_bpo_cameras_from_entry(fig: go.Figure, entry: dict, idx = None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  def cam2world_to_world2cam(R, t):
272
- rt = np.eye(4)
273
- rt[:3,:3] = R
274
- rt[:3,3] = t.reshape(-1)
275
- rt = np.linalg.inv(rt)
276
- return rt[:3,:3], rt[:3,3]
277
-
 
278
  for i in range(len(entry['R'])):
279
  if idx is not None and i != idx:
280
  continue
 
 
 
281
  K = np.array(entry['K'][i])
 
 
 
282
  R = np.array(entry['R'][i])
283
  t = np.array(entry['t'][i])
284
- R, t = cam2world_to_world2cam(R, t)
285
- plot_camera(fig, R, t, K)
286
-
287
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  ### Plotting functions
36
 
37
+ def init_figure(height: int = 800, reverse_gravity: bool = False) -> go.Figure:
38
+ """Initialize a 3D figure.
39
+
40
+ Args:
41
+ height: Figure height in pixels.
42
+ reverse_gravity: Set to ``True`` for the **2025** dataset, whose
43
+ coordinate frame has Y pointing *down* (the original SketchUp /
44
+ COLMAP convention before the 2026 re-orientation). When ``False``
45
+ (default, for the **2026** dataset) the viewer is set up for a
46
+ standard Y-up world so that the roof wireframe appears right-side up.
47
+ """
48
  fig = go.FigureWidget()
49
  axes = dict(
50
  visible=False,
 
54
  showticklabels=True,
55
  autorange=True,
56
  )
57
+ if reverse_gravity:
58
+ # 2025 data: Y points down — look from below with Y-down up-vector.
59
+ scene_camera = dict(
60
+ eye=dict(x=0., y=-.1, z=-2.),
61
+ up=dict(x=0, y=-1., z=0),
62
+ projection=dict(type="orthographic"))
63
+ else:
64
+ # 2026 data: Y points up — standard bird's-eye view.
65
+ scene_camera = dict(
66
+ eye=dict(x=0., y=1.5, z=-3.),
67
+ up=dict(x=0, y=1., z=0),
68
+ projection=dict(type="orthographic"))
69
  fig.update_layout(
70
  template="plotly_dark",
71
  height=height,
72
+ scene_camera=scene_camera,
 
 
 
73
  scene=dict(
74
  xaxis=axes,
75
  yaxis=axes,
 
232
  rgbs = []
233
  # Iterate over rec.points3D
234
  for k, p3D in rec.points3D.items():
 
235
  xyzs.append(p3D.xyz)
236
  rgbs.append(p3D.color)
237
 
 
263
  color: str = 'rgb(0, 0, 255)',
264
  name: Optional[str] = None,
265
  **kwargs):
266
+ """Plot a wireframe with per-edge semantic colors."""
267
  gt_vertices = np.array(vertices)
268
  gt_connections = np.array(edges)
269
  if gt_vertices is not None:
 
284
  plot_lines_3d(fig, np.array(gt_lines), color, ps=4)
285
 
286
 
287
+ def plot_bpo_cameras_from_entry(
288
+ fig: go.Figure,
289
+ entry: dict,
290
+ idx: Optional[int] = None,
291
+ color: str = 'rgb(255, 128, 0)',
292
+ size: float = 1.0):
293
+ """Plot BPO (DAE) camera frustums for a dataset entry.
294
+
295
+ Cameras flagged as ``pose_only_in_colmap=True`` are skipped because their
296
+ K / R / t are all zeros and would cause a singular-matrix error.
297
+
298
+ Supports both the 2025 format (``colmap_binary``) and the 2026 format
299
+ (``colmap``, ``pose_only_in_colmap`` per-camera flag).
300
+ """
301
+ pose_only_flags = entry.get('pose_only_in_colmap', [])
302
+
303
  def cam2world_to_world2cam(R, t):
304
+ # Rᵀ(p_cam − t) → R_w2c = Rᵀ, t_w2c = −Rᵀ t
305
+ R = np.array(R, dtype=np.float64)
306
+ t = np.array(t, dtype=np.float64).reshape(3)
307
+ R_w2c = R.T
308
+ t_w2c = -R_w2c @ t
309
+ return R_w2c, t_w2c
310
+
311
  for i in range(len(entry['R'])):
312
  if idx is not None and i != idx:
313
  continue
314
+ # Skip cameras that exist only in COLMAP (zero K/R/t).
315
+ if i < len(pose_only_flags) and pose_only_flags[i]:
316
+ continue
317
  K = np.array(entry['K'][i])
318
+ # Guard against all-zero K from old loaders that may not set pose_only flags.
319
+ if np.allclose(K, 0.0):
320
+ continue
321
  R = np.array(entry['R'][i])
322
  t = np.array(entry['t'][i])
323
+ R_w2c, t_w2c = cam2world_to_world2cam(R, t)
324
+ plot_camera(fig, R_w2c, t_w2c, K, color=color, size=size)
325
+
326
+
327
+ # ---------------------------------------------------------------------------
328
+ # Depth + segmentation unprojection helpers
329
+ # ---------------------------------------------------------------------------
330
+
331
+ def _open_image_field(img_field):
332
+ """Convert an HF Image() field value (PIL Image, bytes-dict, or raw bytes) to PIL Image."""
333
+ import io as _io
334
+ from PIL import Image as PILImage
335
+ if img_field is None:
336
+ return None
337
+ if isinstance(img_field, PILImage.Image):
338
+ return img_field
339
+ raw = None
340
+ if isinstance(img_field, dict) and "bytes" in img_field:
341
+ raw = img_field["bytes"]
342
+ elif isinstance(img_field, (bytes, bytearray)):
343
+ raw = img_field
344
+ if raw is None:
345
+ return None
346
+ try:
347
+ return PILImage.open(_io.BytesIO(raw))
348
+ except Exception:
349
+ return None
350
+
351
+
352
+ def _resolve_skip_colors(skip_classes):
353
+ """
354
+ Return a uint8 array of shape (K, 3) with the ADE20k RGB colours for
355
+ *skip_classes*, or None if no classes could be resolved.
356
+
357
+ Matching rules (case-insensitive):
358
+ 1. Exact key match – 'sky' → 'sky'
359
+ 2. Semicolon-part match – 'window' → 'windowpane;window'
360
+ Unknown names are silently ignored.
361
+ """
362
+ from hoho2025.color_mappings import ade20k_color_mapping
363
+ colors = []
364
+ for cls in skip_classes:
365
+ cls_lower = cls.lower()
366
+ if cls_lower in ade20k_color_mapping:
367
+ colors.append(ade20k_color_mapping[cls_lower])
368
+ else:
369
+ for key, rgb in ade20k_color_mapping.items():
370
+ if cls_lower in [p.strip() for p in key.split(';')]:
371
+ colors.append(rgb)
372
+ break
373
+ return np.array(colors, dtype=np.uint8) if colors else None # (K, 3) or None
374
+
375
+
376
+ def _unproject_depth(depth_pil, ade_rgb, K_np, R_np, t_np,
377
+ target_size, depth_scale, max_depth, skip_colors_arr):
378
+ """
379
+ Shared unprojection core. Returns (pts_world, r_ch, g_ch, b_ch) or None.
380
+
381
+ K_np — 3×3 intrinsics (modified in-place to match target_size).
382
+ R_np — 3×3 cam_from_world rotation.
383
+ t_np — (3,) cam_from_world translation.
384
+ """
385
+ from PIL import Image as PILImage
386
+
387
+ W_t, H_t = target_size
388
+ W_d, H_d = depth_pil.size # PIL (width, height)
389
+
390
+ # Rescale K from its native resolution (inferred from cx) to depth image size,
391
+ # then again to target_size.
392
+ w_K = K_np[0, 2] * 2.0
393
+ h_K = K_np[1, 2] * 2.0
394
+ if w_K > 0 and h_K > 0:
395
+ K_np[0, 0] *= W_d / w_K; K_np[1, 1] *= H_d / h_K
396
+ K_np[0, 2] *= W_d / w_K; K_np[1, 2] *= H_d / h_K
397
+ K_np[0, 0] *= W_t / W_d; K_np[1, 1] *= H_t / H_d
398
+ K_np[0, 2] *= W_t / W_d; K_np[1, 2] *= H_t / H_d
399
+
400
+ depth_arr = np.array(depth_pil, dtype=np.float32)
401
+ if depth_arr.ndim == 3:
402
+ depth_arr = depth_arr[:, :, 0]
403
+ depth_np = np.array(
404
+ PILImage.fromarray(depth_arr, mode='F').resize((W_t, H_t), PILImage.NEAREST),
405
+ dtype=np.float32) * depth_scale
406
+
407
+ if ade_rgb is not None:
408
+ ade_s = np.array(
409
+ PILImage.fromarray(ade_rgb).resize((W_t, H_t), PILImage.NEAREST),
410
+ dtype=np.uint8)
411
+ else:
412
+ ade_s = np.full((H_t, W_t, 3), 180, dtype=np.uint8)
413
+
414
+ valid = (depth_np > 0) & (depth_np < max_depth)
415
+ if skip_colors_arr is not None:
416
+ class_mask = np.any(
417
+ np.all(ade_s[:, :, None, :] == skip_colors_arr[None, None, :, :], axis=-1),
418
+ axis=-1)
419
+ valid = valid & ~class_mask
420
+ if not valid.any():
421
+ return None
422
+
423
+ u_grid, v_grid = np.meshgrid(np.arange(W_t, dtype=np.float64),
424
+ np.arange(H_t, dtype=np.float64))
425
+ pix_h = np.stack([u_grid[valid], v_grid[valid], np.ones(valid.sum())], axis=1)
426
+ pts_cam = (pix_h @ np.linalg.inv(K_np).T) * depth_np[valid, None].astype(np.float64)
427
+ pts_world = (pts_cam - t_np.reshape(3)) @ R_np # Rᵀ(p_cam − t)
428
+
429
+ return pts_world, ade_s[:, :, 0][valid], ade_s[:, :, 1][valid], ade_s[:, :, 2][valid]
430
+
431
+
432
+ def _load_colmap_from_entry(entry):
433
+ """
434
+ Unzip and parse the COLMAP reconstruction stored in entry['colmap'] or
435
+ entry['colmap_binary'] (old 2025 key name).
436
+
437
+ Returns a pycolmap.Reconstruction, or None if the field is absent/invalid.
438
+ """
439
+ import io as _io
440
+ import zipfile
441
+ import tempfile
442
+
443
+ colmap_data = entry.get("colmap") or entry.get("colmap_binary")
444
+ if colmap_data is None:
445
+ return None
446
+ if isinstance(colmap_data, list):
447
+ colmap_data = bytes(colmap_data)
448
+ if not isinstance(colmap_data, (bytes, bytearray)) or len(colmap_data) == 0:
449
+ return None
450
+ try:
451
+ with tempfile.TemporaryDirectory() as tmpdir:
452
+ with zipfile.ZipFile(_io.BytesIO(colmap_data), "r") as zf:
453
+ zf.extractall(tmpdir)
454
+ rec = pycolmap.Reconstruction(tmpdir)
455
+ return rec
456
+ except Exception as e:
457
+ print(f"Warning: could not load colmap from entry: {e}")
458
+ return None
459
+
460
+
461
+ def plot_depth_and_segmentation_in_3d(
462
+ fig: go.Figure,
463
+ entry: dict,
464
+ idx: Optional[int] = None,
465
+ target_size: tuple = (128, 96),
466
+ depth_scale: float = 0.001,
467
+ max_depth: float = 64.0,
468
+ skip_classes: Optional[list] = None,
469
+ point_size: int = 2):
470
+ """Unproject depth maps coloured with ADE20k segmentation into a 3D scatter.
471
+
472
+ Uses the BPO camera parameters (entry['K'], entry['R'], entry['t']).
473
+ Cameras flagged as ``pose_only_in_colmap`` are skipped automatically.
474
+
475
+ In the 2026 format, depth/ade lists may be shorter than the full camera list
476
+ because pose-only cameras have no depth/image files. This function correctly
477
+ matches each depth entry to its corresponding camera by building a positional
478
+ mapping over non-pose-only cameras.
479
+
480
+ Args:
481
+ fig: Plotly figure created by init_figure().
482
+ entry: Dataset entry dict (2025 or 2026 format).
483
+ idx: If set, only process the depth image at this position in the
484
+ depth list (i.e. among non-pose-only cameras).
485
+ target_size: (width, height) to downscale before unprojection.
486
+ depth_scale: Multiply raw pixel values by this to get metres.
487
+ max_depth: Discard pixels deeper than this (metres).
488
+ skip_classes: ADE20k class names to exclude (e.g. ['sky', 'tree']).
489
+ point_size: Plotly marker size.
490
+ """
491
+ skip_colors_arr = _resolve_skip_colors(skip_classes) if skip_classes else None
492
+
493
+ depths = entry.get("depth", []) or []
494
+ aes = entry.get("ade", []) or []
495
+ Ks = entry.get("K", [])
496
+ Rs = entry.get("R", [])
497
+ ts = entry.get("t", [])
498
+ pose_only = entry.get("pose_only_in_colmap", [])
499
+ image_ids = entry.get("image_ids", [])
500
+
501
+ # Build the list of camera indices (into K/R/t) that actually have depth/ade.
502
+ # In 2026 format, pose-only cameras are interspersed in K/R/t but absent from
503
+ # depth/ade lists, so we cannot use a shared positional counter.
504
+ non_po_cam_indices = [
505
+ i for i in range(len(Ks))
506
+ if not (i < len(pose_only) and pose_only[i]) and not np.allclose(Ks[i], 0.0)
507
+ ]
508
+
509
+ for depth_pos, cam_idx in enumerate(non_po_cam_indices):
510
+ if idx is not None and depth_pos != idx:
511
+ continue
512
+ if depth_pos >= len(depths):
513
+ break
514
+
515
+ depth_field = depths[depth_pos]
516
+ ade_field = aes[depth_pos] if depth_pos < len(aes) else None
517
+
518
+ depth_pil = _open_image_field(depth_field)
519
+ ade_pil = _open_image_field(ade_field)
520
+ if depth_pil is None:
521
+ continue
522
+
523
+ K_np = np.array(Ks[cam_idx], dtype=np.float64).copy()
524
+ R_np = np.array(Rs[cam_idx], dtype=np.float64)
525
+ t_np = np.array(ts[cam_idx], dtype=np.float64).reshape(3)
526
+
527
+ ade_rgb = (np.array(ade_pil.convert("RGB"), dtype=np.uint8)
528
+ if ade_pil is not None else None)
529
+
530
+ result = _unproject_depth(
531
+ depth_pil, ade_rgb,
532
+ K_np=K_np, R_np=R_np, t_np=t_np,
533
+ target_size=target_size,
534
+ depth_scale=depth_scale,
535
+ max_depth=max_depth,
536
+ skip_colors_arr=skip_colors_arr,
537
+ )
538
+ if result is None:
539
+ continue
540
+ pts_world, r_ch, g_ch, b_ch = result
541
+
542
+ colors = [f"rgb({r},{g},{b})" for r, g, b in zip(r_ch, g_ch, b_ch)]
543
+ label = image_ids[cam_idx] if cam_idx < len(image_ids) else str(cam_idx)
544
+ fig.add_trace(go.Scatter3d(
545
+ x=pts_world[:, 0],
546
+ y=pts_world[:, 1],
547
+ z=pts_world[:, 2],
548
+ mode="markers",
549
+ marker=dict(size=point_size, color=colors, line_width=0),
550
+ name=f"depth_{label}",
551
+ showlegend=False,
552
+ ))
553
+
554
+
555
+ def plot_depth_and_segmentation_in_3d_colmap(
556
+ fig: go.Figure,
557
+ entry: dict,
558
+ idx: Optional[int] = None,
559
+ target_size: tuple = (128, 96),
560
+ depth_scale: float = 0.001,
561
+ max_depth: float = 64.0,
562
+ skip_classes: Optional[list] = None,
563
+ point_size: int = 2):
564
+ """Unproject depth maps into 3D using camera poses from the stored COLMAP
565
+ reconstruction (entry['colmap'] or entry['colmap_binary']).
566
+
567
+ Unlike :func:`plot_depth_and_segmentation_in_3d`, this variant reads camera
568
+ parameters directly from the COLMAP reconstruction. This means all cameras
569
+ registered in COLMAP are available, including those flagged as
570
+ ``pose_only_in_colmap``.
571
+
572
+ Depth images are matched to COLMAP cameras by ``image_id`` (the same
573
+ lexicographic order used by ds_loader_2026.py for non-pose-only cameras).
574
+
575
+ Args:
576
+ fig: Plotly figure created by :func:`init_figure`.
577
+ entry: Dataset entry with keys ``colmap``/``colmap_binary``, ``depth``,
578
+ ``ade``, ``image_ids``, ``pose_only_in_colmap``.
579
+ idx: If set, only process the depth image at this position in the
580
+ depth list (i.e. among non-pose-only cameras).
581
+ target_size: ``(width, height)`` for downscaling before unprojection.
582
+ depth_scale: Scale factor to convert raw pixel values to metres.
583
+ max_depth: Discard pixels whose depth exceeds this value.
584
+ skip_classes: ADE20k class names to exclude (e.g. ``['sky', 'tree']``).
585
+ point_size: Plotly marker size.
586
+ """
587
+ from PIL import Image as PILImage
588
+
589
+ skip_colors_arr = _resolve_skip_colors(skip_classes) if skip_classes else None
590
+
591
+ rec = _load_colmap_from_entry(entry)
592
+ if rec is None:
593
+ print("plot_depth_and_segmentation_in_3d_colmap: no colmap in entry")
594
+ return
595
+
596
+ depths = entry.get("depth", []) or []
597
+ aes = entry.get("ade", []) or []
598
+ image_ids = entry.get("image_ids", [])
599
+ pose_only = entry.get("pose_only_in_colmap", [])
600
+
601
+ # Build img_id → (K, R, t) from the COLMAP reconstruction.
602
+ # Image names may be raw ("image_{img_id}_order_{order_id}.jpg") or
603
+ # anonymised hashes ("{img_id}.jpg") depending on the dataset version.
604
+ colmap_cam_map = {}
605
+ for _, img in rec.images.items():
606
+ parts = img.name.split('_')
607
+ img_id = parts[1] if len(parts) >= 2 else img.name.split('.')[0]
608
+ cam = rec.cameras[img.camera_id]
609
+ K_c = cam.calibration_matrix()
610
+ R_c = img.cam_from_world.rotation.matrix()
611
+ t_c = img.cam_from_world.translation
612
+ colmap_cam_map[img_id] = (K_c, R_c, t_c)
613
+
614
+ # Non-pose-only image IDs in sorted order — these have depth/ade entries.
615
+ non_po_ids = [
616
+ image_ids[i] for i in range(len(image_ids))
617
+ if not (i < len(pose_only) and pose_only[i])
618
+ ]
619
+
620
+ for depth_pos, img_id in enumerate(non_po_ids):
621
+ if idx is not None and depth_pos != idx:
622
+ continue
623
+ if depth_pos >= len(depths):
624
+ break
625
+
626
+ depth_field = depths[depth_pos]
627
+ ade_field = aes[depth_pos] if depth_pos < len(aes) else None
628
+
629
+ depth_pil = _open_image_field(depth_field)
630
+ ade_pil = _open_image_field(ade_field)
631
+ if depth_pil is None:
632
+ continue
633
+
634
+ if img_id not in colmap_cam_map:
635
+ continue
636
+ K_c, R_c, t_c = colmap_cam_map[img_id]
637
+
638
+ ade_rgb = (np.array(ade_pil.convert("RGB"), dtype=np.uint8)
639
+ if ade_pil is not None else None)
640
+
641
+ result = _unproject_depth(
642
+ depth_pil, ade_rgb,
643
+ K_np=K_c.astype(np.float64).copy(),
644
+ R_np=R_c.astype(np.float64),
645
+ t_np=t_c.astype(np.float64),
646
+ target_size=target_size,
647
+ depth_scale=depth_scale,
648
+ max_depth=max_depth,
649
+ skip_colors_arr=skip_colors_arr,
650
+ )
651
+ if result is None:
652
+ continue
653
+ pts_world, r_ch, g_ch, b_ch = result
654
+
655
+ colors = [f"rgb({r},{g},{b})" for r, g, b in zip(r_ch, g_ch, b_ch)]
656
+ fig.add_trace(go.Scatter3d(
657
+ x=pts_world[:, 0],
658
+ y=pts_world[:, 1],
659
+ z=pts_world[:, 2],
660
+ mode="markers",
661
+ marker=dict(size=point_size, color=colors, line_width=0),
662
+ name=f"colmap_depth_{img_id}",
663
+ showlegend=False,
664
+ ))
notebooks/{example.ipynb → example_2025.ipynb} RENAMED
The diff for this file is too large to render. See raw diff
 
notebooks/example_2026.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt CHANGED
@@ -1,3 +1,4 @@
 
1
  datasets
2
  huggingface-hub
3
  ipywidgets
@@ -6,9 +7,9 @@ numpy
6
  opencv-python
7
  Pillow
8
  plotly
9
- pycolmap
10
  scipy
11
  torch
12
  trimesh
13
  webdataset
14
- manifold3d # for metric computation
 
1
+ # Python >= 3.10 required (see setup.py)
2
  datasets
3
  huggingface-hub
4
  ipywidgets
 
7
  opencv-python
8
  Pillow
9
  plotly
10
+ pycolmap>=0.6
11
  scipy
12
  torch
13
  trimesh
14
  webdataset
15
+ manifold3d # for metric computation