ysharma HF Staff commited on
Commit
5399134
·
verified ·
1 Parent(s): 3eabdd8

Add full-sweep render script (24 views/object, OSMesa, alpha from depth)

Browse files
Files changed (1) hide show
  1. render_full.py +285 -0
render_full.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Render 24 views (az 0..315 step 45 x elevations low/-20, eye/10, high/40) of ALL
3
+ Google Scanned Objects from suvadityamuk/google-scanned-objects webdataset shards.
4
+
5
+ 768x768 RGBA, transparent background, soft three-point lighting, no ground plane.
6
+ Z-up meshes converted to Y-up. One camera distance per object, from the bounding
7
+ sphere (eye-level projected span ~60% of frame, fov 40 deg). Per-object rejection:
8
+ any view with alpha coverage < 8% or projected span > 95% of frame.
9
+
10
+ Outputs (uploaded to ysharma/gso-orbit-rgba):
11
+ renders/{object_id}/az{000..315}_el{low|eye|high}.png
12
+ metadata.jsonl one line per view
13
+ split.json heldout_40 / rejected_objects / train_objects
14
+ contact_sheets/*.png one sheet per sampled category
15
+ """
16
+ import os
17
+ os.environ['PYOPENGL_PLATFORM'] = 'osmesa' # must precede pyrender import
18
+ import io, json, math, random, tarfile, time, traceback
19
+ from concurrent.futures import ProcessPoolExecutor
20
+
21
+ import numpy as np
22
+ import pyrender
23
+ import trimesh
24
+ from scipy.ndimage import distance_transform_edt
25
+ from huggingface_hub import HfApi
26
+
27
+ DATA = '/data/data'
28
+ OUT = '/out'
29
+ REPO_ID = 'ysharma/gso-orbit-rgba'
30
+ N_SHARDS = 43
31
+ SZ = 1536
32
+ OUTSZ = 768
33
+ FOV_Y = math.radians(40.0)
34
+ FOCAL_F = 0.60
35
+ DIST = 0.5 / (FOCAL_F * math.tan(FOV_Y / 2.0))
36
+ ZNEAR, ZFAR = 0.05, 10.0
37
+ ELEVS = [('low', -20.0), ('eye', 10.0), ('high', 40.0)]
38
+ AZS = list(range(0, 360, 45))
39
+ HALO_RING = 8
40
+ BG = [0.0, 0.0, 0.0]
41
+ COV_MIN = 0.08
42
+ SPAN_MAX = 0.95
43
+ WORKERS = 8
44
+
45
+ T_UP = np.eye(4); T_UP[1, 1] = 0.0; T_UP[1, 2] = -1.0; T_UP[2, 1] = 1.0; T_UP[2, 2] = 0.0
46
+
47
+
48
+ def camera_pose(az_deg, el_deg, dist):
49
+ az, el = math.radians(az_deg), math.radians(el_deg)
50
+ eye = dist * np.array([math.cos(el) * math.cos(az), math.sin(el),
51
+ math.cos(el) * math.sin(az)])
52
+ zax = eye / np.linalg.norm(eye)
53
+ up = np.array([0.0, 1.0, 0.0])
54
+ xax = np.cross(up, zax); xax /= np.linalg.norm(xax)
55
+ yax = np.cross(zax, xax)
56
+ pose = np.eye(4)
57
+ pose[:3, 0], pose[:3, 1], pose[:3, 2], pose[:3, 3] = xax, yax, zax, eye
58
+ return pose
59
+
60
+
61
+ def rot_y(deg):
62
+ a = math.radians(deg)
63
+ R = np.eye(4)
64
+ R[:3, :3] = [[math.cos(a), 0, math.sin(a)], [0, 1, 0], [-math.sin(a), 0, math.cos(a)]]
65
+ return R
66
+
67
+
68
+ def build_scene(glb_bytes):
69
+ st = trimesh.load(io.BytesIO(glb_bytes), file_type='glb', force='scene')
70
+ geoms = list(st.geometry.values())
71
+ for g in geoms:
72
+ g.apply_transform(T_UP)
73
+ mesh = pyrender.Mesh.from_trimesh(geoms)
74
+ scene = pyrender.Scene(bg_color=BG, ambient_light=[0.30, 0.30, 0.30])
75
+ scene.add(mesh)
76
+ return scene
77
+
78
+
79
+ def add_lights(scene, cam_pose):
80
+ base = cam_pose.copy(); base[:3, 3] = 0.0
81
+ scene.add(pyrender.DirectionalLight(intensity=3.0), pose=base @ rot_y(0.0)) # key
82
+ scene.add(pyrender.DirectionalLight(intensity=1.2), pose=base @ rot_y(35.0)) # fill
83
+ scene.add(pyrender.DirectionalLight(intensity=2.0), pose=base @ rot_y(160.0)) # rim
84
+
85
+
86
+ def tar_read(tf, name):
87
+ m = None
88
+ for cand in (name, name.lower(), name.replace(" ", "_")):
89
+ try:
90
+ m = tf.getmember(cand)
91
+ break
92
+ except KeyError:
93
+ continue
94
+ if m is None:
95
+ for mem in tf.getmembers():
96
+ if mem.name.lower() == name.lower():
97
+ m = mem
98
+ break
99
+ if m is None:
100
+ raise KeyError(name)
101
+ f = tf.extractfile(m)
102
+ return f.read() if f else None
103
+
104
+
105
+ def halo_fill(rgb, mask):
106
+ inv = (~mask)
107
+ if not inv.any() or not mask.any():
108
+ return rgb
109
+ dist, idx = distance_transform_edt(inv, return_indices=True)
110
+ fill = inv & (dist <= HALO_RING)
111
+ rgb = rgb.copy()
112
+ ys, xs = np.nonzero(fill)
113
+ rgb[ys, xs] = rgb[idx[0][ys, xs], idx[1][ys, xs]]
114
+ return rgb
115
+
116
+
117
+ def downsample_rgba(rgb, mask):
118
+ premul = rgb.astype(np.float32) * mask[..., None]
119
+ a = mask.astype(np.float32)
120
+ h2 = SZ // 2
121
+ pm = premul.reshape(h2, 2, h2, 2, 3).mean(axis=(1, 3))
122
+ am = a.reshape(h2, 2, h2, 2).mean(axis=(1, 3))
123
+ out = np.zeros((h2, h2, 4), np.uint8)
124
+ good = am > (1.0 / 255.0)
125
+ denom = np.maximum(am, 1e-6)
126
+ for c in range(3):
127
+ ch = np.clip(pm[..., c] / denom, 0, 255)
128
+ out[..., c] = np.where(good, ch, 0).astype(np.uint8)
129
+ out[..., 3] = np.clip(am * 255.0 + 0.5, 0, 255).astype(np.uint8)
130
+ return out
131
+
132
+
133
+ def render_object(args):
134
+ shard_path, object_id, category = args
135
+ t_start = time.time()
136
+ try:
137
+ with tarfile.open(shard_path, 'r') as tf:
138
+ glb_bytes = tar_read(tf, f'{object_id}.glb')
139
+ os.makedirs(os.path.join(OUT, 'renders', object_id), exist_ok=True)
140
+ scene = build_scene(glb_bytes)
141
+ cam = pyrender.PerspectiveCamera(yfov=FOV_Y, znear=ZNEAR, zfar=ZFAR)
142
+ scene.add(cam, pose=camera_pose(0.0, 10.0, DIST))
143
+ add_lights(scene, camera_pose(0.0, 10.0, DIST))
144
+ renderer = pyrender.OffscreenRenderer(SZ, SZ)
145
+ rows, t_render = [], 0.0
146
+ eye_covs = []
147
+ for el_name, el in ELEVS:
148
+ for az in AZS:
149
+ t0 = time.time()
150
+ scene.set_pose(scene.main_camera_node, camera_pose(az, el, DIST))
151
+ color, depth = renderer.render(scene)
152
+ t_render += time.time() - t0
153
+ mask = (depth > 0.0)
154
+ cov = float(mask.mean())
155
+ ys_m, xs_m = np.nonzero(mask)
156
+ span = max((xs_m.max() - xs_m.min()) / SZ, (ys_m.max() - ys_m.min()) / SZ) if len(xs_m) else 0.0
157
+ if el_name == 'eye':
158
+ eye_covs.append(cov)
159
+ rgb = halo_fill(color, mask)
160
+ rgba = downsample_rgba(rgb, mask)
161
+ fn = f'az{az:03d}_el{el_name}.png'
162
+ from PIL import Image
163
+ Image.fromarray(rgba, 'RGBA').save(os.path.join(OUT, 'renders', object_id, fn))
164
+ rows.append({
165
+ 'object_id': object_id, 'category': category,
166
+ 'azimuth_deg': az, 'elevation_deg': el, 'elevation_name': el_name,
167
+ 'camera_azimuth_deg': az, 'camera_elevation_deg': el,
168
+ 'distance': round(DIST, 6), 'coverage': round(cov, 6), 'bbox_span': round(span, 6),
169
+ 'file': f'renders/{object_id}/{fn}',
170
+ })
171
+ renderer.delete()
172
+ rejected = any(r['coverage'] < COV_MIN or r['bbox_span'] > SPAN_MAX for r in rows)
173
+ return {'ok': True, 'rows': rows, 'object_id': object_id, 'rejected': rejected,
174
+ 's_per_view': round(t_render / 24.0, 3),
175
+ 'render_s': round(t_render, 3)}
176
+ except Exception:
177
+ return {'ok': False, 'object_id': object_id, 'error': traceback.format_exc()}
178
+
179
+
180
+ def list_all_objects():
181
+ jobs = []
182
+ for i in range(N_SHARDS):
183
+ shard = os.path.join(DATA, f'gso-train-{i:05d}.tar')
184
+ with tarfile.open(shard, 'r') as tf:
185
+ stems, seen = [], set()
186
+ for m in tf.getnames():
187
+ ext = m.rsplit('.', 1)[1].lower()
188
+ if ext not in ('glb', 'json'):
189
+ continue
190
+ stem = m.rsplit('.', 1)[0]
191
+ if stem not in seen:
192
+ seen.add(stem)
193
+ stems.append(stem)
194
+ for stem in stems:
195
+ with tarfile.open(shard, 'r') as tf:
196
+ j = json.loads(tar_read(tf, f'{stem}.json'))
197
+ jobs.append((shard, stem, j.get('category', '') or 'unlabeled'))
198
+ return jobs
199
+
200
+
201
+ def make_split(jobs, all_flags):
202
+ """40 held-out objects stratified by category; rejected objects excluded from both."""
203
+ cats = {}
204
+ for _, oid, cat in jobs:
205
+ cats.setdefault(cat, []).append(oid)
206
+ rng = random.Random(20260923)
207
+ heldout = []
208
+ total = sum(len(v) for v in cats.values())
209
+ for cat in sorted(cats):
210
+ pool = [o for o in cats[cat] if not all_flags.get(o, False)]
211
+ rng.shuffle(pool)
212
+ n = max(1, round(40.0 * len(pool) / total)) if pool else 0
213
+ heldout.extend(pool[:n])
214
+ rng.shuffle(heldout)
215
+ heldout = heldout[:40]
216
+ hs = set(heldout)
217
+ train = [o for _, o, c in jobs
218
+ if o not in hs and not all_flags.get(o, False)]
219
+ return heldout, train
220
+
221
+
222
+ def contact_sheets(sheets_ids):
223
+ from PIL import Image
224
+ os.makedirs(os.path.join(OUT, 'contact_sheets'), exist_ok=True)
225
+ cell = 256
226
+ for sample_id in sheets_ids:
227
+ sheet = Image.new('RGB', (8 * cell, 3 * cell), (128, 128, 128))
228
+ for r, (_, el) in enumerate(ELEVS):
229
+ for c, az in enumerate(AZS):
230
+ im = Image.open(os.path.join(OUT, 'renders', sample_id, f'az{az:03d}_el{el[0]}.png'))
231
+ im = im.resize((cell, cell), Image.LANCZOS)
232
+ sheet.paste(im, (c * cell, r * cell), im)
233
+ sheet.save(os.path.join(OUT, 'contact_sheets', f'{sample_id}.jpg'), quality=88)
234
+
235
+
236
+ def main():
237
+ t0 = time.time()
238
+ jobs = list_all_objects()
239
+ print(f'{len(jobs)} objects listed across {N_SHARDS} shards', flush=True)
240
+ os.makedirs(OUT, exist_ok=True)
241
+ all_rows, ok_flags, sheets_pool = [], {}, []
242
+ s_per_view = []
243
+ n_ok = n_fail = n_rej = 0
244
+ with ProcessPoolExecutor(max_workers=WORKERS) as ex:
245
+ for k, res in enumerate(ex.map(render_object, jobs)):
246
+ if not res['ok']:
247
+ print(f"FAILED {res['object_id']}: {res['error'][-300:]}", flush=True)
248
+ n_fail += 1
249
+ continue
250
+ n_ok += 1
251
+ all_rows.extend(res['rows'])
252
+ ok_flags[res['object_id']] = res['rejected']
253
+ s_per_view.append(res['s_per_view'])
254
+ if not res['rejected'] and len(sheets_pool) < 8:
255
+ sheets_pool.append(res['object_id'])
256
+ if (k + 1) % 100 == 0:
257
+ print(f' {k+1}/{len(jobs)} objects | mean s/view {np.mean(s_per_view):.3f} '
258
+ f'| elapsed {time.time()-t0:.0f}s', flush=True)
259
+ with open(os.path.join(OUT, 'metadata.jsonl'), 'w') as f:
260
+ for r in all_rows:
261
+ f.write(json.dumps(r) + '\n')
262
+ heldout, train = make_split(jobs, ok_flags)
263
+ split = {'heldout_40': heldout, 'train_objects': train,
264
+ 'rejected_objects': sorted([o for o, r in ok_flags.items() if r]),
265
+ 'failed_objects': [], 'seed': 20260923,
266
+ 'n_renders': len(all_rows), 'instructions_version': 'orbit-relative-v1'}
267
+ with open(os.path.join(OUT, 'split.json'), 'w') as f:
268
+ json.dump(split, f, indent=2)
269
+ contact_sheets(sheets_pool[:6])
270
+ bad = sum(1 for r in all_rows if r['coverage'] < COV_MIN)
271
+ n_rej = sum(1 for r in ok_flags.values() if r)
272
+ print(f'\nDONE {n_ok} ok / {n_fail} failed | rejected {n_rej} objects | '
273
+ f'views <8% cov: {bad}/{len(all_rows)} | {time.time()-t0:.0f}s total '
274
+ f'| mean {np.mean(s_per_view):.3f} s/view ({WORKERS} workers)', flush=True)
275
+ print(f'split: {len(heldout)} heldout, {len(train)} train', flush=True)
276
+
277
+ api = HfApi(token=os.environ.get('HF_TOKEN'))
278
+ print('uploading to Hub (upload_large_folder)...', flush=True)
279
+ t_up = time.time()
280
+ api.upload_large_folder(repo_id=REPO_ID, repo_type='dataset', folder_path=OUT)
281
+ print(f'UPLOAD DONE in {time.time()-t_up:.0f}s', flush=True)
282
+
283
+
284
+ if __name__ == '__main__':
285
+ main()