shuinb's picture
Upload STB code utilities
b004d6f verified
Raw
History Blame Contribute Delete
24.4 kB
import json
import os
from typing import Sequence, Tuple
# import h5py
import numpy as np
import scipy
import torch
import torch.nn.functional as F
from tqdm import tqdm
from .utils import Rays
C = 299792458.0
def _normalize_index(idx: torch.Tensor, size: int) -> torch.Tensor:
if size <= 1:
return torch.zeros_like(idx)
return 2.0 * idx / float(size - 1) - 1.0
def _load_numpy_coo_npz(npz_path: str) -> np.ndarray:
pack = np.load(npz_path, allow_pickle=False)
try:
if "format" not in pack:
raise ValueError("missing 'format' key in npz")
fmt = str(np.asarray(pack["format"]).item())
if fmt != "coo_numpy":
raise ValueError(f"unsupported npz format tag: {fmt}")
shape = tuple(np.asarray(pack["shape"], dtype=np.int64).tolist())
row = np.asarray(pack["row"], dtype=np.int64)
col = np.asarray(pack["col"], dtype=np.int64)
data = np.asarray(pack["data"])
dense = np.zeros(shape, dtype=data.dtype)
np.add.at(dense, (row, col), data)
return dense
finally:
pack.close()
def _load_histogram_2d(path: str, dtype=np.float32) -> np.ndarray:
ext = os.path.splitext(path)[1].lower()
if ext == ".txt":
arr = np.loadtxt(path, dtype=dtype)
elif ext == ".npz":
try:
from scipy import sparse # type: ignore
arr = sparse.load_npz(path).toarray()
except Exception:
arr = _load_numpy_coo_npz(path)
if dtype is not None:
arr = np.asarray(arr, dtype=dtype)
else:
raise ValueError(f"unsupported histogram extension for 2D loader: {ext}")
arr = np.asarray(arr, dtype=dtype)
if arr.ndim == 1:
arr = arr.reshape(1, -1)
return arr
def _reshape_histogram_to_hwt(arr: np.ndarray, hw: Tuple[int, int]) -> torch.Tensor:
h, w = int(hw[0]), int(hw[1])
if arr.ndim == 3:
if arr.shape[0] == h and arr.shape[1] == w:
out = arr
elif arr.shape[0] == w and arr.shape[1] == h:
out = arr.transpose(1, 0, 2)
else:
raise ValueError(f"3D histogram shape {arr.shape} incompatible with target ({h}, {w}, T)")
return torch.from_numpy(np.asarray(out, dtype=np.float32))
if arr.ndim != 2:
raise ValueError(f"expected 2D/3D histogram array, got shape={arr.shape}")
if arr.shape[0] == h * w:
out = arr.reshape(h, w, arr.shape[1])
elif arr.shape[1] == h * w:
out = arr.T.reshape(h, w, arr.shape[0])
else:
raise ValueError(
f"2D histogram shape {arr.shape} does not match H*W={h*w}; "
"expected [H*W, bins] or [bins, H*W]."
)
return torch.from_numpy(np.asarray(out, dtype=np.float32))
def _load_valid_mask_from_offset(
offset_path: str,
source_hw: Tuple[int, int],
target_hw: Tuple[int, int],
invalid_gt: float = 10.0,
) -> torch.Tensor:
ext = os.path.splitext(offset_path)[1].lower()
if ext == ".npy":
arr = np.load(offset_path).astype(np.float32)
else:
arr = np.loadtxt(offset_path, dtype=np.float32)
arr = np.asarray(arr, dtype=np.float32).squeeze()
src_h, src_w = int(source_hw[0]), int(source_hw[1])
if arr.ndim == 1:
if arr.size != src_h * src_w:
raise ValueError(
f"offset map length {arr.size} does not match source H*W={src_h*src_w}"
)
arr = arr.reshape(src_h, src_w)
elif arr.ndim == 2:
if arr.shape == (src_h, src_w):
pass
elif arr.shape == (src_w, src_h):
arr = arr.T
elif arr.size == src_h * src_w:
arr = arr.reshape(src_h, src_w)
else:
raise ValueError(
f"offset map shape {arr.shape} incompatible with source shape ({src_h}, {src_w})"
)
else:
raise ValueError(f"offset map must be 1D/2D, got shape={arr.shape}")
valid = (arr <= float(invalid_gt)).astype(np.float32)
valid_t = torch.from_numpy(valid)[None, None, ...]
dst_h, dst_w = int(target_hw[0]), int(target_hw[1])
if (src_h, src_w) != (dst_h, dst_w):
valid_t = F.interpolate(
valid_t,
size=(dst_h, dst_w),
mode="nearest",
)
return valid_t.squeeze(0).squeeze(0) > 0.5
def _load_measurement_histogram(path: str, hw: Tuple[int, int]) -> torch.Tensor:
ext = os.path.splitext(path)[1].lower()
if ext in (".txt", ".npz"):
arr = _load_histogram_2d(path, dtype=np.float32)
hist = _reshape_histogram_to_hwt(arr, hw)
elif ext == ".pt":
raw = torch.load(path, map_location="cpu")
if not isinstance(raw, torch.Tensor):
raise ValueError(f".pt file must contain a tensor: {path}")
hist = raw.to_dense() if raw.is_sparse else raw
hist = hist.to(torch.float32).cpu()
if hist.ndim == 2:
hist = _reshape_histogram_to_hwt(hist.numpy(), hw)
elif hist.ndim == 3:
pass
else:
raise ValueError(f"unsupported tensor shape in {path}: {tuple(hist.shape)}")
# elif ext in (".h5", ".hdf5"):
# with h5py.File(path, "r") as f:
# if "data" not in f:
# raise ValueError(f"h5 file missing key 'data': {path}")
# arr = np.asarray(f["data"])
# hist = _reshape_histogram_to_hwt(arr, hw)
else:
raise ValueError(f"unsupported measurement extension: {ext}")
if hist.ndim == 4 and hist.shape[-1] == 1:
hist = hist[..., 0]
if hist.ndim == 4 and hist.shape[-1] == 3:
hist = hist[..., 0]
if hist.ndim != 3:
raise ValueError(f"expected histogram shape [H,W,T], got {tuple(hist.shape)} from {path}")
return hist
def _parse_shift_for_grid(shift, hw: Tuple[int, int]):
h, w = int(hw[0]), int(hw[1])
arr = np.asarray(shift, dtype=np.float32)
if arr.ndim == 0:
return float(arr.item()), None
arr = arr.squeeze()
if arr.ndim == 0 or arr.size == 1:
return float(arr.reshape(-1)[0]), None
if arr.ndim == 1 and arr.size == h * w:
return 0.0, torch.from_numpy(arr.reshape(h, w))
if arr.ndim == 2:
shift_map = torch.from_numpy(arr.astype(np.float32))
if tuple(shift_map.shape) != (h, w):
shift_map = F.interpolate(
shift_map[None, None, ...],
size=(h, w),
mode="bilinear",
align_corners=True,
).squeeze(0).squeeze(0)
return 0.0, shift_map
return float(arr.reshape(-1)[0]), None
def _build_shift_grid(
hw: Tuple[int, int],
n_bins: int,
shift,
bin_width_s: float,
device: str = "cpu",
) -> torch.Tensor:
h, w = int(hw[0]), int(hw[1])
exposure_time = C * float(bin_width_s)
shift_scalar, shift_map = _parse_shift_for_grid(shift, hw)
z = torch.arange(n_bins, device=device, dtype=torch.float32)[:, None, None]
z = z * exposure_time / 2.0
if shift_map is not None:
z = z - shift_map.to(device)[None, ...]
else:
z = z - float(shift_scalar)
z = z * 2.0 / exposure_time
z = _normalize_index(z, n_bins)
x = _normalize_index(torch.arange(w, device=device, dtype=torch.float32), w)
y = _normalize_index(torch.arange(h, device=device, dtype=torch.float32), h)
x = x[None, None, :].expand(n_bins, h, w)
y = y[None, :, None].expand(n_bins, h, w)
z = z.expand(n_bins, h, w)
# grid_sample 5D grid order is (x, y, z) for input shaped [N,C,D,H,W].
grid = torch.stack((x, y, z), dim=-1)[None, ...]
return grid
def _apply_shift(hist: torch.Tensor, shift, bin_width_s: float) -> torch.Tensor:
h, w, t = hist.shape
grid = _build_shift_grid((h, w), t, shift, bin_width_s, device=hist.device)
# [H, W, T] -> [N=1, C=1, D=T, H, W]
hist_dhw = hist.permute(2, 0, 1)[None, None, ...]
shifted = F.grid_sample(hist_dhw, grid, align_corners=True)
# back to [H, W, T]
return shifted.squeeze(0).squeeze(0).permute(1, 2, 0)
def _resize_hist_spatial(hist: torch.Tensor, target_hw: Tuple[int, int]) -> torch.Tensor:
target_h, target_w = int(target_hw[0]), int(target_hw[1])
h, w, _ = hist.shape
if (h, w) == (target_h, target_w):
return hist
# [H,W,T] -> [1,T,H,W] for spatial resize only.
hist_chw = hist.permute(2, 0, 1)[None, ...]
resized = F.interpolate(hist_chw, size=(target_h, target_w), mode="area")
return resized.squeeze(0).permute(1, 2, 0)
def _resolve_measurement_path(
data_dir: str,
split: str,
frame_file_path: str,
measurement_root: str = None,
data_exts: Sequence[str] = (".npz", ".txt", ".pt", ".h5", ".hdf5"),
) -> str:
raw = str(frame_file_path)
if os.path.isabs(raw) and os.path.isfile(raw):
return raw
rel = raw.replace("\\", "/").lstrip("./")
base = os.path.basename(rel)
stem, ext = os.path.splitext(base)
rel_stem = os.path.splitext(rel)[0]
roots = []
if measurement_root:
roots.extend([measurement_root, os.path.join(measurement_root, split)])
roots.extend([data_dir, os.path.join(data_dir, split)])
seen_roots = set()
unique_roots = []
for r in roots:
rr = os.path.normpath(r)
if rr not in seen_roots:
unique_roots.append(rr)
seen_roots.add(rr)
# Prefer exact path if extension already exists.
if ext:
for root in unique_roots:
for rel_name in (rel, base):
cand = os.path.normpath(os.path.join(root, rel_name))
if os.path.isfile(cand):
return cand
# Then resolve by stem and supported extensions.
for root in unique_roots:
for data_ext in data_exts:
for rel_name in (rel_stem + data_ext, stem + data_ext):
cand = os.path.normpath(os.path.join(root, rel_name))
if os.path.isfile(cand):
return cand
raise FileNotFoundError(
f"Cannot resolve measurement file for frame '{frame_file_path}'. "
f"Searched roots={unique_roots}, exts={tuple(data_exts)}."
)
def _load_renderings_transient_real_ours(
root_fp: str,
split: str,
have_images=True,
img_shape=(256, 256),
source_img_shape=None,
n_bins=4096,
shift=0,
bin_width_s=4e-12,
measurement_root=None,
data_exts=(".npz", ".txt", ".pt", ".h5", ".hdf5"),
):
data_dir = root_fp
with open(os.path.join(data_dir, f"transforms_{split}.json"), "r", encoding="utf-8") as fp:
meta = json.load(fp)
images = []
camtoworlds = []
if have_images:
tqdm.write("Loading data")
reshape_hw = tuple(source_img_shape) if source_img_shape is not None else tuple(img_shape)
for i in tqdm(range(len(meta["frames"]))):
frame = meta["frames"][i]
file_key = frame.get("file_path", frame.get("filepath"))
if file_key is None:
raise KeyError("Each frame in transforms json must contain 'file_path' or 'filepath'.")
measurement_path = _resolve_measurement_path(
data_dir=data_dir,
split=split,
frame_file_path=file_key,
measurement_root=measurement_root,
data_exts=data_exts,
)
hist = _load_measurement_histogram(measurement_path, reshape_hw).to(torch.float32).cpu()
hist = torch.clip(hist, min=0.0)
hist = _apply_shift(hist, shift=shift, bin_width_s=bin_width_s)
if hist.shape[-1] != int(n_bins):
raise ValueError(
f"Histogram bin count mismatch for '{measurement_path}': "
f"loaded {hist.shape[-1]} vs config n_bins={n_bins}. "
"This pipeline does not truncate or adjacent-bin average."
)
hist = _resize_hist_spatial(hist, img_shape)
hist_rgb = hist[..., None].repeat(1, 1, 1, 3)
camtoworlds.append(frame["transform_matrix"])
images.append(hist_rgb)
images = torch.stack(images, axis=0)
max_value = torch.max(images).clamp_min(1e-8)
images = images / max_value
camtoworlds = np.stack(camtoworlds, axis=0)
else:
for frame in meta["frames"]:
camtoworlds.append(frame["transform_matrix"])
camtoworlds = np.stack(camtoworlds, axis=0)
max_value = torch.tensor(1.0)
return images, camtoworlds, max_value
class SubjectLoaderTransientRealOurs(torch.utils.data.Dataset):
"""Captured-data loader for custom txt/npz/pt histograms without bin truncation/averaging."""
SPLITS = ["train", "val", "trainval", "test"]
NEAR, FAR = 0, 6
OPENGL_CAMERA = True
def __init__(
self,
subject_id: str,
root_fp: str,
split: str,
color_bkgd_aug: str = "black",
num_rays: int = None,
near: float = None,
far: float = None,
batch_over_images: bool = True,
have_images=True,
img_shape=(256, 256),
source_img_shape=None,
n_bins=10000,
rfilter_sigma=0.15,
sample_as_per_distribution=True,
shift=0.0,
testing=False,
bin_width_s=4e-12,
measurement_root=None,
data_exts=(".npz", ".txt", ".pt", ".h5", ".hdf5"),
invalid_mask_path=None,
invalid_mask_invalid_gt=10.0,
):
super().__init__()
assert color_bkgd_aug in ["white", "black", "random"]
self.sample_as_per_distribution = sample_as_per_distribution
self.rfilter_sigma = rfilter_sigma
self.HEIGHT, self.WIDTH = int(img_shape[0]), int(img_shape[1])
self.split = split
self.testing = testing
self.num_rays = num_rays
self.near = self.NEAR if near is None else near
self.far = self.FAR if far is None else far
self.training = (num_rays is not None) and (split in ["train", "trainval"])
self.shift = shift
self.rep = 1
self.color_bkgd_aug = color_bkgd_aug
self.batch_over_images = batch_over_images
self.have_images = have_images
self.n_bins = int(n_bins)
self.bin_width_s = float(bin_width_s)
self.measurement_root = measurement_root
self.data_exts = tuple(data_exts)
self.source_img_shape = tuple(source_img_shape) if source_img_shape is not None else None
self.invalid_mask_path = invalid_mask_path
self.invalid_mask_invalid_gt = float(invalid_mask_invalid_gt)
if have_images:
self.images, self.camtoworlds, self.max = _load_renderings_transient_real_ours(
root_fp=root_fp,
split=split,
n_bins=self.n_bins,
shift=shift,
img_shape=(self.HEIGHT, self.WIDTH),
source_img_shape=self.source_img_shape,
bin_width_s=self.bin_width_s,
measurement_root=self.measurement_root,
data_exts=self.data_exts,
)
self.images = self.images.to(torch.float32)
assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH)
else:
raise ValueError("have_images=False is not supported in SubjectLoaderTransientRealOurs.")
self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32)
if self.invalid_mask_path:
source_hw = (
tuple(self.source_img_shape)
if self.source_img_shape is not None
else (self.HEIGHT, self.WIDTH)
)
self.valid_mask = _load_valid_mask_from_offset(
self.invalid_mask_path,
source_hw=source_hw,
target_hw=(self.HEIGHT, self.WIDTH),
invalid_gt=self.invalid_mask_invalid_gt,
).to(torch.bool)
else:
self.valid_mask = torch.ones((self.HEIGHT, self.WIDTH), dtype=torch.bool)
def __len__(self):
return len(self.camtoworlds)
def __getitem__(self, index):
data = self.fetch_data(index)
data = self.preprocess(data)
return data
def preprocess(self, data):
rgba, rays = data["rgba"], data["rays"]
if rgba is not None:
pixels = rgba.to(self.camtoworlds.device)
else:
pixels = rgba
if self.color_bkgd_aug == "random":
color_bkgd = torch.rand(3, device=self.camtoworlds.device)
elif self.color_bkgd_aug == "white":
color_bkgd = torch.ones(3, device=self.camtoworlds.device)
else:
color_bkgd = torch.zeros(3, device=self.camtoworlds.device)
return {
"pixels": pixels,
"rays": rays,
"color_bkgd": color_bkgd,
**{k: v for k, v in data.items() if k not in ["rgba", "rays"]},
}
def update_num_rays(self, num_rays):
self.num_rays = num_rays
def fetch_data(self, index, rep=None, num_rays=None):
if num_rays is None:
num_rays = self.num_rays
if rep is None:
rep = self.rep
if self.training:
if self.batch_over_images:
image_id = torch.randint(
0,
len(self.images),
size=(num_rays,),
device=self.images.device,
)
else:
image_id = [index]
x = torch.randint(0, self.WIDTH, size=(num_rays,), device="cpu")
y = torch.randint(0, self.HEIGHT, size=(num_rays,), device="cpu")
x = x.repeat(rep)
y = y.repeat(rep)
image_id = image_id.repeat(rep)
rgba = self.images[image_id, y, x]
elif self.testing:
image_id = [index]
x, y = torch.meshgrid(
torch.arange(self.WIDTH, device="cpu"),
torch.arange(self.HEIGHT, device="cpu"),
indexing="xy",
)
x = x.flatten().repeat(rep)
y = y.flatten().repeat(rep)
rgba = self.images[image_id, y, x] if self.have_images else None
else:
image_id = [index]
x, y = torch.meshgrid(
torch.arange(self.WIDTH, device=self.camtoworlds.device),
torch.arange(self.HEIGHT, device=self.camtoworlds.device),
indexing="xy",
)
x = x.flatten()
y = y.flatten()
rgba = self.images[image_id, y, x] if self.have_images else None
x_cpu_long = x.detach().cpu().long()
y_cpu_long = y.detach().cpu().long()
valid_mask = self.valid_mask[y_cpu_long, x_cpu_long]
c2w = self.camtoworlds[image_id]
scale = self.rfilter_sigma
if self.training or self.testing:
s_x, s_y, weights = spatial_filter(
x,
y,
sigma=scale,
rep=self.rep,
prob_dithering=self.sample_as_per_distribution,
)
s_x = torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH - 1).to(self.camtoworlds.device).to(torch.float32)
s_y = torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT - 1).to(self.camtoworlds.device).to(torch.float32)
weights = torch.tensor(weights, device=self.camtoworlds.device, dtype=torch.float32)
else:
s_x = x
s_y = y
weights = None
camera_dirs = self.K(s_x, s_y)
directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1)
origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape)
viewdirs = directions / torch.linalg.norm(directions, dim=-1, keepdims=True)
if self.training:
origins = torch.reshape(origins, (-1, 3))
viewdirs = torch.reshape(viewdirs, (-1, 3))
rgba = torch.reshape(rgba, (-1, self.n_bins * 3))
valid_mask = torch.reshape(valid_mask, (-1,))
elif self.testing:
origins = torch.reshape(origins, (-1, 3))
viewdirs = torch.reshape(viewdirs, (-1, 3))
if self.have_images:
rgba = torch.reshape(rgba, (-1, self.n_bins * 3))
valid_mask = torch.reshape(valid_mask, (-1,))
elif self.have_images:
origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, self.n_bins * 3))
valid_mask = torch.reshape(valid_mask, (self.HEIGHT, self.WIDTH))
else:
origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
rgba = None
valid_mask = torch.reshape(valid_mask, (self.HEIGHT, self.WIDTH))
rays = Rays(origins=origins, viewdirs=viewdirs)
if self.training or self.testing:
return {"rgba": rgba, "rays": rays, "weights": weights, "valid_mask": valid_mask}
return {"rgba": rgba, "rays": rays, "valid_mask": valid_mask}
class LearnRays(torch.nn.Module):
"""Interpolation-based ray lookup from per-pixel ray table (H,W,3)."""
def __init__(self, rays, device="cuda:0", img_shape=(256, 256)):
super().__init__()
self.device = device
self.img_shape = (int(img_shape[0]), int(img_shape[1]))
self.height = self.img_shape[0]
self.width = self.img_shape[1]
rays = np.asarray(rays, dtype=np.float32)
if rays.ndim != 3 or rays.shape[-1] != 3:
raise ValueError(f"rays must be [H,W,3], got shape={rays.shape}")
rays_t = torch.from_numpy(rays).to(self.device)
if tuple(rays_t.shape[:2]) != self.img_shape:
rays_t = F.interpolate(
rays_t.permute(2, 0, 1)[None, ...],
size=self.img_shape,
mode="bilinear",
align_corners=True,
).squeeze(0).permute(1, 2, 0)
rays_t = rays_t / torch.linalg.norm(rays_t, dim=-1, keepdims=True).clamp_min(1e-8)
self.rays = rays_t
def forward(self, x0, y0):
rays = self.rays
x0 = x0.to(rays.device).float()
y0 = y0.to(rays.device).float()
x1 = torch.floor(x0)
y1 = torch.floor(y0)
x2 = x1 + 1
y2 = y1 + 1
x1 = torch.clip(x1, 0, self.width - 1)
y1 = torch.clip(y1, 0, self.height - 1)
x2 = torch.clip(x2, 0, self.width - 1)
y2 = torch.clip(y2, 0, self.height - 1)
wx2 = ((x0 - x1) / (x2 - x1 + 1e-8))[:, None]
wx1 = 1.0 - wx2
wy2 = ((y0 - y1) / (y2 - y1 + 1e-8))[:, None]
wy1 = 1.0 - wy2
x1 = x1.long()
y1 = y1.long()
x2 = x2.long()
y2 = y2.long()
out = (
wx1 * wy1 * rays[y1, x1]
+ wx1 * wy2 * rays[y2, x1]
+ wx2 * wy1 * rays[y1, x2]
+ wx2 * wy2 * rays[y2, x2]
)
out = out / torch.linalg.norm(out, dim=-1, keepdims=True).clamp_min(1e-8)
return out.float()
def spatial_filter(x, y, sigma, rep, prob_dithering=True):
pdf_fn = lambda z: np.exp(-z / (2 * sigma**2)) - np.exp(-16)
if prob_dithering:
bounds_max = [4 * sigma] * x.shape[0]
loc = 0
s_x = scipy.stats.truncnorm.rvs(
(-np.array(bounds_max) - loc) / sigma,
(np.array(bounds_max) - loc) / sigma,
loc=loc,
scale=sigma,
)
s_y = scipy.stats.truncnorm.rvs(
(-np.array(bounds_max) - loc) / sigma,
(np.array(bounds_max) - loc) / sigma,
loc=loc,
scale=sigma,
)
weights = np.ones_like(s_x) * 1 / rep
else:
s_x = np.random.uniform(low=-4 * sigma, high=4 * sigma, size=(rep, x.shape[0] // rep))
s_y = np.random.uniform(low=-4 * sigma, high=4 * sigma, size=(rep, x.shape[0] // rep))
dists = s_x**2 + s_y**2
weights = pdf_fn(dists)
weights = weights / weights.sum(0)[None, :]
s_x = s_x.flatten()
s_y = s_y.flatten()
weights = weights.flatten()
return s_x, s_y, weights