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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Rewrite generated children from infer_upsample.py debug_npz with a fixed opacity.
|
| 3 |
+
|
| 4 |
+
This is a controlled diagnostic: positions, scales, rotations, DC, and SH stay
|
| 5 |
+
identical; only opacity changes.
|
| 6 |
+
|
| 7 |
+
Example:
|
| 8 |
+
python rewrite_generated_opacity.py --debug_npz debug_sample.npz \
|
| 9 |
+
--codebook_dir codebooks --alpha 0.2 --save_path same_points_alpha02.ply
|
| 10 |
+
|
| 11 |
+
python rewrite_generated_opacity.py --debug_npz debug_sample.npz \
|
| 12 |
+
--codebook_dir codebooks --alpha 0.2 --force_rgb 1 1 1 \
|
| 13 |
+
--save_path same_points_alpha02_white.ply
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import os
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from plyfile import PlyData, PlyElement
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
SH_C0 = 0.28209479177387814
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def alpha_to_logit(alpha: float) -> float:
|
| 28 |
+
alpha = float(np.clip(alpha, 1e-6, 1.0 - 1e-6))
|
| 29 |
+
return float(np.log(alpha / (1.0 - alpha)))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def normalize_quaternions(rotations: np.ndarray) -> np.ndarray:
|
| 33 |
+
rotations = rotations.astype(np.float32, copy=True)
|
| 34 |
+
norms = np.linalg.norm(rotations, axis=1, keepdims=True)
|
| 35 |
+
valid = np.isfinite(norms) & (norms > 1e-8)
|
| 36 |
+
rotations = np.where(valid, rotations / np.maximum(norms, 1e-8), rotations)
|
| 37 |
+
bad = ~valid.squeeze(1)
|
| 38 |
+
if bad.any():
|
| 39 |
+
rotations[bad] = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
|
| 40 |
+
return rotations
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_codebook(codebook_dir: str, name: str) -> np.ndarray:
|
| 44 |
+
path = os.path.join(codebook_dir, f"{name}_codebook.npz")
|
| 45 |
+
if not os.path.exists(path):
|
| 46 |
+
raise FileNotFoundError(path)
|
| 47 |
+
return np.load(path)["codebook"].astype(np.float32)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def print_percentiles(name: str, values: np.ndarray) -> None:
|
| 51 |
+
pct = np.percentile(values, [0, 1, 50, 90, 95, 99, 99.9, 100], axis=0)
|
| 52 |
+
print(f"\n[{name}]")
|
| 53 |
+
for p, row in zip([0, 1, 50, 90, 95, 99, 99.9, 100], pct):
|
| 54 |
+
row = np.ravel(row)
|
| 55 |
+
print(f" p{p:>5}: " + " ".join(f"{float(x):.6g}" for x in row))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def write_ply(debug_npz: str,
|
| 59 |
+
codebook_dir: str,
|
| 60 |
+
save_path: str,
|
| 61 |
+
alpha: Optional[float],
|
| 62 |
+
opacity_logit: Optional[float],
|
| 63 |
+
force_rgb: Optional[list],
|
| 64 |
+
scale_offset: float) -> None:
|
| 65 |
+
data = np.load(debug_npz)
|
| 66 |
+
keys = set(data.files)
|
| 67 |
+
positions = data["positions"].astype(np.float32)
|
| 68 |
+
|
| 69 |
+
# 支持两种 npz:
|
| 70 |
+
# 1) infer_upsample.py --debug_npz 生成的 generated debug:
|
| 71 |
+
# scale_idx, rot_idx, dc_idx, sh_idx
|
| 72 |
+
# 2) quantize.py 生成的 quantized npz:
|
| 73 |
+
# scale_indices, rotation_indices, dc_indices, sh_indices
|
| 74 |
+
if {"scale_idx", "rot_idx", "dc_idx", "sh_idx"}.issubset(keys):
|
| 75 |
+
scale_idx = data["scale_idx"].astype(np.int64)
|
| 76 |
+
rot_idx = data["rot_idx"].astype(np.int64)
|
| 77 |
+
dc_idx = data["dc_idx"].astype(np.int64)
|
| 78 |
+
sh_idx = data["sh_idx"].astype(np.int64)
|
| 79 |
+
source_kind = "generated-debug"
|
| 80 |
+
elif {"scale_indices", "rotation_indices", "dc_indices", "sh_indices"}.issubset(keys):
|
| 81 |
+
scale_idx = data["scale_indices"].astype(np.int64)
|
| 82 |
+
rot_idx = data["rotation_indices"].astype(np.int64)
|
| 83 |
+
dc_idx = data["dc_indices"].astype(np.int64)
|
| 84 |
+
sh_idx = data["sh_indices"].astype(np.int64)
|
| 85 |
+
source_kind = "quantized"
|
| 86 |
+
else:
|
| 87 |
+
raise KeyError(
|
| 88 |
+
"Unsupported npz format. Expected either generated debug keys "
|
| 89 |
+
"(scale_idx/rot_idx/dc_idx/sh_idx) or quantized keys "
|
| 90 |
+
"(scale_indices/rotation_indices/dc_indices/sh_indices). "
|
| 91 |
+
f"Found keys: {sorted(keys)}"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
if alpha is not None:
|
| 95 |
+
raw_opacity = np.full(positions.shape[0], alpha_to_logit(alpha), dtype=np.float32)
|
| 96 |
+
elif opacity_logit is not None:
|
| 97 |
+
raw_opacity = np.full(positions.shape[0], float(opacity_logit), dtype=np.float32)
|
| 98 |
+
elif "opacities" in keys:
|
| 99 |
+
raw_opacity = data["opacities"].astype(np.float32)
|
| 100 |
+
if raw_opacity.ndim > 1:
|
| 101 |
+
raw_opacity = raw_opacity.reshape(-1)
|
| 102 |
+
else:
|
| 103 |
+
raise KeyError("No opacity source found. Pass --alpha or --opacity_logit.")
|
| 104 |
+
|
| 105 |
+
cb_scale = load_codebook(codebook_dir, "scale")
|
| 106 |
+
cb_rot = normalize_quaternions(load_codebook(codebook_dir, "rotation"))
|
| 107 |
+
cb_dc = load_codebook(codebook_dir, "dc")
|
| 108 |
+
cb_sh = load_codebook(codebook_dir, "sh")
|
| 109 |
+
|
| 110 |
+
scales = cb_scale[scale_idx].copy()
|
| 111 |
+
if scale_offset != 0.0:
|
| 112 |
+
scales = scales + float(scale_offset)
|
| 113 |
+
rotations = cb_rot[rot_idx]
|
| 114 |
+
dc = cb_dc[dc_idx]
|
| 115 |
+
sh = cb_sh[sh_idx]
|
| 116 |
+
|
| 117 |
+
if force_rgb is not None:
|
| 118 |
+
rgb = np.asarray(force_rgb, dtype=np.float32)
|
| 119 |
+
if rgb.shape != (3,):
|
| 120 |
+
raise ValueError("--force_rgb expects exactly three values: R G B")
|
| 121 |
+
rgb = np.clip(rgb, 0.0, 1.0)
|
| 122 |
+
dc_value = (rgb - 0.5) / SH_C0
|
| 123 |
+
dc = np.broadcast_to(dc_value.reshape(1, 3), dc.shape).astype(np.float32)
|
| 124 |
+
sh = np.zeros_like(sh, dtype=np.float32)
|
| 125 |
+
|
| 126 |
+
fields = (
|
| 127 |
+
[("x", "f4"), ("y", "f4"), ("z", "f4"),
|
| 128 |
+
("opacity", "f4"),
|
| 129 |
+
("scale_0", "f4"), ("scale_1", "f4"), ("scale_2", "f4"),
|
| 130 |
+
("rot_0", "f4"), ("rot_1", "f4"), ("rot_2", "f4"), ("rot_3", "f4"),
|
| 131 |
+
("f_dc_0", "f4"), ("f_dc_1", "f4"), ("f_dc_2", "f4"),
|
| 132 |
+
("filter_3D", "f4")]
|
| 133 |
+
+ [(f"f_rest_{i}", "f4") for i in range(sh.shape[1])]
|
| 134 |
+
)
|
| 135 |
+
vd = np.zeros(positions.shape[0], dtype=np.dtype(fields))
|
| 136 |
+
vd["x"] = positions[:, 0]
|
| 137 |
+
vd["y"] = positions[:, 1]
|
| 138 |
+
vd["z"] = positions[:, 2]
|
| 139 |
+
vd["opacity"] = raw_opacity
|
| 140 |
+
vd["scale_0"] = scales[:, 0]
|
| 141 |
+
vd["scale_1"] = scales[:, 1]
|
| 142 |
+
vd["scale_2"] = scales[:, 2]
|
| 143 |
+
vd["rot_0"] = rotations[:, 0]
|
| 144 |
+
vd["rot_1"] = rotations[:, 1]
|
| 145 |
+
vd["rot_2"] = rotations[:, 2]
|
| 146 |
+
vd["rot_3"] = rotations[:, 3]
|
| 147 |
+
vd["f_dc_0"] = dc[:, 0]
|
| 148 |
+
vd["f_dc_1"] = dc[:, 1]
|
| 149 |
+
vd["f_dc_2"] = dc[:, 2]
|
| 150 |
+
vd["filter_3D"] = 0.0
|
| 151 |
+
for i in range(sh.shape[1]):
|
| 152 |
+
vd[f"f_rest_{i}"] = sh[:, i]
|
| 153 |
+
|
| 154 |
+
os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
|
| 155 |
+
PlyData([PlyElement.describe(vd, "vertex")]).write(save_path)
|
| 156 |
+
|
| 157 |
+
alpha_values = 1.0 / (1.0 + np.exp(-np.clip(raw_opacity, -80.0, 80.0)))
|
| 158 |
+
volumes = np.exp(np.clip(scales.sum(axis=1), -80.0, 80.0))
|
| 159 |
+
print(f"[write] source={source_kind}")
|
| 160 |
+
print(f"[write] {positions.shape[0]:,} gaussians -> {save_path}")
|
| 161 |
+
print_percentiles("written raw opacity", raw_opacity)
|
| 162 |
+
print_percentiles("written alpha", alpha_values)
|
| 163 |
+
print_percentiles("written f_dc", dc)
|
| 164 |
+
approx_rgb = np.clip(dc * SH_C0 + 0.5, 0.0, 1.0)
|
| 165 |
+
print_percentiles("approx RGB from DC only", approx_rgb)
|
| 166 |
+
print_percentiles("written raw scale", scales)
|
| 167 |
+
print_percentiles("exp(written scale)", np.exp(np.clip(scales, -80.0, 80.0)))
|
| 168 |
+
print_percentiles("decoded physical volume", volumes)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def parse_args() -> argparse.Namespace:
|
| 172 |
+
parser = argparse.ArgumentParser(description="Rewrite generated debug_npz as PLY with fixed opacity.")
|
| 173 |
+
parser.add_argument("--debug_npz", required=True)
|
| 174 |
+
parser.add_argument("--codebook_dir", required=True)
|
| 175 |
+
parser.add_argument("--save_path", required=True)
|
| 176 |
+
group = parser.add_mutually_exclusive_group()
|
| 177 |
+
group.add_argument("--alpha", type=float, help="Fixed alpha value to write, converted to raw logit.")
|
| 178 |
+
group.add_argument("--opacity_logit", type=float, help="Fixed raw opacity logit to write.")
|
| 179 |
+
parser.add_argument("--force_rgb", nargs=3, type=float,
|
| 180 |
+
help="Force DC color to this RGB in [0,1] and zero SH rest.")
|
| 181 |
+
parser.add_argument("--scale_offset", type=float, default=0.0,
|
| 182 |
+
help="Add this value to all raw log-scales. 0.693 roughly doubles physical scale.")
|
| 183 |
+
return parser.parse_args()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
args = parse_args()
|
| 188 |
+
write_ply(
|
| 189 |
+
debug_npz=args.debug_npz,
|
| 190 |
+
codebook_dir=args.codebook_dir,
|
| 191 |
+
save_path=args.save_path,
|
| 192 |
+
alpha=args.alpha,
|
| 193 |
+
opacity_logit=args.opacity_logit,
|
| 194 |
+
force_rgb=args.force_rgb,
|
| 195 |
+
scale_offset=args.scale_offset,
|
| 196 |
+
)
|