LLFF / rewrite.py
SlekLi's picture
Upload rewrite.py
018cc0b verified
Raw
History Blame Contribute Delete
7.88 kB
"""
Rewrite generated children from infer_upsample.py debug_npz with a fixed opacity.
This is a controlled diagnostic: positions, scales, rotations, DC, and SH stay
identical; only opacity changes.
Example:
python rewrite_generated_opacity.py --debug_npz debug_sample.npz \
--codebook_dir codebooks --alpha 0.2 --save_path same_points_alpha02.ply
python rewrite_generated_opacity.py --debug_npz debug_sample.npz \
--codebook_dir codebooks --alpha 0.2 --force_rgb 1 1 1 \
--save_path same_points_alpha02_white.ply
"""
import argparse
import os
from typing import Optional
import numpy as np
from plyfile import PlyData, PlyElement
SH_C0 = 0.28209479177387814
def alpha_to_logit(alpha: float) -> float:
alpha = float(np.clip(alpha, 1e-6, 1.0 - 1e-6))
return float(np.log(alpha / (1.0 - alpha)))
def normalize_quaternions(rotations: np.ndarray) -> np.ndarray:
rotations = rotations.astype(np.float32, copy=True)
norms = np.linalg.norm(rotations, axis=1, keepdims=True)
valid = np.isfinite(norms) & (norms > 1e-8)
rotations = np.where(valid, rotations / np.maximum(norms, 1e-8), rotations)
bad = ~valid.squeeze(1)
if bad.any():
rotations[bad] = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
return rotations
def load_codebook(codebook_dir: str, name: str) -> np.ndarray:
path = os.path.join(codebook_dir, f"{name}_codebook.npz")
if not os.path.exists(path):
raise FileNotFoundError(path)
return np.load(path)["codebook"].astype(np.float32)
def print_percentiles(name: str, values: np.ndarray) -> None:
pct = np.percentile(values, [0, 1, 50, 90, 95, 99, 99.9, 100], axis=0)
print(f"\n[{name}]")
for p, row in zip([0, 1, 50, 90, 95, 99, 99.9, 100], pct):
row = np.ravel(row)
print(f" p{p:>5}: " + " ".join(f"{float(x):.6g}" for x in row))
def write_ply(debug_npz: str,
codebook_dir: str,
save_path: str,
alpha: Optional[float],
opacity_logit: Optional[float],
force_rgb: Optional[list],
scale_offset: float) -> None:
data = np.load(debug_npz)
keys = set(data.files)
positions = data["positions"].astype(np.float32)
# 支持两种 npz:
# 1) infer_upsample.py --debug_npz 生成的 generated debug:
# scale_idx, rot_idx, dc_idx, sh_idx
# 2) quantize.py 生成的 quantized npz:
# scale_indices, rotation_indices, dc_indices, sh_indices
if {"scale_idx", "rot_idx", "dc_idx", "sh_idx"}.issubset(keys):
scale_idx = data["scale_idx"].astype(np.int64)
rot_idx = data["rot_idx"].astype(np.int64)
dc_idx = data["dc_idx"].astype(np.int64)
sh_idx = data["sh_idx"].astype(np.int64)
source_kind = "generated-debug"
elif {"scale_indices", "rotation_indices", "dc_indices", "sh_indices"}.issubset(keys):
scale_idx = data["scale_indices"].astype(np.int64)
rot_idx = data["rotation_indices"].astype(np.int64)
dc_idx = data["dc_indices"].astype(np.int64)
sh_idx = data["sh_indices"].astype(np.int64)
source_kind = "quantized"
else:
raise KeyError(
"Unsupported npz format. Expected either generated debug keys "
"(scale_idx/rot_idx/dc_idx/sh_idx) or quantized keys "
"(scale_indices/rotation_indices/dc_indices/sh_indices). "
f"Found keys: {sorted(keys)}"
)
if alpha is not None:
raw_opacity = np.full(positions.shape[0], alpha_to_logit(alpha), dtype=np.float32)
elif opacity_logit is not None:
raw_opacity = np.full(positions.shape[0], float(opacity_logit), dtype=np.float32)
elif "opacities" in keys:
raw_opacity = data["opacities"].astype(np.float32)
if raw_opacity.ndim > 1:
raw_opacity = raw_opacity.reshape(-1)
else:
raise KeyError("No opacity source found. Pass --alpha or --opacity_logit.")
cb_scale = load_codebook(codebook_dir, "scale")
cb_rot = normalize_quaternions(load_codebook(codebook_dir, "rotation"))
cb_dc = load_codebook(codebook_dir, "dc")
cb_sh = load_codebook(codebook_dir, "sh")
scales = cb_scale[scale_idx].copy()
if scale_offset != 0.0:
scales = scales + float(scale_offset)
rotations = cb_rot[rot_idx]
dc = cb_dc[dc_idx]
sh = cb_sh[sh_idx]
if force_rgb is not None:
rgb = np.asarray(force_rgb, dtype=np.float32)
if rgb.shape != (3,):
raise ValueError("--force_rgb expects exactly three values: R G B")
rgb = np.clip(rgb, 0.0, 1.0)
dc_value = (rgb - 0.5) / SH_C0
dc = np.broadcast_to(dc_value.reshape(1, 3), dc.shape).astype(np.float32)
sh = np.zeros_like(sh, dtype=np.float32)
fields = (
[("x", "f4"), ("y", "f4"), ("z", "f4"),
("opacity", "f4"),
("scale_0", "f4"), ("scale_1", "f4"), ("scale_2", "f4"),
("rot_0", "f4"), ("rot_1", "f4"), ("rot_2", "f4"), ("rot_3", "f4"),
("f_dc_0", "f4"), ("f_dc_1", "f4"), ("f_dc_2", "f4"),
("filter_3D", "f4")]
+ [(f"f_rest_{i}", "f4") for i in range(sh.shape[1])]
)
vd = np.zeros(positions.shape[0], dtype=np.dtype(fields))
vd["x"] = positions[:, 0]
vd["y"] = positions[:, 1]
vd["z"] = positions[:, 2]
vd["opacity"] = raw_opacity
vd["scale_0"] = scales[:, 0]
vd["scale_1"] = scales[:, 1]
vd["scale_2"] = scales[:, 2]
vd["rot_0"] = rotations[:, 0]
vd["rot_1"] = rotations[:, 1]
vd["rot_2"] = rotations[:, 2]
vd["rot_3"] = rotations[:, 3]
vd["f_dc_0"] = dc[:, 0]
vd["f_dc_1"] = dc[:, 1]
vd["f_dc_2"] = dc[:, 2]
vd["filter_3D"] = 0.0
for i in range(sh.shape[1]):
vd[f"f_rest_{i}"] = sh[:, i]
os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
PlyData([PlyElement.describe(vd, "vertex")]).write(save_path)
alpha_values = 1.0 / (1.0 + np.exp(-np.clip(raw_opacity, -80.0, 80.0)))
volumes = np.exp(np.clip(scales.sum(axis=1), -80.0, 80.0))
print(f"[write] source={source_kind}")
print(f"[write] {positions.shape[0]:,} gaussians -> {save_path}")
print_percentiles("written raw opacity", raw_opacity)
print_percentiles("written alpha", alpha_values)
print_percentiles("written f_dc", dc)
approx_rgb = np.clip(dc * SH_C0 + 0.5, 0.0, 1.0)
print_percentiles("approx RGB from DC only", approx_rgb)
print_percentiles("written raw scale", scales)
print_percentiles("exp(written scale)", np.exp(np.clip(scales, -80.0, 80.0)))
print_percentiles("decoded physical volume", volumes)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Rewrite generated debug_npz as PLY with fixed opacity.")
parser.add_argument("--debug_npz", required=True)
parser.add_argument("--codebook_dir", required=True)
parser.add_argument("--save_path", required=True)
group = parser.add_mutually_exclusive_group()
group.add_argument("--alpha", type=float, help="Fixed alpha value to write, converted to raw logit.")
group.add_argument("--opacity_logit", type=float, help="Fixed raw opacity logit to write.")
parser.add_argument("--force_rgb", nargs=3, type=float,
help="Force DC color to this RGB in [0,1] and zero SH rest.")
parser.add_argument("--scale_offset", type=float, default=0.0,
help="Add this value to all raw log-scales. 0.693 roughly doubles physical scale.")
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
write_ply(
debug_npz=args.debug_npz,
codebook_dir=args.codebook_dir,
save_path=args.save_path,
alpha=args.alpha,
opacity_logit=args.opacity_logit,
force_rgb=args.force_rgb,
scale_offset=args.scale_offset,
)