Datasets:
Tasks:
Image-to-3D
Modalities:
Tabular
Formats:
parquet
Languages:
English
Size:
10K - 100K
License:
File size: 5,161 Bytes
150d753 | 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 | """LayeredDepth preprocessing (aligned with SeeGroup ``LayeredDepthSyn``).
This module is self-contained for Hugging Face dataset users. It mirrors the
logic in ``dataset/layereddepth_syn.py`` and ``dataset/hf_utils.py``.
"""
from __future__ import annotations
import io
import os
from typing import Iterable, Sequence
import numpy as np
DEFAULT_LAYER_IDS: tuple[int, ...] = (1, 3, 5, 7)
def decode_image(value) -> np.ndarray:
if isinstance(value, np.ndarray):
return value
try:
from PIL.Image import Image as PILImage
except ImportError:
PILImage = ()
if isinstance(value, PILImage):
return np.asarray(value.copy())
if isinstance(value, dict):
if value.get("bytes") is not None:
from PIL import Image
with Image.open(io.BytesIO(value["bytes"])) as image:
return np.asarray(image.copy())
if value.get("path") is not None:
value = value["path"]
if isinstance(value, (str, os.PathLike)):
from PIL import Image
with Image.open(value) as image:
return np.asarray(image.copy())
if hasattr(value, "__array__"):
return np.asarray(value)
raise TypeError(f"Unsupported image value type: {type(value)!r}")
def image_to_float_rgb(value) -> np.ndarray:
image = decode_image(value)
if image.ndim == 2:
image = np.repeat(image[..., None], 3, axis=2)
if image.ndim != 3 or image.shape[2] not in (3, 4):
raise ValueError(f"Expected RGB image, got shape {image.shape}")
if image.shape[2] == 4:
image = image[..., :3]
image = image.astype(np.float32, copy=False)
if image.max(initial=0) > 1.0:
scale = 65535.0 if image.max(initial=0) > 255.0 else 255.0
image = image / scale
return image
def depth_png_to_meters(value) -> np.ndarray:
depth = decode_image(value)
if depth.ndim == 3:
depth = depth[..., 0]
depth = depth.astype(np.float32, copy=False) / 1000.0
depth[~np.isfinite(depth)] = 0
depth[depth > 80] = 0
depth[depth <= 0] = 0
return depth
def get_row_value(row, names: Sequence[str]):
for name in names:
if name in row:
return row[name]
raise KeyError(f"None of the expected fields are present: {list(names)}")
def postprocess_layered_depth(depth_layers: Iterable[np.ndarray]) -> np.ndarray:
"""Collapse invalid target pixels into deeper valid layers (LayeredDepth convention)."""
layers = [layer.copy() for layer in depth_layers]
for current_layer in range(1, len(layers)):
for target_layer in range(current_layer):
valid_current = layers[current_layer] != 0
valid_target = layers[target_layer] != 0
collapse_region = valid_current & (~valid_target)
layers[target_layer][collapse_region] = layers[current_layer][collapse_region]
layers[current_layer][collapse_region] = 0
return np.stack(layers, axis=-1)
def load_depth_layers_from_row(row, layer_ids: Sequence[int] = DEFAULT_LAYER_IDS) -> np.ndarray:
layers = []
for layer_id in layer_ids:
layers.append(
depth_png_to_meters(get_row_value(row, [f"depth_{layer_id}.png", f"depth{layer_id}.png"]))
)
return postprocess_layered_depth(layers)
def preprocess_sample(
row,
*,
layer_ids: Sequence[int] = DEFAULT_LAYER_IDS,
selected_layer_ids: Sequence[int] | None = None,
) -> dict:
"""Return a training-ready dict from a ``princeton-vl/LayeredDepth-Syn`` row."""
image = image_to_float_rgb(get_row_value(row, ["image.png", "image", "rgb"]))
depth = load_depth_layers_from_row(row, layer_ids=layer_ids)
valid_mask = (depth > 0).astype(np.float32)
sample = {
"image": image,
"depth": depth,
"valid_mask": valid_mask,
"sample_key": str(row.get("__key__", row.get("id", ""))),
}
if selected_layer_ids is not None:
indices = [layer_ids.index(layer_id) for layer_id in selected_layer_ids]
sample["depth_selected"] = depth[..., indices]
sample["valid_mask_selected"] = valid_mask[..., indices]
return sample
def sort_depth_with_mask(depth: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
valid_mask = depth > 0
sort_key = np.where(valid_mask, depth, np.inf)
order = np.argsort(sort_key, axis=-1)
sorted_depth = np.take_along_axis(depth, order, axis=-1)
sorted_mask = np.take_along_axis(valid_mask, order, axis=-1)
return sorted_depth, sorted_mask
def compressed_layer_count_per_pixel(
sorted_depth: np.ndarray,
sorted_mask: np.ndarray,
*,
abs_gap_threshold: float = 1e-4,
rel_gap_threshold: float = 0.0,
) -> np.ndarray:
raw_count = sorted_mask.sum(axis=-1)
raw_gap = sorted_depth[..., 1:] - sorted_depth[..., :-1]
adjacent_valid = sorted_mask[..., 1:] & sorted_mask[..., :-1]
threshold = np.maximum(abs_gap_threshold, rel_gap_threshold * np.abs(sorted_depth[..., :-1]))
event_gap = adjacent_valid & (raw_gap > threshold)
return (raw_count > 0).astype(np.int16) + event_gap.sum(axis=-1).astype(np.int16)
|