whc commited on
Commit
b97e541
·
verified ·
1 Parent(s): 0dccd41

Upload ./convert_gt.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. convert_gt.py +445 -0
convert_gt.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import os
3
+ from utils import load_json, write_json, dir_of_this_file, load_csv
4
+ import torch
5
+ # import numpy as np
6
+ from tqdm import tqdm
7
+
8
+
9
+ sn_2_imgdir = {
10
+ e[0]: Path("/your_path/colmap_results/data/") / e[1]
11
+ for e in load_csv(dir_of_this_file(__file__) / "seed_db.csv")
12
+ }
13
+
14
+
15
+ SAVE_ROOT = dir_of_this_file(__file__) / "gt_cams"
16
+
17
+
18
+ def write_cams(sn, all_cams):
19
+ output_fn = SAVE_ROOT / f"{sn}.json"
20
+ write_json(output_fn, all_cams)
21
+ print(sn, end=',')
22
+ print(output_fn)
23
+
24
+
25
+ def list_scene_fnames(sn):
26
+ return list(sorted(os.listdir(sn_2_imgdir[sn])))
27
+
28
+
29
+ def break_scenes(raw):
30
+ raw = raw.strip().split('\n')
31
+ return [e.strip() for e in raw]
32
+
33
+
34
+ def strip_sn_prefix(sn_name):
35
+ parts = sn_name.split("_")[1:]
36
+ return "_".join(parts)
37
+
38
+
39
+ def invert_trans(trans_T):
40
+ assert trans_T.shape == (4, 4)
41
+ R = trans_T[0:3, 0:3]
42
+ t = trans_T[0:3, 3:4]
43
+ new_T = torch.eye(4, dtype=trans_T.dtype, device=trans_T.device)
44
+ new_T[0:3, 0:3] = R.T
45
+ new_T[0:3, 3:4] = -R.T @ t
46
+ return new_T
47
+
48
+
49
+ def hike():
50
+ ''' # these are problematic scenes
51
+ hike_garden2: cams without their images!
52
+ '''
53
+
54
+ scenes = '''
55
+ hike_forest1
56
+ hike_forest2
57
+ hike_forest3
58
+ hike_garden3
59
+ hike_indoor
60
+ hike_playground
61
+ hike_university1
62
+ hike_university2
63
+ hike_university3
64
+ hike_university4
65
+ '''
66
+ scenes = break_scenes(scenes)
67
+ root = Path("/your_path/colmap_results/data/statichike")
68
+
69
+ # for sn in scenes:
70
+ # gt_path = f"/your_path/colmap_results/data/statichike/{strip_sn_prefix(sn)}/sparse"
71
+ # gt_path = Path(gt_path)
72
+ # assert not (gt_path / "1").is_dir()
73
+ # print(sn, end=',')
74
+ # print(str(gt_path / "0"))
75
+ # return
76
+
77
+ for sn in scenes:
78
+ img_fnames = list_scene_fnames(sn)
79
+
80
+ raw = load_json(
81
+ root / strip_sn_prefix(sn) / "transforms.json"
82
+ )
83
+ frames = list(sorted(raw['frames'], key=lambda x: x['file_path']))
84
+
85
+ cam_dir = root / strip_sn_prefix(sn) / "sparse"
86
+ assert not (cam_dir / "1").is_dir()
87
+
88
+ fr_fnames = [Path(fr['file_path']).name for fr in frames]
89
+
90
+ c2ws_b = torch.tensor(
91
+ [fr['transform_matrix'] for fr in frames],
92
+ dtype=torch.float64, device="cuda"
93
+ )
94
+ # from opengl to opencv
95
+ c2ws_b[:, :, 1] *= -1
96
+ c2ws_b[:, :, 2] *= -1
97
+
98
+ try:
99
+ from metrics import load_colmap_db_cams, pose_stats_suite
100
+ # from read_colmap_model import read_colmap_w2c
101
+ # names, intrs, Rs, ts = read_colmap_w2c(cam_dir / "0")
102
+ names, _, c2ws_a = load_colmap_db_cams(cam_dir / "0", ".bin", return_all=True)
103
+ assert fr_fnames == names
104
+ res = pose_stats_suite(c2ws_a, c2ws_b)
105
+ assert res['ate'] < 1e-5
106
+ assert res['auc_p'][0] > 99.99
107
+ del names, c2ws_a, res
108
+ '''
109
+ the c2w in frames are globally shifted for some reason.
110
+ check that after alignment, error is small.
111
+ '''
112
+ except FileNotFoundError as e:
113
+ print(e)
114
+
115
+ # some imgs are discarded in gt cams
116
+ assert set(fr_fnames).issubset(set(img_fnames))
117
+ # if len(fr_fnames) != len(img_fnames):
118
+ # print(f"{sn} img {len(img_fnames)} vs cam {len(fr_fnames)}")
119
+
120
+ c2ws_b = c2ws_b.cpu().float().tolist()
121
+ all_cams = []
122
+ for i in range(len(frames)):
123
+ all_cams.append({
124
+ 'fname': fr_fnames[i],
125
+ 'c2w': c2ws_b[i]
126
+ })
127
+
128
+ write_cams(sn, all_cams)
129
+
130
+
131
+ def process_meganerf_cam(cam):
132
+ c2w = cam['c2w'] # [3, 4] opengl: x-right, y-up, z-back
133
+ x, y, z, t = torch.unbind(c2w, dim=1)
134
+ c2w = torch.stack([x, -y, -z, t], dim=-1) # opengl -> opencv
135
+ full_c2w = torch.eye(4)
136
+ full_c2w[0:3] = c2w
137
+ return full_c2w
138
+
139
+
140
+ def mill19():
141
+ scenes = """
142
+ mill19_building
143
+ mill19_rubble
144
+ """
145
+ scenes = break_scenes(scenes)
146
+
147
+ for sn in scenes:
148
+ img_fnames = list_scene_fnames(sn)
149
+ cam_dir = Path(f"/your_path/colmap_results/data/mill19/{strip_sn_prefix(sn)}-pixsfm/train/metadata")
150
+ all_cams = []
151
+ for im in tqdm(img_fnames):
152
+ cam_file = cam_dir / Path(im).with_suffix(".pt")
153
+ assert cam_file.is_file()
154
+ cam = torch.load(cam_file, weights_only=True)
155
+ c2w = process_meganerf_cam(cam)
156
+ all_cams.append({
157
+ 'fname': im,
158
+ 'c2w': c2w.tolist()
159
+ })
160
+
161
+ write_cams(sn, all_cams)
162
+
163
+
164
+ def urban_scene():
165
+ from string import Template
166
+
167
+ scenes = '''
168
+ urbn_Campus
169
+ urbn_Residence
170
+ urbn_Sci-Art
171
+ '''
172
+ scenes = break_scenes(scenes)
173
+ for sn in scenes:
174
+ _sn = strip_sn_prefix(sn).lower()
175
+ lns = load_csv(
176
+ f"/your_path/colmap_results/data/urbanscene3d_meganerf/{_sn}-pixsfm/mappings.txt"
177
+ )
178
+ cam_dir_template = Template(
179
+ "/your_path/colmap_results/data/urbanscene3d_meganerf/${sn}-pixsfm/${split}/metadata"
180
+ )
181
+
182
+ im_2_camfn = {e[0]: e[1] for e in lns}
183
+ all_cams = []
184
+ keys = list(sorted(im_2_camfn.keys()))
185
+ for k in tqdm(keys):
186
+ # default assumes it's under train/
187
+ camfn = Path(cam_dir_template.substitute(sn=_sn, split="train")) / im_2_camfn[k]
188
+ if not camfn.is_file():
189
+ camfn = Path(cam_dir_template.substitute(sn=_sn, split="val")) / im_2_camfn[k]
190
+ assert camfn.is_file()
191
+
192
+ cam = torch.load(camfn, weights_only=True)
193
+ c2w = process_meganerf_cam(cam)
194
+ all_cams.append({
195
+ 'fname': k,
196
+ 'c2w': c2w.tolist()
197
+ })
198
+
199
+ write_cams(sn, all_cams)
200
+
201
+
202
+ def nerf_osr():
203
+ scenes = """
204
+ nosr_europa
205
+ nosr_lk2
206
+ nosr_lwp
207
+ nosr_rathaus
208
+ nosr_schloss
209
+ nosr_st
210
+ nosr_stjacob
211
+ nosr_stjohann
212
+ """
213
+ scenes = break_scenes(scenes)
214
+
215
+ for sn in scenes:
216
+ img_fnames = list_scene_fnames(sn)
217
+ raw = load_json(
218
+ f"/your_path/colmap_results/data/nerfosr_original/{strip_sn_prefix(sn)}/final/kai_cameras.json"
219
+ )
220
+ all_cams = []
221
+ for im in img_fnames:
222
+ cam = raw[im]
223
+ w2c = torch.tensor(cam['W2C'], dtype=torch.float64).reshape(4, 4)
224
+ c2w = invert_trans(w2c)
225
+ all_cams.append({
226
+ 'fname': im,
227
+ 'c2w': c2w.tolist()
228
+ })
229
+
230
+ write_cams(sn, all_cams)
231
+
232
+
233
+ def drone_deploy():
234
+ # ruin1 has missing images. ignore that scene
235
+ scenes = """
236
+ dploy_house1
237
+ dploy_house2
238
+ dploy_house3
239
+ dploy_house4
240
+ dploy_pipes1
241
+ dploy_ruins1
242
+ dploy_ruins2
243
+ dploy_ruins3
244
+ dploy_tower1
245
+ dploy_tower2
246
+ """
247
+ scenes = break_scenes(scenes)
248
+ for sn in scenes:
249
+ img_fnames = list_scene_fnames(sn)
250
+ raw = load_json(
251
+ f"/your_path/colmap_results/data/dronedeploy/{strip_sn_prefix(sn)}/cameras.json"
252
+ )
253
+ # keys: 'frames', 'fl_x', 'fl_y', 'k1', 'k2', 'p1', 'p2', 'k3', 'k4', 'k5', 'k6', 'cx', 'cy', 'w', 'h',
254
+ # 'camera_angle_x', 'camera_angle_y', 'aabb_scale'
255
+ frames = raw['frames']
256
+ frames = list(sorted(frames, key=lambda x: x['file_path']))
257
+
258
+ # print(f"{sn}, {len(img_fnames)} vs {len(frames)}")
259
+ _fnames = [
260
+ Path(e['file_path']).name
261
+ for e in frames
262
+ ]
263
+
264
+ has_missing_img = False
265
+ for e in _fnames:
266
+ if e not in img_fnames:
267
+ has_missing_img = True
268
+ # print(f"warn! img for {e} missing")
269
+
270
+ if has_missing_img:
271
+ # ruin1 has missing images. ignore that scene
272
+ continue
273
+
274
+ # some imgs don't have gt cam
275
+ # assert img_fnames == _fnames
276
+
277
+ all_cams = []
278
+ for fr in frames:
279
+ c2w = torch.tensor(fr['transform_matrix'])
280
+ x, y, z, t = torch.unbind(c2w, dim=1)
281
+ c2w = torch.stack([x, -y, -z, t], dim=-1) # opengl -> opencv
282
+ all_cams.append({
283
+ 'fname': Path(fr['file_path']).name,
284
+ 'c2w': c2w.tolist()
285
+ })
286
+
287
+ write_cams(sn, all_cams)
288
+
289
+
290
+ def mipnerf360():
291
+ scenes = """
292
+ m360_flowers
293
+ m360_room
294
+ m360_counter
295
+ m360_stump
296
+ m360_kitchen
297
+ m360_garden
298
+ m360_bicycle
299
+ m360_bonsai
300
+ m360_treehill
301
+ """
302
+ scenes = break_scenes(scenes)
303
+ for sn in scenes:
304
+ path = f"/your_path/nerfbln_dset/mipnerf360/{strip_sn_prefix(sn)}/sparse/0"
305
+ print(sn, end=',')
306
+ print(path)
307
+
308
+
309
+ def eyeful():
310
+ scenes = """
311
+ eft_apartment
312
+ eft_kitchen
313
+ """
314
+
315
+ # def make_filter_f(sensor_prefix):
316
+ # return lambda fr: fr['cameraId'].split('/')[0] != sensor_prefix
317
+
318
+ scenes = break_scenes(scenes)
319
+ for sn in scenes:
320
+ frames = load_json(
321
+ Path(f"/your_path/colmap_results/data/eyefultower/{strip_sn_prefix(sn)}/cameras.json")
322
+ )['KRT']
323
+ frames = sorted(frames, key=lambda x: x['cameraId'])
324
+
325
+ # # filter low overlap cameras
326
+ # prefix_to_discard = {
327
+ # 'eft_apartment': '31',
328
+ # 'eft_kitchen': '28'
329
+ # }[sn]
330
+ # n_before = len(frames)
331
+ # frames = list(filter(make_filter_f(prefix_to_discard), frames))
332
+ # n_after = len(frames)
333
+ # print(f"{n_before} vs {n_after}")
334
+
335
+ all_cams = []
336
+ for fr in tqdm(frames):
337
+ w2c = torch.tensor(fr['T']).T # note the transpose. col_major -> row major
338
+ c2w = invert_trans(w2c)
339
+ all_cams.append({
340
+ 'fname': f"{fr['cameraId']}.jpg",
341
+ 'c2w': c2w.tolist()
342
+ })
343
+
344
+ write_cams(sn, all_cams)
345
+
346
+ # I renamed the gt jsons that discarded low overlap cams as
347
+ # eft_apartment_remove_31.json
348
+ # eft_kitchen_remove_28.json
349
+ # they are created on 25.03.10 14:54
350
+ # the other gt files are made from 25.02.23 - 23.02.26
351
+
352
+
353
+ def tnt():
354
+ scenes = '''
355
+ tnt_advn_Auditorium
356
+ tnt_advn_Ballroom
357
+ tnt_advn_Courtroom
358
+ tnt_advn_Museum
359
+ tnt_advn_Palace
360
+ tnt_advn_Temple
361
+ tnt_intrmdt_Family
362
+ tnt_intrmdt_Francis
363
+ tnt_intrmdt_Horse
364
+ tnt_intrmdt_Lighthouse
365
+ tnt_intrmdt_M60
366
+ tnt_intrmdt_Panther
367
+ tnt_intrmdt_Playground
368
+ tnt_intrmdt_Train
369
+ tnt_trng_Barn
370
+ tnt_trng_Caterpillar
371
+ tnt_trng_Church
372
+ tnt_trng_Courthouse
373
+ tnt_trng_Ignatius
374
+ tnt_trng_Meetingroom
375
+ tnt_trng_Truck
376
+ '''
377
+ scenes = break_scenes(scenes)
378
+ for sn in scenes:
379
+ _sn = sn.split('_')[-1].lower()
380
+ gt_cam_path = f"/your_path/nerfbln_dset/tnt/{_sn}/sparse" # no 0/
381
+ print(sn, end=',')
382
+ print(gt_cam_path)
383
+
384
+
385
+ def eth3d_dslr():
386
+ scenes = '''
387
+ eth3d_dslr_botanical_garden
388
+ eth3d_dslr_boulders
389
+ eth3d_dslr_bridge
390
+ eth3d_dslr_courtyard
391
+ eth3d_dslr_delivery_area
392
+ eth3d_dslr_door
393
+ eth3d_dslr_electro
394
+ eth3d_dslr_exhibition_hall
395
+ eth3d_dslr_facade
396
+ eth3d_dslr_kicker
397
+ eth3d_dslr_lecture_room
398
+ eth3d_dslr_living_room
399
+ eth3d_dslr_lounge
400
+ eth3d_dslr_meadow
401
+ eth3d_dslr_observatory
402
+ eth3d_dslr_office
403
+ eth3d_dslr_old_computer
404
+ eth3d_dslr_pipes
405
+ eth3d_dslr_playground
406
+ eth3d_dslr_relief
407
+ eth3d_dslr_relief_2
408
+ eth3d_dslr_statue
409
+ eth3d_dslr_terrace
410
+ eth3d_dslr_terrace_2
411
+ eth3d_dslr_terrains
412
+ '''
413
+ scenes = break_scenes(scenes)
414
+
415
+ # # used to edit db_mapping.csv
416
+ # for sn in scenes:
417
+ # db_path = f"/your_path/sfm_workspace/runs_db/d_{sn}/database.db"
418
+ # assert Path(db_path).is_file()
419
+ # print(sn, end=',')
420
+ # print(db_path)
421
+ # return
422
+
423
+ for sn in scenes:
424
+ _sn = sn[len('eth3d_dslr_'):]
425
+ gt_cam_path = f"/your_path/colmap_results/data/eth3d_dslr/{_sn}/dslr_calibration_undistorted"
426
+ assert Path(gt_cam_path).is_dir()
427
+ print(sn, end=',')
428
+ print(gt_cam_path)
429
+
430
+
431
+ def main():
432
+ # hike()
433
+ # mill19()
434
+ # nerf_osr()
435
+ # mipnerf360()
436
+ # eyeful()
437
+ # tnt()
438
+ # urban_scene()
439
+ # drone_deploy()
440
+ # eth3d_dslr()
441
+ pass
442
+
443
+
444
+ if __name__ == "__main__":
445
+ main()