| """ |
| Rewrite a 3DGS PLY opacity field to a saturated infer-like distribution. |
| |
| The PLY `opacity` field in standard 3DGS is raw logit opacity, not alpha. |
| This script builds a target alpha distribution and writes logit(alpha) back |
| to the PLY while leaving all other vertex fields unchanged. |
| |
| Default profile: |
| - 95% of points get alpha=0.95, matching an opacity cap at logit(0.95) |
| - the remaining 5% get a tiny transparent tail near the user's diagnose log |
| """ |
|
|
| import argparse |
| import os |
|
|
| import numpy as np |
|
|
|
|
| PERCENTILES = [0, 1, 50, 90, 95, 99, 99.9, 100] |
| DEFAULT_LOW_ALPHA_MIN = 1.2487531e-6 |
| DEFAULT_LOW_ALPHA_MAX = 5.3099717e-6 |
|
|
|
|
| def sigmoid(x: np.ndarray) -> np.ndarray: |
| return 1.0 / (1.0 + np.exp(-np.clip(x, -80.0, 80.0))) |
|
|
|
|
| def logit(alpha: np.ndarray) -> np.ndarray: |
| alpha = np.clip(alpha, 1e-6, 1.0 - 1e-6) |
| return np.log(alpha / (1.0 - alpha)) |
|
|
|
|
| def print_percentiles(name: str, values: np.ndarray) -> None: |
| pct = np.percentile(values, PERCENTILES, axis=0) |
| print(f"\n[{name}]") |
| for p, row in zip(PERCENTILES, pct): |
| row = np.asarray(row).reshape(-1) |
| joined = " ".join(f"{float(v): .8g}" for v in row) |
| print(f" p{p:>5}: {joined}") |
|
|
|
|
| def build_alpha_profile( |
| n_points: int, |
| high_fraction: float, |
| high_alpha: float, |
| low_alpha_min: float, |
| low_alpha_max: float, |
| seed: int, |
| ) -> np.ndarray: |
| if n_points <= 0: |
| return np.zeros((0,), dtype=np.float32) |
|
|
| high_fraction = float(np.clip(high_fraction, 0.0, 1.0)) |
| high_alpha = float(np.clip(high_alpha, 1e-6, 1.0 - 1e-6)) |
| low_alpha_min = float(np.clip(low_alpha_min, 1e-6, 1.0 - 1e-6)) |
| low_alpha_max = float(np.clip(low_alpha_max, low_alpha_min, high_alpha)) |
|
|
| n_high = int(round(n_points * high_fraction)) |
| n_high = max(0, min(n_points, n_high)) |
| n_low = n_points - n_high |
|
|
| alpha = np.empty(n_points, dtype=np.float32) |
| if n_low > 0: |
| |
| low = np.geomspace(low_alpha_min, low_alpha_max, n_low).astype(np.float32) |
| alpha[:n_low] = low |
| if n_high > 0: |
| alpha[n_low:] = high_alpha |
|
|
| rng = np.random.default_rng(seed) |
| rng.shuffle(alpha) |
| return alpha |
|
|
|
|
| def assign_alpha( |
| original_raw_opacity: np.ndarray, |
| target_alpha: np.ndarray, |
| assignment: str, |
| seed: int, |
| ) -> np.ndarray: |
| if assignment == "random": |
| return target_alpha |
|
|
| if assignment == "rank": |
| original_alpha = sigmoid(original_raw_opacity) |
| order_src = np.argsort(original_alpha) |
| sorted_target = np.sort(target_alpha) |
| assigned = np.empty_like(target_alpha) |
| assigned[order_src] = sorted_target |
| return assigned |
|
|
| if assignment == "shuffle": |
| assigned = np.sort(target_alpha) |
| rng = np.random.default_rng(seed) |
| rng.shuffle(assigned) |
| return assigned |
|
|
| raise ValueError(f"Unknown assignment mode: {assignment}") |
|
|
|
|
| def rewrite_opacity(args: argparse.Namespace) -> None: |
| try: |
| from plyfile import PlyData, PlyElement |
| except ImportError as exc: |
| raise ImportError( |
| "Missing dependency 'plyfile'. Install it in the environment that will run this " |
| "script, for example: pip install plyfile" |
| ) from exc |
|
|
| ply = PlyData.read(args.input_ply) |
| if "vertex" not in ply: |
| raise ValueError("PLY does not contain a vertex element") |
|
|
| vertex = ply["vertex"] |
| names = vertex.data.dtype.names |
| if "opacity" not in names: |
| raise ValueError("PLY vertex element does not contain an opacity field") |
|
|
| arr = vertex.data.copy() |
| original_raw = np.asarray(arr["opacity"], dtype=np.float32).reshape(-1) |
|
|
| target_alpha = build_alpha_profile( |
| n_points=original_raw.shape[0], |
| high_fraction=args.high_fraction, |
| high_alpha=args.high_alpha, |
| low_alpha_min=args.low_alpha_min, |
| low_alpha_max=args.low_alpha_max, |
| seed=args.seed, |
| ) |
| assigned_alpha = assign_alpha( |
| original_raw_opacity=original_raw, |
| target_alpha=target_alpha, |
| assignment=args.assignment, |
| seed=args.seed, |
| ) |
| new_raw = logit(assigned_alpha).astype(np.float32) |
| arr["opacity"] = new_raw |
|
|
| os.makedirs(os.path.dirname(os.path.abspath(args.output_ply)), exist_ok=True) |
| PlyData([PlyElement.describe(arr, "vertex")], text=ply.text).write(args.output_ply) |
|
|
| print(f"[rewrite] input: {os.path.abspath(args.input_ply)}") |
| print(f"[rewrite] output: {os.path.abspath(args.output_ply)}") |
| print(f"[rewrite] points: {original_raw.shape[0]:,}") |
| print( |
| "[rewrite] target profile: " |
| f"high_fraction={args.high_fraction:.4f}, high_alpha={args.high_alpha:.6f}, " |
| f"low_alpha=[{args.low_alpha_min:.8g}, {args.low_alpha_max:.8g}], " |
| f"assignment={args.assignment}" |
| ) |
|
|
| print_percentiles("original opacity raw field", original_raw) |
| print_percentiles("original sigmoid(opacity)", sigmoid(original_raw)) |
| print_percentiles("written opacity raw field", new_raw) |
| print_percentiles("written sigmoid(opacity)", sigmoid(new_raw)) |
|
|
| high_hit = np.mean(assigned_alpha >= args.high_alpha - 1e-6) |
| print(f"\n[summary] fraction(alpha >= high_alpha): {high_hit:.4%}") |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Rewrite a 3DGS PLY opacity field to an infer-like saturated alpha distribution." |
| ) |
| parser.add_argument("input_ply", help="Input PLY path.") |
| parser.add_argument("output_ply", help="Output PLY path.") |
| parser.add_argument( |
| "--high_fraction", |
| type=float, |
| default=0.95, |
| help="Fraction of points assigned high_alpha. Default: 0.95.", |
| ) |
| parser.add_argument( |
| "--high_alpha", |
| type=float, |
| default=0.95, |
| help="High target alpha value. Written as logit(high_alpha). Default: 0.95.", |
| ) |
| parser.add_argument( |
| "--low_alpha_min", |
| type=float, |
| default=DEFAULT_LOW_ALPHA_MIN, |
| help="Minimum alpha for the transparent tail.", |
| ) |
| parser.add_argument( |
| "--low_alpha_max", |
| type=float, |
| default=DEFAULT_LOW_ALPHA_MAX, |
| help="Maximum alpha for the transparent tail.", |
| ) |
| parser.add_argument( |
| "--assignment", |
| choices=["rank", "random", "shuffle"], |
| default="rank", |
| help=( |
| "How to assign target alphas to points. 'rank' preserves the original opacity rank; " |
| "'random' uses the generated shuffled profile; 'shuffle' shuffles a sorted profile." |
| ), |
| ) |
| parser.add_argument("--seed", type=int, default=42, help="Random seed for tail shuffling.") |
| return parser.parse_args() |
|
|
|
|
| if __name__ == "__main__": |
| rewrite_opacity(parse_args()) |
|
|