SlekLi commited on
Commit
d4471ec
·
verified ·
1 Parent(s): 018cc0b

Upload rewrite_op.py

Browse files
Files changed (1) hide show
  1. rewrite_op.py +205 -0
rewrite_op.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Rewrite a 3DGS PLY opacity field to a saturated infer-like distribution.
3
+
4
+ The PLY `opacity` field in standard 3DGS is raw logit opacity, not alpha.
5
+ This script builds a target alpha distribution and writes logit(alpha) back
6
+ to the PLY while leaving all other vertex fields unchanged.
7
+
8
+ Default profile:
9
+ - 95% of points get alpha=0.95, matching an opacity cap at logit(0.95)
10
+ - the remaining 5% get a tiny transparent tail near the user's diagnose log
11
+ """
12
+
13
+ import argparse
14
+ import os
15
+
16
+ import numpy as np
17
+
18
+
19
+ PERCENTILES = [0, 1, 50, 90, 95, 99, 99.9, 100]
20
+ DEFAULT_LOW_ALPHA_MIN = 1.2487531e-6
21
+ DEFAULT_LOW_ALPHA_MAX = 5.3099717e-6
22
+
23
+
24
+ def sigmoid(x: np.ndarray) -> np.ndarray:
25
+ return 1.0 / (1.0 + np.exp(-np.clip(x, -80.0, 80.0)))
26
+
27
+
28
+ def logit(alpha: np.ndarray) -> np.ndarray:
29
+ alpha = np.clip(alpha, 1e-6, 1.0 - 1e-6)
30
+ return np.log(alpha / (1.0 - alpha))
31
+
32
+
33
+ def print_percentiles(name: str, values: np.ndarray) -> None:
34
+ pct = np.percentile(values, PERCENTILES, axis=0)
35
+ print(f"\n[{name}]")
36
+ for p, row in zip(PERCENTILES, pct):
37
+ row = np.asarray(row).reshape(-1)
38
+ joined = " ".join(f"{float(v): .8g}" for v in row)
39
+ print(f" p{p:>5}: {joined}")
40
+
41
+
42
+ def build_alpha_profile(
43
+ n_points: int,
44
+ high_fraction: float,
45
+ high_alpha: float,
46
+ low_alpha_min: float,
47
+ low_alpha_max: float,
48
+ seed: int,
49
+ ) -> np.ndarray:
50
+ if n_points <= 0:
51
+ return np.zeros((0,), dtype=np.float32)
52
+
53
+ high_fraction = float(np.clip(high_fraction, 0.0, 1.0))
54
+ high_alpha = float(np.clip(high_alpha, 1e-6, 1.0 - 1e-6))
55
+ low_alpha_min = float(np.clip(low_alpha_min, 1e-6, 1.0 - 1e-6))
56
+ low_alpha_max = float(np.clip(low_alpha_max, low_alpha_min, high_alpha))
57
+
58
+ n_high = int(round(n_points * high_fraction))
59
+ n_high = max(0, min(n_points, n_high))
60
+ n_low = n_points - n_high
61
+
62
+ alpha = np.empty(n_points, dtype=np.float32)
63
+ if n_low > 0:
64
+ # Log-space tail keeps the low-opacity values close to the diagnose log.
65
+ low = np.geomspace(low_alpha_min, low_alpha_max, n_low).astype(np.float32)
66
+ alpha[:n_low] = low
67
+ if n_high > 0:
68
+ alpha[n_low:] = high_alpha
69
+
70
+ rng = np.random.default_rng(seed)
71
+ rng.shuffle(alpha)
72
+ return alpha
73
+
74
+
75
+ def assign_alpha(
76
+ original_raw_opacity: np.ndarray,
77
+ target_alpha: np.ndarray,
78
+ assignment: str,
79
+ seed: int,
80
+ ) -> np.ndarray:
81
+ if assignment == "random":
82
+ return target_alpha
83
+
84
+ if assignment == "rank":
85
+ original_alpha = sigmoid(original_raw_opacity)
86
+ order_src = np.argsort(original_alpha)
87
+ sorted_target = np.sort(target_alpha)
88
+ assigned = np.empty_like(target_alpha)
89
+ assigned[order_src] = sorted_target
90
+ return assigned
91
+
92
+ if assignment == "shuffle":
93
+ assigned = np.sort(target_alpha)
94
+ rng = np.random.default_rng(seed)
95
+ rng.shuffle(assigned)
96
+ return assigned
97
+
98
+ raise ValueError(f"Unknown assignment mode: {assignment}")
99
+
100
+
101
+ def rewrite_opacity(args: argparse.Namespace) -> None:
102
+ try:
103
+ from plyfile import PlyData, PlyElement
104
+ except ImportError as exc:
105
+ raise ImportError(
106
+ "Missing dependency 'plyfile'. Install it in the environment that will run this "
107
+ "script, for example: pip install plyfile"
108
+ ) from exc
109
+
110
+ ply = PlyData.read(args.input_ply)
111
+ if "vertex" not in ply:
112
+ raise ValueError("PLY does not contain a vertex element")
113
+
114
+ vertex = ply["vertex"]
115
+ names = vertex.data.dtype.names
116
+ if "opacity" not in names:
117
+ raise ValueError("PLY vertex element does not contain an opacity field")
118
+
119
+ arr = vertex.data.copy()
120
+ original_raw = np.asarray(arr["opacity"], dtype=np.float32).reshape(-1)
121
+
122
+ target_alpha = build_alpha_profile(
123
+ n_points=original_raw.shape[0],
124
+ high_fraction=args.high_fraction,
125
+ high_alpha=args.high_alpha,
126
+ low_alpha_min=args.low_alpha_min,
127
+ low_alpha_max=args.low_alpha_max,
128
+ seed=args.seed,
129
+ )
130
+ assigned_alpha = assign_alpha(
131
+ original_raw_opacity=original_raw,
132
+ target_alpha=target_alpha,
133
+ assignment=args.assignment,
134
+ seed=args.seed,
135
+ )
136
+ new_raw = logit(assigned_alpha).astype(np.float32)
137
+ arr["opacity"] = new_raw
138
+
139
+ os.makedirs(os.path.dirname(os.path.abspath(args.output_ply)), exist_ok=True)
140
+ PlyData([PlyElement.describe(arr, "vertex")], text=ply.text).write(args.output_ply)
141
+
142
+ print(f"[rewrite] input: {os.path.abspath(args.input_ply)}")
143
+ print(f"[rewrite] output: {os.path.abspath(args.output_ply)}")
144
+ print(f"[rewrite] points: {original_raw.shape[0]:,}")
145
+ print(
146
+ "[rewrite] target profile: "
147
+ f"high_fraction={args.high_fraction:.4f}, high_alpha={args.high_alpha:.6f}, "
148
+ f"low_alpha=[{args.low_alpha_min:.8g}, {args.low_alpha_max:.8g}], "
149
+ f"assignment={args.assignment}"
150
+ )
151
+
152
+ print_percentiles("original opacity raw field", original_raw)
153
+ print_percentiles("original sigmoid(opacity)", sigmoid(original_raw))
154
+ print_percentiles("written opacity raw field", new_raw)
155
+ print_percentiles("written sigmoid(opacity)", sigmoid(new_raw))
156
+
157
+ high_hit = np.mean(assigned_alpha >= args.high_alpha - 1e-6)
158
+ print(f"\n[summary] fraction(alpha >= high_alpha): {high_hit:.4%}")
159
+
160
+
161
+ def parse_args() -> argparse.Namespace:
162
+ parser = argparse.ArgumentParser(
163
+ description="Rewrite a 3DGS PLY opacity field to an infer-like saturated alpha distribution."
164
+ )
165
+ parser.add_argument("input_ply", help="Input PLY path.")
166
+ parser.add_argument("output_ply", help="Output PLY path.")
167
+ parser.add_argument(
168
+ "--high_fraction",
169
+ type=float,
170
+ default=0.95,
171
+ help="Fraction of points assigned high_alpha. Default: 0.95.",
172
+ )
173
+ parser.add_argument(
174
+ "--high_alpha",
175
+ type=float,
176
+ default=0.95,
177
+ help="High target alpha value. Written as logit(high_alpha). Default: 0.95.",
178
+ )
179
+ parser.add_argument(
180
+ "--low_alpha_min",
181
+ type=float,
182
+ default=DEFAULT_LOW_ALPHA_MIN,
183
+ help="Minimum alpha for the transparent tail.",
184
+ )
185
+ parser.add_argument(
186
+ "--low_alpha_max",
187
+ type=float,
188
+ default=DEFAULT_LOW_ALPHA_MAX,
189
+ help="Maximum alpha for the transparent tail.",
190
+ )
191
+ parser.add_argument(
192
+ "--assignment",
193
+ choices=["rank", "random", "shuffle"],
194
+ default="rank",
195
+ help=(
196
+ "How to assign target alphas to points. 'rank' preserves the original opacity rank; "
197
+ "'random' uses the generated shuffled profile; 'shuffle' shuffles a sorted profile."
198
+ ),
199
+ )
200
+ parser.add_argument("--seed", type=int, default=42, help="Random seed for tail shuffling.")
201
+ return parser.parse_args()
202
+
203
+
204
+ if __name__ == "__main__":
205
+ rewrite_opacity(parse_args())