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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
3DGS Codebook Builder
|
| 3 |
+
=====================
|
| 4 |
+
ไฝฟ็จ KMeans ๅฏน 3D Gaussian Splatting ๆจกๅ็ๅ็ฑป็นๅพๅๅซๆๅปบ codebook๏ผ
|
| 5 |
+
- scale (3็ปด) โ 16384 ไธช็ฆปๆฃ็ดขๅผ
|
| 6 |
+
- rotation (4็ปด) โ 16384 ไธช็ฆปๆฃ็ดขๅผ
|
| 7 |
+
- DC (3็ปด) โ 4096 ไธช็ฆปๆฃ็ดขๅผ
|
| 8 |
+
- SH rest (45็ปด) โ 4096 ไธช็ฆปๆฃ็ดขๅผ
|
| 9 |
+
|
| 10 |
+
ๆฏไธช codebook ๅ็ฌไฟๅญไธบ .npz ๆไปถ๏ผๅ
ๅซ๏ผ
|
| 11 |
+
- codebook : (K, D) float32 โโ ่็ฑปไธญๅฟ
|
| 12 |
+
- indices : (N,) int32 โโ ๆฏไธช้ซๆฏ็นๅฏนๅบ็็ดขๅผ
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import argparse
|
| 17 |
+
import numpy as np
|
| 18 |
+
from plyfile import PlyData
|
| 19 |
+
from sklearn.cluster import MiniBatchKMeans
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 24 |
+
# 1. PLY ่ฏปๅ
|
| 25 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 26 |
+
|
| 27 |
+
def read_ply(ply_path: str) -> dict:
|
| 28 |
+
"""่ฏปๅ 3DGS .ply ๆไปถ๏ผ่ฟๅๅๅฑๆง numpy ๆฐ็ปใ"""
|
| 29 |
+
plydata = PlyData.read(ply_path)
|
| 30 |
+
vertex = plydata['vertex']
|
| 31 |
+
|
| 32 |
+
positions = np.stack([vertex['x'], vertex['y'], vertex['z']], axis=1) # (N, 3)
|
| 33 |
+
opacities = vertex['opacity'][:, np.newaxis] # (N, 1)
|
| 34 |
+
scales = np.stack([vertex['scale_0'], vertex['scale_1'],
|
| 35 |
+
vertex['scale_2']], axis=1) # (N, 3)
|
| 36 |
+
rotations = np.stack([vertex['rot_0'], vertex['rot_1'],
|
| 37 |
+
vertex['rot_2'], vertex['rot_3']], axis=1) # (N, 4)
|
| 38 |
+
dc = np.stack([vertex['f_dc_0'], vertex['f_dc_1'],
|
| 39 |
+
vertex['f_dc_2']], axis=1) # (N, 3)
|
| 40 |
+
|
| 41 |
+
sh_keys = sorted(
|
| 42 |
+
[k for k in vertex.data.dtype.names if k.startswith('f_rest_')],
|
| 43 |
+
key=lambda s: int(s.split('_')[-1])
|
| 44 |
+
)
|
| 45 |
+
sh_rest = np.stack([vertex[k] for k in sh_keys], axis=1) \
|
| 46 |
+
if sh_keys else None # (N, 45)
|
| 47 |
+
|
| 48 |
+
# filter_3D ๆฏๅฏ้ๅญๆฎต๏ผ้จๅ็ๆฌๆ๏ผ้จๅๆฒกๆ๏ผ
|
| 49 |
+
filter_3d = None
|
| 50 |
+
if 'filter_3D' in vertex.data.dtype.names:
|
| 51 |
+
filter_3d = vertex['filter_3D'][:, np.newaxis] # (N, 1)
|
| 52 |
+
|
| 53 |
+
print(f"[read_ply] ่ฏปๅๅฎๆ๏ผ{positions.shape[0]} ไธช้ซๆฏ็น")
|
| 54 |
+
if sh_rest is not None:
|
| 55 |
+
print(f" SH rest ็ปดๅบฆ๏ผ{sh_rest.shape[1]} "
|
| 56 |
+
f"๏ผๆๆ 45 = 15 ็่ฐ็ณปๆฐ ร 3 ้้๏ผ")
|
| 57 |
+
|
| 58 |
+
return {
|
| 59 |
+
'positions': positions,
|
| 60 |
+
'opacities': opacities,
|
| 61 |
+
'scales': scales,
|
| 62 |
+
'rotations': rotations,
|
| 63 |
+
'dc': dc,
|
| 64 |
+
'sh_rest': sh_rest,
|
| 65 |
+
'filter_3d': filter_3d,
|
| 66 |
+
'plydata': plydata,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 71 |
+
# 2. KMeans ่็ฑป๏ผMiniBatchKMeans๏ผ้ๅบฆๅฟซ๏ผ
|
| 72 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 73 |
+
|
| 74 |
+
def build_codebook(
|
| 75 |
+
features: np.ndarray,
|
| 76 |
+
n_clusters: int,
|
| 77 |
+
name: str,
|
| 78 |
+
random_state: int = 42,
|
| 79 |
+
batch_size: int = 65536,
|
| 80 |
+
max_iter: int = 300,
|
| 81 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 82 |
+
"""
|
| 83 |
+
ๅฏน features (N, D) ๆง่ก MiniBatchKMeans๏ผ่ฟๅ๏ผ
|
| 84 |
+
codebook : (K, D) float32
|
| 85 |
+
indices : (N,) int32
|
| 86 |
+
"""
|
| 87 |
+
N, D = features.shape
|
| 88 |
+
# ่ฅ็นๆฐๅฐไบ cluster ๆฐ๏ผ็ดๆฅๆๆฏไธช็นๅฝไธไธช cluster
|
| 89 |
+
K = min(n_clusters, N)
|
| 90 |
+
if K < n_clusters:
|
| 91 |
+
print(f"[{name}] ่ญฆๅ๏ผ้ซๆฏ็นๆฐ ({N}) < ็ฎๆ cluster ๆฐ ({n_clusters})๏ผ"
|
| 92 |
+
f"่ชๅจ่ฐๆดไธบ K={K}")
|
| 93 |
+
|
| 94 |
+
print(f"[{name}] ๅผๅง KMeans๏ผN={N}, D={D}, K={K} ...")
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
|
| 97 |
+
kmeans = MiniBatchKMeans(
|
| 98 |
+
n_clusters=K,
|
| 99 |
+
batch_size=min(batch_size, N),
|
| 100 |
+
max_iter=max_iter,
|
| 101 |
+
random_state=random_state,
|
| 102 |
+
n_init=3,
|
| 103 |
+
verbose=0,
|
| 104 |
+
)
|
| 105 |
+
kmeans.fit(features.astype(np.float32))
|
| 106 |
+
|
| 107 |
+
codebook = kmeans.cluster_centers_.astype(np.float32) # (K, D)
|
| 108 |
+
indices = kmeans.labels_.astype(np.int32) # (N,)
|
| 109 |
+
|
| 110 |
+
elapsed = time.time() - t0
|
| 111 |
+
inertia = kmeans.inertia_
|
| 112 |
+
print(f"[{name}] ๅฎๆ๏ผ่ๆถ {elapsed:.1f}s | inertia={inertia:.4f}")
|
| 113 |
+
print(f" codebook shape: {codebook.shape} | "
|
| 114 |
+
f"็ดขๅผ่ๅด: [{indices.min()}, {indices.max()}]")
|
| 115 |
+
|
| 116 |
+
return codebook, indices
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 120 |
+
# 3. ไฟๅญๅไธช codebook
|
| 121 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 122 |
+
|
| 123 |
+
def save_codebook(
|
| 124 |
+
save_dir: str,
|
| 125 |
+
name: str,
|
| 126 |
+
codebook: np.ndarray,
|
| 127 |
+
indices: np.ndarray,
|
| 128 |
+
) -> None:
|
| 129 |
+
"""ๅฐ codebook ๅ indices ๅญไธบ <name>_codebook.npzใ"""
|
| 130 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 131 |
+
out_path = os.path.join(save_dir, f"{name}_codebook.npz")
|
| 132 |
+
np.savez_compressed(out_path, codebook=codebook, indices=indices)
|
| 133 |
+
size_mb = os.path.getsize(out_path) / 1024 / 1024
|
| 134 |
+
print(f"[{name}] ๅทฒไฟๅญ โ {out_path} ({size_mb:.2f} MB)")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 138 |
+
# 4. ไธปๆต็จ
|
| 139 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 140 |
+
|
| 141 |
+
CODEBOOK_CONFIG = {
|
| 142 |
+
# name n_clusters
|
| 143 |
+
'scale': 16384,
|
| 144 |
+
'rotation': 16384,
|
| 145 |
+
'dc': 4096,
|
| 146 |
+
'sh': 4096,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def build_all_codebooks(
|
| 151 |
+
ply_path: str,
|
| 152 |
+
save_dir: str,
|
| 153 |
+
random_state: int = 42,
|
| 154 |
+
) -> dict:
|
| 155 |
+
"""
|
| 156 |
+
่ฏปๅ PLY โ ๅฏนๅ็ฑป็นๅพๅๅซ่็ฑป โ ๅๅผไฟๅญใ
|
| 157 |
+
|
| 158 |
+
่ฟๅๅญๅ
ธ๏ผ
|
| 159 |
+
{
|
| 160 |
+
'scale': (codebook_array, indices_array),
|
| 161 |
+
'rotation': ...,
|
| 162 |
+
'dc': ...,
|
| 163 |
+
'sh': ...,
|
| 164 |
+
}
|
| 165 |
+
"""
|
| 166 |
+
# โโ ่ฏปๅๆฐๆฎ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 167 |
+
data = read_ply(ply_path)
|
| 168 |
+
|
| 169 |
+
scales = data['scales'] # (N, 3)
|
| 170 |
+
rotations = data['rotations'] # (N, 4)
|
| 171 |
+
dc = data['dc'] # (N, 3)
|
| 172 |
+
sh_rest = data['sh_rest'] # (N, 45) ๅทฒๅป้ค DC ็ SH
|
| 173 |
+
|
| 174 |
+
if sh_rest is None:
|
| 175 |
+
raise ValueError("PLY ๆไปถไธญๆชๆพๅฐ f_rest_* ๅญๆฎต๏ผๆ ๆณๆๅปบ SH codebookใ")
|
| 176 |
+
|
| 177 |
+
feature_map = {
|
| 178 |
+
'scale': scales,
|
| 179 |
+
'rotation': rotations,
|
| 180 |
+
'dc': dc,
|
| 181 |
+
'sh': sh_rest, # SH codebook ไฝฟ็จๅปๆ DC ็ 45 ็ปด้ซ้ขๅ้
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
# โโ ้ไธ่็ฑปๅนถไฟๅญ โโโโโโโโโโโโโโโโโโโโโโโโ
|
| 185 |
+
results = {}
|
| 186 |
+
for name, n_clusters in CODEBOOK_CONFIG.items():
|
| 187 |
+
features = feature_map[name]
|
| 188 |
+
print(f"\n{'='*55}")
|
| 189 |
+
print(f" ๆๅปบ [{name}] codebook | ็นๅพ็ปดๅบฆ: {features.shape[1]}"
|
| 190 |
+
f" | ็ฎๆ K: {n_clusters}")
|
| 191 |
+
print(f"{'='*55}")
|
| 192 |
+
|
| 193 |
+
codebook, indices = build_codebook(
|
| 194 |
+
features,
|
| 195 |
+
n_clusters=n_clusters,
|
| 196 |
+
name=name,
|
| 197 |
+
random_state=random_state,
|
| 198 |
+
)
|
| 199 |
+
save_codebook(save_dir, name, codebook, indices)
|
| 200 |
+
results[name] = (codebook, indices)
|
| 201 |
+
|
| 202 |
+
print(f"\n{'='*55}")
|
| 203 |
+
print(" ๆๆ codebook ๆๅปบๅฎๆฏ๏ผ")
|
| 204 |
+
print(f" ่พๅบ็ฎๅฝ๏ผ{os.path.abspath(save_dir)}")
|
| 205 |
+
print(f"{'='*55}")
|
| 206 |
+
return results
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 210 |
+
# 5. ้ช่ฏ๏ผไป codebook ้ๅปบ็นๅพๅนถ่ฎก็ฎ่ฏฏๅทฎ
|
| 211 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 212 |
+
|
| 213 |
+
def evaluate_codebooks(
|
| 214 |
+
ply_path: str,
|
| 215 |
+
save_dir: str,
|
| 216 |
+
) -> None:
|
| 217 |
+
"""
|
| 218 |
+
ๅ ่ฝฝๅทฒไฟๅญ็ๅไธช codebook๏ผ้ๅปบ็นๅพ๏ผ
|
| 219 |
+
่ฎก็ฎๆฏไธช็ปดๅบฆ็ๅๆนๆ น่ฏฏๅทฎ๏ผRMSE๏ผใ
|
| 220 |
+
"""
|
| 221 |
+
data = read_ply(ply_path)
|
| 222 |
+
feature_map = {
|
| 223 |
+
'scale': data['scales'],
|
| 224 |
+
'rotation': data['rotations'],
|
| 225 |
+
'dc': data['dc'],
|
| 226 |
+
'sh': data['sh_rest'],
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
print("\n[่ฏไผฐ] ้ๅปบ่ฏฏๅทฎ๏ผRMSE๏ผ๏ผ")
|
| 230 |
+
for name in CODEBOOK_CONFIG:
|
| 231 |
+
path = os.path.join(save_dir, f"{name}_codebook.npz")
|
| 232 |
+
if not os.path.exists(path):
|
| 233 |
+
print(f" [{name}] ๆไปถไธๅญๅจ๏ผ่ทณ่ฟ")
|
| 234 |
+
continue
|
| 235 |
+
|
| 236 |
+
npz = np.load(path)
|
| 237 |
+
codebook = npz['codebook'] # (K, D)
|
| 238 |
+
indices = npz['indices'] # (N,)
|
| 239 |
+
|
| 240 |
+
original = feature_map[name].astype(np.float32)
|
| 241 |
+
reconstructed = codebook[indices] # (N, D)
|
| 242 |
+
|
| 243 |
+
rmse = np.sqrt(np.mean((original - reconstructed) ** 2))
|
| 244 |
+
max_err = np.abs(original - reconstructed).max()
|
| 245 |
+
print(f" [{name:8s}] K={codebook.shape[0]:6d} D={codebook.shape[1]:3d}"
|
| 246 |
+
f" RMSE={rmse:.6f} MaxErr={max_err:.6f}")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 250 |
+
# 6. CLI ๅ
ฅๅฃ
|
| 251 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 252 |
+
|
| 253 |
+
def parse_args():
|
| 254 |
+
parser = argparse.ArgumentParser(
|
| 255 |
+
description="ไธบ 3DGS .ply ๆไปถๆๅปบๅไธช KMeans codebook"
|
| 256 |
+
)
|
| 257 |
+
parser.add_argument('ply_path', type=str,default="./merge/original_3dgs.ply",
|
| 258 |
+
help='่พๅ
ฅ็ 3DGS .ply ๆไปถ่ทฏๅพ')
|
| 259 |
+
parser.add_argument('--save_dir', type=str, default='./codebooks',
|
| 260 |
+
help='codebook ไฟๅญ็ฎๅฝ๏ผ้ป่ฎค๏ผ./codebooks๏ผ')
|
| 261 |
+
parser.add_argument('--seed', type=int, default=42,
|
| 262 |
+
help='้ๆบ็งๅญ๏ผ้ป่ฎค๏ผ42๏ผ')
|
| 263 |
+
parser.add_argument('--evaluate', action='store_true',
|
| 264 |
+
help='ๆๅปบๅฎๆๅ่ฎก็ฎ RMSE ้ๅปบ่ฏฏๅทฎ')
|
| 265 |
+
return parser.parse_args()
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
if __name__ == '__main__':
|
| 269 |
+
args = parse_args()
|
| 270 |
+
|
| 271 |
+
build_all_codebooks(
|
| 272 |
+
ply_path=args.ply_path,
|
| 273 |
+
save_dir=args.save_dir,
|
| 274 |
+
random_state=args.seed,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
if args.evaluate:
|
| 278 |
+
evaluate_codebooks(
|
| 279 |
+
ply_path=args.ply_path,
|
| 280 |
+
save_dir=args.save_dir,
|
| 281 |
+
)
|