File size: 7,031 Bytes
c97431f
 
 
 
 
 
 
 
 
b267904
c97431f
 
 
 
 
b267904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c97431f
 
 
 
 
b267904
 
 
 
 
 
 
 
 
 
 
 
c97431f
 
 
 
b267904
c97431f
b267904
 
 
 
 
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b267904
 
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b267904
 
 
 
 
 
 
 
 
c97431f
 
b267904
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b267904
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Depth estimation and 3D geometry inference."""

import cv2
import numpy as np
import torch
from PIL import Image

import state
from config.models import DEPTH_MODEL_NAME, GEOMETRY_MODEL, MOGE_MODEL_NAME
from config.runtime import ENABLE_DEPTH_ESTIMATION, ENABLE_MOGE_GEOMETRY, ENABLE_ONNX_INFERENCE
from models.loader import _load_depth_model, _load_moge_model
from enums import GeometryProvider
from utils import to_numpy


def _estimate_depth_onnx(img: Image.Image, width: int, height: int) -> np.ndarray | None:
    """Try running depth estimation via ONNX Runtime. Returns None if unavailable."""
    if not ENABLE_ONNX_INFERENCE:
        return None
    from models.onnx_loader import load_depth_onnx_session
    session = load_depth_onnx_session()
    if session is None:
        return None

    if state.depth_processor is None:
        _load_depth_model()

    inputs = state.depth_processor(images=img, return_tensors="np")
    input_feed = {k: v for k, v in inputs.items() if k in [inp.name for inp in session.get_inputs()]}
    outputs = session.run(None, input_feed)

    # outputs[0] is predicted_depth — interpolate to target size
    depth_tensor = torch.from_numpy(outputs[0])
    if depth_tensor.ndim == 2:
        depth_tensor = depth_tensor.unsqueeze(0).unsqueeze(0)
    elif depth_tensor.ndim == 3:
        depth_tensor = depth_tensor.unsqueeze(1)
    depth = torch.nn.functional.interpolate(
        depth_tensor, size=(height, width), mode="bicubic", align_corners=False,
    ).squeeze().numpy()
    return depth


def estimate_depth(img: Image.Image, width: int, height: int):
    if not ENABLE_DEPTH_ESTIMATION:
        return None

    try:
        # Try ONNX first
        depth = _estimate_depth_onnx(img, width, height)
        if depth is not None:
            depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3)
            if "metric" in DEPTH_MODEL_NAME.lower():
                return depth
            depth_min, depth_max = float(np.min(depth)), float(np.max(depth))
            if depth_max - depth_min < 1e-6:
                return None
            return (depth - depth_min) / (depth_max - depth_min)

        # Fallback to PyTorch
        if not _load_depth_model():
            return None

        inputs = state.depth_processor(images=img, return_tensors="pt").to(state.device)
        use_autocast = state.device.type == "cuda"
        with torch.no_grad():
            if use_autocast:
                with torch.autocast(device_type="cuda", dtype=torch.float16):
                    outputs = state.depth_model(**inputs)
            else:
                outputs = state.depth_model(**inputs)
            depth = torch.nn.functional.interpolate(
                outputs.predicted_depth.unsqueeze(1),
                size=(height, width),
                mode="bicubic",
                align_corners=False,
            ).squeeze().cpu().numpy()
        depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3)
        if "metric" in DEPTH_MODEL_NAME.lower():
            return depth
        depth_min, depth_max = float(np.min(depth)), float(np.max(depth))
        if depth_max - depth_min < 1e-6:
            return None
        return (depth - depth_min) / (depth_max - depth_min)
    except Exception as exc:
        print(f"Depth estimation skipped ({exc}).", flush=True)
        return None


def estimate_moge_geometry(img_np: np.ndarray, target_h: int | None = None, target_w: int | None = None):
    """Run MoGe geometry on img_np, upscale outputs to target_h x target_w if provided."""
    if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda":
        return None

    try:
        if not _load_moge_model():
            return None

        image_tensor = torch.from_numpy(img_np.astype(np.float32) / 255.0).permute(2, 0, 1).to(state.device)
        with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.float16):
            output = state.moge_model.infer(image_tensor)

        points = to_numpy(output.get("points"))
        depth = to_numpy(output.get("depth"))
        normals = to_numpy(output.get("normal"))
        valid_mask = to_numpy(output.get("mask"))
        intrinsics = to_numpy(output.get("intrinsics"))
        if points is None or points.ndim != 3 or points.shape[2] != 3:
            raise RuntimeError("MoGe did not return an HxWx3 point map.")
        out_h = target_h if target_h is not None else img_np.shape[0]
        out_w = target_w if target_w is not None else img_np.shape[1]
        if points.shape[:2] != (out_h, out_w):
            points = cv2.resize(points, (out_w, out_h), interpolation=cv2.INTER_LINEAR)
        if depth is not None and depth.shape[:2] != (out_h, out_w):
            depth = cv2.resize(depth, (out_w, out_h), interpolation=cv2.INTER_LINEAR)
        if normals is not None and normals.shape[:2] != (out_h, out_w):
            normals = cv2.resize(normals, (out_w, out_h), interpolation=cv2.INTER_LINEAR)
        if valid_mask is not None and valid_mask.shape[:2] != (out_h, out_w):
            valid_mask = cv2.resize(
                valid_mask.astype(np.uint8),
                (out_w, out_h),
                interpolation=cv2.INTER_NEAREST,
            ).astype(bool)
        if depth is None:
            depth = points[:, :, 2]
        if valid_mask is None:
            valid_mask = np.isfinite(depth) & (depth > 0)

        print(
            "[FLOOR_3D_POINTS] generated raw MoGe HxWx3 point map "
            f"shape={points.shape} validPixels={int(valid_mask.sum())} provider=moge-2",
            flush=True,
        )
        return {
            "provider": GeometryProvider.MOGE_2,
            "points": points.astype(np.float32),
            "depth": depth.astype(np.float32),
            "normals": normals.astype(np.float32) if normals is not None else None,
            "validMask": valid_mask.astype(bool),
            "intrinsics": intrinsics.astype(np.float32) if intrinsics is not None else None,
        }
    except Exception as exc:
        print(f"MoGe geometry estimation failed ({exc}); falling back to depth.", flush=True)
        if state.device.type == "cuda":
            torch.cuda.empty_cache()
        return None


def estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int):
    geometry = estimate_moge_geometry(img_np, target_h=height, target_w=width)
    if geometry is not None:
        return geometry

    depth = estimate_depth(img, width, height)
    depth_provider = GeometryProvider.HOMOGRAPHY
    if depth is not None:
        depth_provider = (
            GeometryProvider.DEPTH_ANYTHING_METRIC
            if "metric" in DEPTH_MODEL_NAME.lower()
            else GeometryProvider.RELATIVE_DEPTH
        )
    return {
        "provider": depth_provider,
        "points": None,
        "depth": depth,
        "normals": None,
        "validMask": np.isfinite(depth) & (depth > 0) if depth is not None else None,
        "intrinsics": None,
    }