File size: 2,386 Bytes
0b94c68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from argparse import ArgumentParser, Namespace
from pathlib import Path
from multiprocessing import Pool
import shutil
import glob
from tqdm import tqdm
from loggez import loggez_logger as logger
import numpy as np

def w2c(x: np.ndarray, cm: np.ndarray) -> np.ndarray:
    x1 = (x - 0.5) * 2 # [0:1] -> [-1: 1]
    x2 = x1 @ np.linalg.inv(cm) # [-1: 1] -> [-1: 1]
    return x2.clip(-1, 1)

def load(path: Path) -> np.ndarray:
    return np.load(path, allow_pickle=True)["arr_0"]

def do_one(args: tuple[Path, Path, Path]):
    in_path, cm_path, out_path = args
    in_np, cm_np = load(in_path), load(cm_path)
    out_np = w2c(in_np.astype(np.float32), cm_np).astype(in_np.dtype)
    np.savez_compressed(out_path, out_np)

def get_args() -> Namespace:
    parser = ArgumentParser()
    parser.add_argument("in_dir", type=Path)
    parser.add_argument("camera_parameters_dir", type=Path)
    parser.add_argument("--out_dir", "-o", type=Path, required=True)
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--n_workers", type=int, default=0)
    args = parser.parse_args()
    assert not args.out_dir.exists() or args.overwrite, f"'{args.out_dir}' exists. Use --overwrite"

    return args

def main(args: Namespace):
    logger.info(f"- In dir: '{args.in_dir}'")
    logger.info(f"- Camera Parameters dir: '{args.camera_parameters_dir}'")
    logger.info(f"- Out dir: '{args.camera_parameters_dir}'")
    in_paths = list(map(Path, glob.glob(f"{args.in_dir}/**/*.npz", recursive=True)))
    out_paths = [args.out_dir / in_path.name for in_path in in_paths]
    assert len(in_paths) > 0, (args.in_dir, in_paths)
    logger.info(f"npz files found: {len(in_paths)}")
    shutil.rmtree(args.out_dir, ignore_errors=True)
    Path(args.out_dir).mkdir()

    cm_paths = []
    for path in in_paths:
        path_split = path.stem.split("_")
        scene, scene_ix = "_".join(path_split[0:-1]), path_split[-1]
        cm_path = Path(args.camera_parameters_dir) / scene / f"cameraRotationMatrices/{scene_ix:0>6}.npz"
        assert cm_path.exists(), (path, cm_path)
        cm_paths.append(cm_path)
    logger.info("Found all camera matrices paths")

    map_fn = map if args.n_workers == 0 else Pool(args.n_workers).imap
    list(map_fn(do_one, tqdm(zip(in_paths, cm_paths, out_paths), total=len(in_paths))))

if __name__ == "__main__":
    main(get_args())