File size: 8,451 Bytes
2340e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
181
182
183
184
"""Real pretrained feature inference. No coordinate claim is made by this module."""
from __future__ import annotations

import json
import math
import os
from functools import lru_cache
from pathlib import Path

import numpy as np
from PIL import Image, ImageOps
import torch
from torch import nn
import torch.nn.functional as F

ROOT = Path(__file__).resolve().parent
MODEL_DIR = Path(os.environ.get("GEO_MODEL_DIR", ROOT / "weights"))
torch.set_num_threads(max(1, min(8, int(os.environ.get("GEO_CPU_THREADS", "2")))))
MEAN = np.array([0.485, 0.456, 0.406], np.float32)[:, None, None]
STD = np.array([0.229, 0.224, 0.225], np.float32)[:, None, None]


def read_image(value):
    if value is None:
        raise ValueError("An input image is required.")
    image = value if isinstance(value, Image.Image) else Image.open(value)
    if image.width < 32 or image.height < 32 or image.width * image.height > 16_000_000:
        raise ValueError("Image dimensions must be >=32px and <=16 megapixels.")
    return ImageOps.exif_transpose(image).convert("RGB")


class SampleEncoder(nn.Module):
    def __init__(self):
        super().__init__()
        import timm
        self.model = timm.create_model(
            "convnext_base.fb_in22k_ft_in1k_384", pretrained=False, num_classes=0
        )
        self.logit_scale = nn.Parameter(torch.tensor(math.log(1 / 0.07)))

    def forward(self, image):
        return F.normalize(self.model(image), dim=-1)


@lru_cache(maxsize=2)
def sample_model(device="cpu"):
    from safetensors.torch import load_file
    model = SampleEncoder().eval()
    model.load_state_dict(load_file(str(MODEL_DIR / "sample4geo_cvusa.safetensors")), strict=True)
    return model.to(device)


class BEVEncoder(nn.Module):
    def __init__(self, model):
        super().__init__()
        self.model = model

    def forward(self, image, camera_tensor):
        from maploc.utils.wrappers import Camera
        # Upstream's `data.shape[-1] in {6, 8, 10}` assertion is not trace-safe:
        # TorchScript represents the dimension as a tensor whose hash differs.
        # Use its unchanged camera mathematics with a validated pinhole wrapper.
        class EncoderCamera(Camera):
            def __init__(self, data):
                if not torch.jit.is_tracing() and data.shape[-1] != 6:
                    raise ValueError("Expected pinhole camera tensor [..., 6]")
                self._data = data
        model = self.model
        features = model.image_encoder({"image": image})["feature_maps"][0]
        camera = EncoderCamera(camera_tensor).scale(1 / model.image_encoder.scales[0])
        scales = model.scale_classifier(features.moveaxis(1, -1))
        polar = model.projection_polar(features, scales, camera)
        bev, valid, _ = model.projection_bev(polar.float(), None, camera.float())
        output = model.bev_net({"input": bev})
        return output["output"], output["confidence"], valid


@lru_cache(maxsize=2)
def bev_model(device="cpu"):
    from maploc.models.orienternet import OrienterNet
    from safetensors.torch import load_file
    config = json.loads((ROOT / "orienternet_config.json").read_text())["model"]
    config["image_encoder"]["backbone"]["pretrained"] = False
    model = OrienterNet(config).eval()
    model.load_state_dict(load_file(str(MODEL_DIR / "orienternet_mgl.safetensors")), strict=True)
    return BEVEncoder(model).eval().to(device)


