|
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 |
|
x2 = x1 @ np.linalg.inv(cm) |
|
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()) |
|
|