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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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
from pathlib import Path
import os
from utils import load_json, write_json, dir_of_this_file, load_csv
import torch
# import numpy as np
from tqdm import tqdm


sn_2_imgdir = {
    e[0]: Path("/your_path/colmap_results/data/") / e[1]
    for e in load_csv(dir_of_this_file(__file__) / "seed_db.csv")
}


SAVE_ROOT = dir_of_this_file(__file__) / "gt_cams"


def write_cams(sn, all_cams):
    output_fn = SAVE_ROOT / f"{sn}.json"
    write_json(output_fn, all_cams)
    print(sn, end=',')
    print(output_fn)


def list_scene_fnames(sn):
    return list(sorted(os.listdir(sn_2_imgdir[sn])))


def break_scenes(raw):
    raw = raw.strip().split('\n')
    return [e.strip() for e in raw]


def strip_sn_prefix(sn_name):
    parts = sn_name.split("_")[1:]
    return "_".join(parts)


def invert_trans(trans_T):
    assert trans_T.shape == (4, 4)
    R = trans_T[0:3, 0:3]
    t = trans_T[0:3, 3:4]
    new_T = torch.eye(4, dtype=trans_T.dtype, device=trans_T.device)
    new_T[0:3, 0:3] = R.T
    new_T[0:3, 3:4] = -R.T @ t
    return new_T


def hike():
    ''' # these are problematic scenes
    hike_garden2: cams without their images!
    '''

    scenes = '''
    hike_forest1
    hike_forest2
    hike_forest3
    hike_garden3
    hike_indoor
    hike_playground
    hike_university1
    hike_university2
    hike_university3
    hike_university4
    '''
    scenes = break_scenes(scenes)
    root = Path("/your_path/colmap_results/data/statichike")

    # for sn in scenes:
    #     gt_path = f"/your_path/colmap_results/data/statichike/{strip_sn_prefix(sn)}/sparse"
    #     gt_path = Path(gt_path)
    #     assert not (gt_path / "1").is_dir()
    #     print(sn, end=',')
    #     print(str(gt_path / "0"))
    # return

    for sn in scenes:
        img_fnames = list_scene_fnames(sn)

        raw = load_json(
            root / strip_sn_prefix(sn) / "transforms.json"
        )
        frames = list(sorted(raw['frames'], key=lambda x: x['file_path']))

        cam_dir = root / strip_sn_prefix(sn) / "sparse"
        assert not (cam_dir / "1").is_dir()

        fr_fnames = [Path(fr['file_path']).name for fr in frames]

        c2ws_b = torch.tensor(
            [fr['transform_matrix'] for fr in frames],
            dtype=torch.float64, device="cuda"
        )
        # from opengl to opencv
        c2ws_b[:, :, 1] *= -1
        c2ws_b[:, :, 2] *= -1

        try:
            from metrics import load_colmap_db_cams, pose_stats_suite
            # from read_colmap_model import read_colmap_w2c
            # names, intrs, Rs, ts = read_colmap_w2c(cam_dir / "0")
            names, _, c2ws_a = load_colmap_db_cams(cam_dir / "0", ".bin", return_all=True)
            assert fr_fnames == names
            res = pose_stats_suite(c2ws_a, c2ws_b)
            assert res['ate'] < 1e-5
            assert res['auc_p'][0] > 99.99
            del names, c2ws_a, res
            '''
            the c2w in frames are globally shifted for some reason.
            check that after alignment, error is small.
            '''
        except FileNotFoundError as e:
            print(e)

        # some imgs are discarded in gt cams
        assert set(fr_fnames).issubset(set(img_fnames))
        # if len(fr_fnames) != len(img_fnames):
        #     print(f"{sn} img {len(img_fnames)} vs cam {len(fr_fnames)}")

        c2ws_b = c2ws_b.cpu().float().tolist()
        all_cams = []
        for i in range(len(frames)):
            all_cams.append({
                'fname': fr_fnames[i],
                'c2w': c2ws_b[i]
            })

        write_cams(sn, all_cams)


def process_meganerf_cam(cam):
    c2w = cam['c2w']  # [3, 4] opengl: x-right, y-up, z-back
    x, y, z, t = torch.unbind(c2w, dim=1)
    c2w = torch.stack([x, -y, -z, t], dim=-1)  # opengl -> opencv
    full_c2w = torch.eye(4)
    full_c2w[0:3] = c2w
    return full_c2w