def prepare_bev(image, hfov=60.0, pitch=0.0, roll=0.0):
    from scipy.spatial.transform import Rotation
    from maploc.utils.wrappers import Camera
    values = list(map(float, (hfov, pitch, roll)))
    if not all(math.isfinite(x) for x in values):
        raise ValueError("Camera assumptions must be finite.")
    hfov, pitch, roll = values
    if not (20 <= hfov <= 150 and abs(pitch) <= 45 and abs(roll) <= 45):
        raise ValueError("HFOV must be 20..150; pitch/roll must be -45..45 degrees.")
    image = read_image(image)
    w, h = image.size
    scale = 512 / max(w, h)
    rw, rh = round(w * scale), round(h * scale)
    focal = w / (2 * math.tan(math.radians(hfov) / 2))
    camera = Camera(torch.tensor([w, h, focal, focal, (w - 1) / 2, (h - 1) / 2], dtype=torch.float32))
    camera = camera.scale((rw / w, rh / h))
    array = np.asarray(image.resize((rw, rh), Image.Resampling.BILINEAR), dtype=np.float32) / 255
    tensor = torch.from_numpy(array.copy()).permute(2, 0, 1)
    # Same ZX roll/pitch convention as upstream maploc/data/image.py.
    if pitch or roll:
        yy, xx = torch.meshgrid(torch.arange(rh), torch.arange(rw), indexing="ij")
        grid = torch.stack((xx, yy), -1).float()
        rays = torch.cat((camera.normalize(grid), torch.ones(rh, rw, 1)), dim=-1)
        rotation = torch.tensor(Rotation.from_euler("ZX", (roll, pitch), degrees=True).as_matrix(), dtype=torch.float32)
        rays = rays @ rotation.T
        pixels = camera.denormalize(rays[..., :2] / rays[..., 2:])
        grid_norm = (pixels + 0.5) / torch.tensor([rw, rh]) * 2 - 1
        tensor = F.grid_sample(tensor[None], grid_norm[None], align_corners=False)[0]
    tensor = F.pad(tensor, (0, 512 - rw, 0, 512 - rh))[None]
    camera = camera.crop((0, 0), (512, 512))
    return tensor.numpy(), camera._data[None].numpy(), {
        "input_size_wh": [w, h], "resized_wh": [rw, rh], "model_size_wh": [512, 512],
        "hfov_deg": hfov, "pitch_deg": pitch, "roll_deg": roll,
        "camera_calibrated": False,
        "camera_note": "User-supplied or default assumptions, NOT measured calibration; no lens distortion correction.",
    }


def prepare_embedding(image, view="ground"):
    if view not in {"ground", "satellite"}:
        raise ValueError("view must be ground or satellite")
    image = read_image(image)
    size = (768, 140) if view == "ground" else (384, 384)
    array = np.asarray(image.resize(size, Image.Resampling.BILINEAR), dtype=np.float32) / 255
    array = (array.transpose(2, 0, 1) - MEAN) / STD
    return np.ascontiguousarray(array[None]), {
        "view": view, "input_size_wh": list(image.size), "model_size_wh": list(size),
        "resize": "PIL bilinear, direct resize; ground panorama shape follows CVUSA evaluation",
        "distribution_warning": "CVUSA panorama-trained model; narrow-FOV, night photos and Chinese cities are unvalidated distribution shifts.",
    }


@lru_cache(maxsize=2)
def ort_session(model_name):
    import onnxruntime as ort
    options = ort.SessionOptions()
    options.intra_op_num_threads = torch.get_num_threads()
    options.inter_op_num_threads = 1
    if model_name == "orienternet_bev.onnx":
        # Preserve BN/conv arithmetic: fusion caused a near-zero feature to fail
        # the unchanged numerical gate. See the precision diagnosis receipt.
        options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
    return ort.InferenceSession(str(MODEL_DIR / model_name), options, providers=["CPUExecutionProvider"])


def infer_bev_cpu(image, camera):
    return ort_session("orienternet_bev.onnx").run(None, {"image": image, "camera": camera})


def infer_embedding_cpu(image):
    return ort_session("sample4geo_cvusa.onnx").run(None, {"image": image})[0]


def visualize_bev(features, confidence, valid):
    """An arbitrary feature-color image, NOT a semantic/satellite reconstruction."""
    feat = np.asarray(features)[0]
    conf = np.asarray(confidence)[0]
    mask = np.asarray(valid)[0].astype(bool)
    # Fixed feature channels, per-image contrast only for visualization.
    colors = feat[:3].transpose(1, 2, 0)
    if not np.isfinite(colors).all():
        raise ValueError("Non-finite BEV model output")
    lo = np.percentile(colors, 2, axis=(0, 1))
    hi = np.percentile(colors, 98, axis=(0, 1))
    colors = np.clip((colors - lo) / np.maximum(hi - lo, 1e-6), 0, 1)
    colors *= mask[..., None]
    left = Image.fromarray((colors * 255).astype(np.uint8)).resize((516, 256), Image.Resampling.NEAREST)
    right = Image.fromarray((np.clip(conf, 0, 1) * mask * 255).astype(np.uint8)).convert("RGB").resize((516, 256), Image.Resampling.NEAREST)
    panel = Image.new("RGB", (1032, 286), (20, 24, 30))
    panel.paste(left, (0, 30)); panel.paste(right, (516, 30))
    from PIL import ImageDraw
    draw = ImageDraw.Draw(panel)
    draw.text((8, 8), "BEV feature colors (not an aerial photo)", fill="white")
    draw.text((524, 8), "Model confidence (not location confidence)", fill="white")
    return panel