fastmap_sfm / convert_gt.py
whc's picture
Upload ./convert_gt.py with huggingface_hub
b97e541 verified
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()