def mill19():
    scenes = """
    mill19_building
    mill19_rubble
    """
    scenes = break_scenes(scenes)

    for sn in scenes:
        img_fnames = list_scene_fnames(sn)
        cam_dir = Path(f"/your_path/colmap_results/data/mill19/{strip_sn_prefix(sn)}-pixsfm/train/metadata")
        all_cams = []
        for im in tqdm(img_fnames):
            cam_file = cam_dir / Path(im).with_suffix(".pt")
            assert cam_file.is_file()
            cam = torch.load(cam_file, weights_only=True)
            c2w = process_meganerf_cam(cam)
            all_cams.append({
                'fname': im,
                'c2w': c2w.tolist()
            })

        write_cams(sn, all_cams)


def urban_scene():
    from string import Template

    scenes = '''
    urbn_Campus
    urbn_Residence
    urbn_Sci-Art
    '''
    scenes = break_scenes(scenes)
    for sn in scenes:
        _sn = strip_sn_prefix(sn).lower()
        lns = load_csv(
            f"/your_path/colmap_results/data/urbanscene3d_meganerf/{_sn}-pixsfm/mappings.txt"
        )
        cam_dir_template = Template(
            "/your_path/colmap_results/data/urbanscene3d_meganerf/${sn}-pixsfm/${split}/metadata"
        )

        im_2_camfn = {e[0]: e[1] for e in lns}
        all_cams = []
        keys = list(sorted(im_2_camfn.keys()))
        for k in tqdm(keys):
            # default assumes it's under train/
            camfn = Path(cam_dir_template.substitute(sn=_sn, split="train")) / im_2_camfn[k]
            if not camfn.is_file():
                camfn = Path(cam_dir_template.substitute(sn=_sn, split="val")) / im_2_camfn[k]
                assert camfn.is_file()

            cam = torch.load(camfn, weights_only=True)
            c2w = process_meganerf_cam(cam)
            all_cams.append({
                'fname': k,
                'c2w': c2w.tolist()
            })

        write_cams(sn, all_cams)


def nerf_osr():
    scenes = """
    nosr_europa
    nosr_lk2
    nosr_lwp
    nosr_rathaus
    nosr_schloss
    nosr_st
    nosr_stjacob
    nosr_stjohann
    """
    scenes = break_scenes(scenes)

    for sn in scenes:
        img_fnames = list_scene_fnames(sn)
        raw = load_json(
            f"/your_path/colmap_results/data/nerfosr_original/{strip_sn_prefix(sn)}/final/kai_cameras.json"
        )
        all_cams = []
        for im in img_fnames:
            cam = raw[im]
            w2c = torch.tensor(cam['W2C'], dtype=torch.float64).reshape(4, 4)
            c2w = invert_trans(w2c)
            all_cams.append({
                'fname': im,
                'c2w': c2w.tolist()
            })

        write_cams(sn, all_cams)


def drone_deploy():
    # ruin1 has missing images. ignore that scene
    scenes = """
    dploy_house1
    dploy_house2
    dploy_house3
    dploy_house4
    dploy_pipes1
    dploy_ruins1
    dploy_ruins2
    dploy_ruins3
    dploy_tower1
    dploy_tower2
    """
    scenes = break_scenes(scenes)
    for sn in scenes:
        img_fnames = list_scene_fnames(sn)
        raw = load_json(
            f"/your_path/colmap_results/data/dronedeploy/{strip_sn_prefix(sn)}/cameras.json"
        )
        # keys: 'frames', 'fl_x', 'fl_y', 'k1', 'k2', 'p1', 'p2', 'k3', 'k4', 'k5', 'k6', 'cx', 'cy', 'w', 'h',
        #       'camera_angle_x', 'camera_angle_y', 'aabb_scale'
        frames = raw['frames']
        frames = list(sorted(frames, key=lambda x: x['file_path']))

        # print(f"{sn}, {len(img_fnames)} vs {len(frames)}")
        _fnames = [
            Path(e['file_path']).name
            for e in frames
        ]

        has_missing_img = False
        for e in _fnames:
            if e not in img_fnames:
                has_missing_img = True
                # print(f"warn! img for {e} missing")

        if has_missing_img:
            # ruin1 has missing images. ignore that scene
            continue

        # some imgs don't have gt cam
        # assert img_fnames == _fnames

        all_cams = []
        for fr in frames:
            c2w = torch.tensor(fr['transform_matrix'])
            x, y, z, t = torch.unbind(c2w, dim=1)
            c2w = torch.stack([x, -y, -z, t], dim=-1)  # opengl -> opencv
            all_cams.append({
                'fname': Path(fr['file_path']).name,
                'c2w': c2w.tolist()
            })

        write_cams(sn, all_cams)


