Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
329 lines (281 loc) · 11.9 KB
/
Copy pathutils.py
File metadata and controls
329 lines (281 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import os, sys, subprocess
import json
import numpy as np
import torch
import torch.nn.functional as F
import colorsys
from scipy.spatial import KDTree
from scipy.ndimage import gaussian_filter, binary_opening, binary_closing
rng = np.random.default_rng
def make_segment_condition(size, k, seed):
def to_binary(seg):
seg_max = torch.argmax(seg, dim=0, keepdim=True) # (1,H,W)
seg_binary = F.one_hot(seg_max.squeeze(0), num_classes=seg.shape[0]).permute(2,0,1).float() # (K,H,W)
return seg_binary
def to_sharp(seg,w=50):
seg_soft = F.softmax(seg*w, dim=0)
return seg_soft
segment = torch.tensor(gaussian_layers(size[0], size[1], k, seed=seed)) # (K,H,W)
segment = to_binary(segment)
# segment = to_sharp(segment)
# segment = segment.unsqueeze(-1).repeat(1,1,1,size[2]) # (K,H,W,D)
return segment
def make_grid_segment_condition(size, reso):
gx, gy, gz = size
H, W, D = gx*reso, gy*reso, gz*reso
K = gx * gy * gz
seg = torch.zeros((H, W, D), dtype=torch.long)
idx = 0
for ix in range(gx):
for iy in range(gy):
for iz in range(gz):
xs, xe = ix * reso, (ix + 1) * reso
ys, ye = iy * reso, (iy + 1) * reso
zs, ze = iz * reso, (iz + 1) * reso
seg[xs:xe, ys:ye, zs:ze] = idx
idx += 1
# one-hot: [H,W,D,K] -> [K,H,W,D]
segment = F.one_hot(seg, num_classes=K).permute(3, 0, 1, 2).float()
return segment
def voronoi_seg(H, W, num_classes, seed=0, jitter=True, morph=True):
rng_ = np.random.default_rng(seed)
# 포인트 찍기
pts = np.stack([rng_.uniform(0, H, size=num_classes),
rng_.uniform(0, W, size=num_classes)], axis=1)
yy, xx = np.meshgrid(np.arange(H), np.arange(W), indexing='ij')
coords = np.stack([yy.reshape(-1), xx.reshape(-1)], axis=1)
tree = KDTree(pts)
_, idx = tree.query(coords, k=1)
seg = idx.reshape(H, W).astype(np.int32)
if jitter:
# 가장자리들 약간 흔들기
noise = rng_.normal(0, 0.5, size=(H, W))
seg = (seg + (gaussian_filter(noise, 1.0) > 0.8)).clip(0, num_classes-1)
if morph:
# 너무 가는 가시 제거
for k in range(num_classes):
mask = (seg == k)
mask = binary_opening(mask, structure=np.ones((3,3)))
mask = binary_closing(mask, structure=np.ones((3,3)))
seg[mask] = k
return seg
def blobs_seg(
H, W, K, seed=0, n_blobs=None,
ensure_all_classes=True,
smooth_sigma=0.0 # 경계 살짝 부드럽게 하고 싶으면 0.3~0.7
):
"""
랜덤 blob 기반 세그멘테이션.
- 항상 K개 클래스가 모두 등장하도록 보장 (ensure_all_classes=True).
- 벡터화 구현으로 빠름.
"""
rng = np.random.default_rng(seed)
if n_blobs is None:
n_blobs = K
# 1) 센터/반경 샘플
cy = rng.uniform(0, H, size=n_blobs)
cx = rng.uniform(0, W, size=n_blobs)
r = rng.uniform(min(H, W)*0.05, min(H, W)*0.25, size=n_blobs)
# (선택) 동일 좌표/타이트한 중복 방지용 아주 작은 지터
cy += rng.normal(0, 1e-3, size=n_blobs)
cx += rng.normal(0, 1e-3, size=n_blobs)
# 2) 라벨 할당: 처음 K개 blob은 0..K-1로 고정 → K 전부 등장 보장
if ensure_all_classes:
labels = np.empty(n_blobs, dtype=np.int32)
# 먼저 0..K-1
labels[:min(K, n_blobs)] = np.arange(min(K, n_blobs))
# 남는 blob은 0..K-1 중 임의로 부여 (merge를 허용)
if n_blobs > K:
labels[K:] = rng.integers(0, K, size=n_blobs - K)
# blob 순서를 섞어 모양 랜덤화
perm = rng.permutation(n_blobs)
cy, cx, r, labels = cy[perm], cx[perm], r[perm], labels[perm]
else:
labels = rng.integers(0, K, size=n_blobs, dtype=np.int32)
# 3) 벡터화 거리계산: score = d / r (작을수록 우선)
yy, xx = np.meshgrid(np.arange(H), np.arange(W), indexing='ij')
# (n_blobs, H, W)
dy = yy[None, :, :] - cy[:, None, None]
dx = xx[None, :, :] - cx[:, None, None]
d = np.sqrt(dy*dy + dx*dx)
score = d / (r[:, None, None] + 1e-6)
# 4) 각 픽셀에서 score가 가장 작은 blob 선택 → 그 blob의 label
winner = np.argmin(score, axis=0) # (H, W) blob index
seg = labels[winner].astype(np.int32) # (H, W) class id
# 5) (옵션) 경계 살짝 부드럽게
if smooth_sigma and smooth_sigma > 0:
seg = gaussian_filter(seg.astype(np.float32), smooth_sigma).round().astype(np.int32)
seg = np.clip(seg, 0, K-1)
# 안전 체크: 모든 클래스가 등장하는지 확인
if ensure_all_classes:
present = set(np.unique(seg))
if len(present) < K:
# 이 케이스는 거의 없지만(중복 좌표 극단적 타이), 하나라도 빠지면
# 빠진 클래스를 강제로 한 픽셀이라도 넣어줌
missing = [c for c in range(K) if c not in present]
for c in missing:
# 해당 클래스의 전용 blob 중 하나의 center를 가장 가까운 정수 좌표에 찍는다.
idx = np.where(labels == c)[0][0]
py = int(np.clip(round(cy[idx]), 0, H-1))
px = int(np.clip(round(cx[idx]), 0, W-1))
seg[py, px] = c
return seg
def gaussian_layers(H, W, K, seed=0, clip_thresh=0.01):
"""
H, W: 출력 해상도
K: Gaussian 개수 (채널 수)
반환: (K, H, W) numpy array
"""
rng = np.random.default_rng(seed)
yy, xx = np.meshgrid(np.arange(H), np.arange(W), indexing="ij")
xx = xx[None, :, :] # shape (1,H,W)
yy = yy[None, :, :] # shape (1,H,W)
layers = np.zeros((K, H, W), dtype=np.float32)
for k in range(K):
# 중심은 uniform random
mu_x = rng.uniform(0, W)
mu_y = rng.uniform(0, H)
# sigma는 화면 크기의 일부로 랜덤 설정
sigma_x = rng.uniform(W * 0.1, W * 0.3) # 분산 범위
sigma_y = rng.uniform(H * 0.1, H * 0.3)
# 2D Gaussian 계산
g = np.exp(-0.5 * (((xx - mu_x) / sigma_x) ** 2 +
((yy - mu_y) / sigma_y) ** 2))
# normalize → 최대값 1
g = g / g.max()
# 너무 작은 값 잘라내기
g[g < clip_thresh] = 0.0
layers[k] = g
return layers
def make_palette(num_classes):
if num_classes <= 0:
return np.zeros((0, 3), dtype=np.uint8)
hues = (np.arange(num_classes) * 0.618033988749895) % 1.0
colors = [
colorsys.hsv_to_rgb(float(hue), 0.38, 0.94)
for hue in hues
]
return (np.asarray(colors, dtype=np.float32).clip(0, 1) * 255).round().astype(np.uint8)
def to_rgb(seg, palette):
rgb = palette[seg] # (H,W,3)
return rgb.astype(np.uint8)
def normalize_coords(coords, max_index, mode="0_1"):
"""
coords: (N,3) numpy or torch, 정수 인덱스 좌표 (0..max_index)
max_index: 63, 127 등 (축별 최대 인덱스가 다르면 튜플/리스트로 전달 가능)
mode: "0_1" -> [0,1], "m1_1" -> [-1,1]
"""
# numpy로 통일
if "torch" in str(type(coords)):
coords = coords.detach().cpu().numpy()
else:
coords = np.asarray(coords)
max_idx = np.array(max_index, dtype=np.float32)
if max_idx.size == 1:
max_idx = np.array([max_idx, max_idx, max_idx], dtype=np.float32)
eps = 1e-8 # 0으로 나눔 방지
if mode == "0_1":
out = coords.astype(np.float32) / (max_idx + eps)
elif mode == "m1_1":
out = (coords.astype(np.float32) / (max_idx + eps)) * 2.0 - 1.0
else:
raise ValueError("mode must be '0_1' or 'm1_1'")
return out
def write_ply(points, path, colors=None, normals=None, binary=True):
"""
points: (N,3) float32
colors: (N,3) uint8 in [0,255] (optional)
normals: (N,3) float32 (optional)
"""
points = np.asarray(points, dtype=np.float32)
N = points.shape[0]
has_colors = colors is not None
has_normals = normals is not None
header = ["ply"]
header.append("format binary_little_endian 1.0" if binary else "format ascii 1.0")
header.append(f"element vertex {N}")
header.append("property float x")
header.append("property float y")
header.append("property float z")
if has_normals:
header.append("property float nx")
header.append("property float ny")
header.append("property float nz")
if has_colors:
header.append("property uchar red")
header.append("property uchar green")
header.append("property uchar blue")
header.append("end_header")
header_str = "\n".join(header) + "\n"
if binary:
with open(path, "wb") as f:
f.write(header_str.encode("ascii"))
# vertex record: x,y,z,(nx,ny,nz),(r,g,b)
rec = [points]
if has_normals:
rec.append(np.asarray(normals, dtype=np.float32))
if has_colors:
rec.append(np.asarray(colors, dtype=np.uint8).view(np.uint8))
# pack into a single structured array-like byte stream
if has_normals and has_colors:
data = np.concatenate([points.view(np.float32),
normals.view(np.float32),
colors.view(np.uint8)], axis=1)
# But concatenation on viewed arrays can be tricky; safest is to interleave per-vertex:
for i in range(N):
f.write(points[i].tobytes())
f.write(normals[i].tobytes())
f.write(colors[i].tobytes())
elif has_normals:
for i in range(N):
f.write(points[i].tobytes())
f.write(normals[i].tobytes())
elif has_colors:
for i in range(N):
f.write(points[i].tobytes())
f.write(colors[i].tobytes())
else:
f.write(points.tobytes())
else:
with open(path, "w") as f:
f.write(header_str)
if has_normals and has_colors:
for i in range(N):
x, y, z = points[i]
nx, ny, nz = normals[i]
r, g, b = colors[i]
f.write(f"{x} {y} {z} {nx} {ny} {nz} {int(r)} {int(g)} {int(b)}\n")
elif has_normals:
for i in range(N):
x, y, z = points[i]
nx, ny, nz = normals[i]
f.write(f"{x} {y} {z} {nx} {ny} {nz}\n")
elif has_colors:
for i in range(N):
x, y, z = points[i]
r, g, b = colors[i]
f.write(f"{x} {y} {z} {int(r)} {int(g)} {int(b)}\n")
else:
for i in range(N):
x, y, z = points[i]
f.write(f"{x} {y} {z}\n")
def save_run_config(args, outdir):
stage1_config = {
"output_dir": outdir,
"model": getattr(args, "resolved_model", "microsoft/TRELLIS-text-xlarge"),
"args": vars(args).copy(),
}
config = {"stage1": stage1_config}
with open(os.path.join(outdir, "config.json"), "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, ensure_ascii=False)
def save_spark_gaussian_assets(gaussian, outdir):
ply_path = os.path.join(outdir, "stage1_sample.ply") ###
spz_path = os.path.join(outdir, "stage1_sample.spz")
gaussian.save_ply(ply_path, transform=None)
converter = os.path.join(os.path.dirname(__file__), "tools", "spark_viewer", "convert_to_spz.mjs")
subprocess.run(["node", converter, ply_path, spz_path],check=True,cwd=os.path.dirname(__file__),)
if os.path.exists(spz_path):
os.remove(ply_path) ### because ply file is large, remove it after conversion
print(f"[spark] wrote {spz_path}")
print(f"[spark] removed temporary {ply_path}")
print(f"[spark] viewer hint: /tools/spark_viewer/?run={os.path.basename(outdir)}&file={os.path.basename(spz_path)}")