Download reconstruction/scripts/get_pointmap_dir.py from hk239/v2d: direct link, hf CLI and curl.
- Browser
- Download file 6.85 kB
-
https://huggingface.co/datasets/hk239/v2d/resolve/main/reconstruction/scripts/get_pointmap_dir.py
- Command line
-
hf download hf://datasets/hk239/v2d/reconstruction/scripts/get_pointmap_dir.py
-
curl -L -o get_pointmap_dir.py https://huggingface.co/datasets/hk239/v2d/resolve/main/reconstruction/scripts/get_pointmap_dir.py
6.85 kB
| """ | |
| Compute MoGe pointmaps (+ camera intrinsics) for one image or a whole directory. | |
| Uses the local checkpoint at checkpoints/moge when MOGE_CHECKPOINT is set | |
| (or the Fast-SAM3D pipeline.yaml depth_model as a fallback). | |
| Single image: | |
| python get_pointmap_dir.py --image /path/to/0028.png --output /path/to/0028_pointmap.npy | |
| Batch: | |
| python get_pointmap_dir.py --image_dir /path/to/all_frames | |
| """ | |
| import argparse | |
| import glob | |
| import os | |
| import sys | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| _RECON_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| _PROJECT_ROOT = os.path.dirname(_RECON_ROOT) | |
| def _default_moge_ckpt(): | |
| env = os.environ.get("MOGE_CHECKPOINT") | |
| if env: | |
| return env | |
| local = os.path.join(_PROJECT_ROOT, "checkpoints", "moge", "model.pt") | |
| return local if os.path.isfile(local) else None | |
| def _moge_version_from_checkpoint(ckpt_path: str) -> str: | |
| """Local model.pt can be v1 (encoder name str), v2 (encoder dict), or v3 (has refiner).""" | |
| blob = torch.load(ckpt_path, map_location="cpu", weights_only=True) | |
| if isinstance(blob.get("model_version"), str): | |
| return blob["model_version"] | |
| cfg = blob.get("model_config") or {} | |
| if "refiner" in cfg or cfg.get("refiner_depth_resolution") is not None: | |
| return "v3" | |
| enc = cfg.get("encoder") | |
| if isinstance(enc, dict): | |
| return "v2" | |
| return "v1" | |
| def load_model(): | |
| """Load MoGe from a local checkpoint, else Fast-SAM3D pipeline.yaml.""" | |
| ckpt = _default_moge_ckpt() | |
| if ckpt: | |
| from moge.model import import_model_class_by_version | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| version = _moge_version_from_checkpoint(ckpt) | |
| print(f"Loading MoGe {version} from {ckpt}") | |
| cls = import_model_class_by_version(version) | |
| model = cls.from_pretrained(ckpt).to(device).eval() | |
| return ("moge", model) | |
| SAM3D_REPO_ROOT = os.environ.get( | |
| "SAM3D_REPO_ROOT", os.path.join(_RECON_ROOT, "modules", "Fast-SAM3D") | |
| ) | |
| if SAM3D_REPO_ROOT not in sys.path: | |
| sys.path.insert(0, SAM3D_REPO_ROOT) | |
| from hydra.utils import instantiate | |
| from omegaconf import OmegaConf | |
| config_path = os.path.join(SAM3D_REPO_ROOT, "checkpoints", "hf", "pipeline.yaml") | |
| cfg = OmegaConf.load(config_path) | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| depth_model = instantiate(cfg.depth_model, device=device) | |
| return ("sam3d", depth_model) | |
| def _run_moge(model, rgb_chw: torch.Tensor): | |
| """Normalize MoGe / SAM3D depth wrappers to pointmaps + intrinsics.""" | |
| if hasattr(model, "infer"): | |
| out = model.infer(rgb_chw) | |
| else: | |
| out = model(rgb_chw) | |
| if isinstance(out, dict): | |
| points = out.get("pointmaps", out.get("points")) | |
| intrinsics = out.get("intrinsics") | |
| else: | |
| points, intrinsics = out, None | |
| if points is None: | |
| raise RuntimeError("MoGe output missing pointmaps/points") | |
| return points, intrinsics | |
| def run_pointmap(bundle, image_path: str, output_path: str, intrinsics_format: str = "npy"): | |
| kind, depth_model = bundle | |
| img = np.array(Image.open(image_path).convert("RGB")).astype(np.uint8) | |
| loaded_rgb = torch.from_numpy((img / 255.0).astype(np.float32)).permute(2, 0, 1).contiguous() | |
| dtype = torch.float16 if torch.cuda.is_available() else torch.float32 | |
| with torch.no_grad(): | |
| if torch.cuda.is_available(): | |
| with torch.autocast(device_type="cuda", dtype=dtype): | |
| points, intrinsics = _run_moge(depth_model, loaded_rgb) | |
| else: | |
| points, intrinsics = _run_moge(depth_model, loaded_rgb) | |
| pointmap_np = points.detach().cpu().numpy() if torch.is_tensor(points) else np.asarray(points) | |
| np.save(output_path, pointmap_np) | |
| print(f"Saved pointmap to: {output_path}") | |
| H, W = img.shape[:2] | |
| if intrinsics is None: | |
| print("No intrinsics in MoGe output; skipping") | |
| return | |
| intrinsics = intrinsics.detach().cpu().numpy().copy() if torch.is_tensor(intrinsics) else np.asarray(intrinsics).copy() | |
| # Some MoGe builds return normalized fx/fy; scale when values look like [0,1]. | |
| if np.nanmax(np.abs(intrinsics[:2, :2])) <= 2.0: | |
| intrinsics[0, 0] *= W | |
| intrinsics[1, 1] *= H | |
| intrinsics[0, 2] *= W | |
| intrinsics[1, 2] *= H | |
| if intrinsics_format == "txt": | |
| fx, fy = float(intrinsics[0, 0]), float(intrinsics[1, 1]) | |
| cx, cy = float(intrinsics[0, 2]), float(intrinsics[1, 2]) | |
| intrinsics_txt_path = output_path.replace("_pointmap.npy", "_intrinsics.txt") | |
| with open(intrinsics_txt_path, "w") as f: | |
| f.write(f"{fx}\n{fy}\n{cx}\n{cy}\n") | |
| print(f"Saved intrinsics to: {intrinsics_txt_path}") | |
| else: | |
| intrinsics_path = output_path.replace("_pointmap.npy", "_intrinsics.npy") | |
| np.save(intrinsics_path, intrinsics) | |
| print(f"Saved intrinsics to: {intrinsics_path}") | |
| def _list_images(image_dir: str): | |
| paths = [] | |
| for ext in ("*.png", "*.jpg", "*.jpeg"): | |
| paths.extend(glob.glob(os.path.join(image_dir, ext))) | |
| return sorted(paths) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--image", type=str, default=None) | |
| parser.add_argument("--image_dir", type=str, default=None) | |
| parser.add_argument("--output", type=str, default=None) | |
| parser.add_argument("--overwrite", action="store_true") | |
| args = parser.parse_args() | |
| if args.image_dir is not None: | |
| image_paths = _list_images(args.image_dir) | |
| if not image_paths: | |
| print(f"No images found in {args.image_dir}") | |
| sys.exit(1) | |
| print(f"Found {len(image_paths)} images in {args.image_dir}") | |
| bundle = load_model() | |
| for i, image_path in enumerate(image_paths): | |
| base, _ = os.path.splitext(image_path) | |
| output_path = f"{base}_pointmap.npy" | |
| if os.path.exists(output_path) and not args.overwrite: | |
| print(f"\n[{i+1}/{len(image_paths)}] skip {os.path.basename(output_path)}") | |
| continue | |
| print(f"\n[{i+1}/{len(image_paths)}] {os.path.basename(image_path)}") | |
| run_pointmap(bundle, image_path, output_path, intrinsics_format="npy") | |
| print(f"\nDone! Processed {len(image_paths)} images.") | |
| elif args.image is not None: | |
| if args.output is None: | |
| base, _ = os.path.splitext(args.image) | |
| args.output = f"{base}_pointmap.npy" | |
| if os.path.exists(args.output) and not args.overwrite: | |
| print(f"skip {args.output} (already exists)") | |
| else: | |
| bundle = load_model() | |
| run_pointmap(bundle, args.image, args.output, intrinsics_format="txt") | |
| else: | |
| parser.error("Must specify either --image or --image_dir") | |