def mipnerf360():
    scenes = """
    m360_flowers
    m360_room
    m360_counter
    m360_stump
    m360_kitchen
    m360_garden
    m360_bicycle
    m360_bonsai
    m360_treehill
    """
    scenes = break_scenes(scenes)
    for sn in scenes:
        path = f"/your_path/nerfbln_dset/mipnerf360/{strip_sn_prefix(sn)}/sparse/0"
        print(sn, end=',')
        print(path)


def eyeful():
    scenes = """
    eft_apartment
    eft_kitchen
    """

    # def make_filter_f(sensor_prefix):
    #     return lambda fr: fr['cameraId'].split('/')[0] != sensor_prefix

    scenes = break_scenes(scenes)
    for sn in scenes:
        frames = load_json(
            Path(f"/your_path/colmap_results/data/eyefultower/{strip_sn_prefix(sn)}/cameras.json")
        )['KRT']
        frames = sorted(frames, key=lambda x: x['cameraId'])

        # # filter low overlap cameras
        # prefix_to_discard = {
        #     'eft_apartment': '31',
        #     'eft_kitchen': '28'
        # }[sn]
        # n_before = len(frames)
        # frames = list(filter(make_filter_f(prefix_to_discard), frames))
        # n_after = len(frames)
        # print(f"{n_before} vs {n_after}")

        all_cams = []
        for fr in tqdm(frames):
            w2c = torch.tensor(fr['T']).T  # note the transpose. col_major -> row major
            c2w = invert_trans(w2c)
            all_cams.append({
                'fname': f"{fr['cameraId']}.jpg",
                'c2w': c2w.tolist()
            })

        write_cams(sn, all_cams)

    # I renamed the gt jsons that discarded low overlap cams as
    #   eft_apartment_remove_31.json
    #   eft_kitchen_remove_28.json
    # they are created on 25.03.10 14:54
    # the other gt files are made from 25.02.23 - 23.02.26


def tnt():
    scenes = '''
    tnt_advn_Auditorium
    tnt_advn_Ballroom
    tnt_advn_Courtroom
    tnt_advn_Museum
    tnt_advn_Palace
    tnt_advn_Temple
    tnt_intrmdt_Family
    tnt_intrmdt_Francis
    tnt_intrmdt_Horse
    tnt_intrmdt_Lighthouse
    tnt_intrmdt_M60
    tnt_intrmdt_Panther
    tnt_intrmdt_Playground
    tnt_intrmdt_Train
    tnt_trng_Barn
    tnt_trng_Caterpillar
    tnt_trng_Church
    tnt_trng_Courthouse
    tnt_trng_Ignatius
    tnt_trng_Meetingroom
    tnt_trng_Truck
    '''
    scenes = break_scenes(scenes)
    for sn in scenes:
        _sn = sn.split('_')[-1].lower()
        gt_cam_path = f"/your_path/nerfbln_dset/tnt/{_sn}/sparse"  # no 0/
        print(sn, end=',')
        print(gt_cam_path)


def eth3d_dslr():
    scenes = '''
    eth3d_dslr_botanical_garden
    eth3d_dslr_boulders
    eth3d_dslr_bridge
    eth3d_dslr_courtyard
    eth3d_dslr_delivery_area
    eth3d_dslr_door
    eth3d_dslr_electro
    eth3d_dslr_exhibition_hall
    eth3d_dslr_facade
    eth3d_dslr_kicker
    eth3d_dslr_lecture_room
    eth3d_dslr_living_room
    eth3d_dslr_lounge
    eth3d_dslr_meadow
    eth3d_dslr_observatory
    eth3d_dslr_office
    eth3d_dslr_old_computer
    eth3d_dslr_pipes
    eth3d_dslr_playground
    eth3d_dslr_relief
    eth3d_dslr_relief_2
    eth3d_dslr_statue
    eth3d_dslr_terrace
    eth3d_dslr_terrace_2
    eth3d_dslr_terrains
    '''
    scenes = break_scenes(scenes)

    # # used to edit db_mapping.csv
    # for sn in scenes:
    #     db_path = f"/your_path/sfm_workspace/runs_db/d_{sn}/database.db"
    #     assert Path(db_path).is_file()
    #     print(sn, end=',')
    #     print(db_path)
    # return

    for sn in scenes:
        _sn = sn[len('eth3d_dslr_'):]
        gt_cam_path = f"/your_path/colmap_results/data/eth3d_dslr/{_sn}/dslr_calibration_undistorted"
        assert Path(gt_cam_path).is_dir()
        print(sn, end=',')
        print(gt_cam_path)


def main():
    # hike()
    # mill19()
    # nerf_osr()
    # mipnerf360()
    # eyeful()
    # tnt()
    # urban_scene()
    # drone_deploy()
    # eth3d_dslr()
    pass


if __name__ == "__main__":
    main()