File size: 6,849 Bytes
c1a4584
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""
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")