File size: 4,458 Bytes
cdfb882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Run one of the Depth Pro 2 L ONNX graphs on a photo.

    python example.py photo.jpg --model onnx/model_int8.onnx --out depth.png

The image is resized so the long side is at most ``--max-side`` and both sides are made
multiples of 32 (the model's only shape constraint). ``f_px`` is taken from EXIF when
available, otherwise from ``--f-px``, otherwise from a 60-degree horizontal field of view.

Works with a local file or a Hugging Face repo id:

    python example.py photo.jpg --model Petrouil/DepthPro2-L-ONNX:onnx/model_int8.onnx
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np
import onnxruntime as ort
from PIL import Image


def exif_focal_px(image: Image.Image) -> float | None:
    """Horizontal focal length in pixels from the 35 mm-equivalent EXIF tag, if present."""
    try:
        exif = image.getexif()
        focal = exif.get(37386)  # FocalLength
        focal35 = exif.get(41989)  # FocalLengthIn35mmFilm
        if focal and focal35:
            return float(focal35) / 36.0 * image.width
    except Exception:  # noqa: BLE001 - EXIF is best effort
        pass
    return None


def resize_to_multiple(image: Image.Image, max_side: int) -> tuple[Image.Image, float]:
    """Resize preserving aspect, then crop to a multiple of 32. Returns (image, scale)."""
    scale = min(1.0, max_side / max(image.size))
    width = max(32, int(round(image.width * scale / 32)) * 32)
    height = max(32, int(round(image.height * scale / 32)) * 32)
    resized = image.convert("RGB").resize((width, height), Image.Resampling.LANCZOS)
    return resized, width / image.width


def colorize(depth: np.ndarray, path: Path) -> None:
    """Simple turbo-like colour map on the 2nd-98th percentile, sky left white."""
    finite = np.isfinite(depth) & (depth > 0)
    if not finite.any():
        raise SystemExit("the model returned no finite depth")
    lo, hi = np.percentile(depth[finite], [2, 98])
    normalised = np.clip((depth - lo) / max(hi - lo, 1e-6), 0.0, 1.0)
    red = np.clip(1.5 - np.abs(4 * normalised - 3), 0, 1)
    green = np.clip(1.5 - np.abs(4 * normalised - 2), 0, 1)
    blue = np.clip(1.5 - np.abs(4 * normalised - 1), 0, 1)
    rgb = np.stack([red, green, blue], axis=-1)
    rgb[~finite] = 1.0
    Image.fromarray((rgb * 255).astype(np.uint8)).save(path)


def resolve_model(spec: str) -> str:
    """Accept a local path or ``repo_id:path``; download the latter."""
    if Path(spec).exists():
        return spec
    if ":" in spec:
        from huggingface_hub import hf_hub_download

        repo, filename = spec.split(":", 1)
        return hf_hub_download(repo, filename)
    raise SystemExit(f"model not found: {spec} (use a path or repo_id:file)")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("image", type=Path)
    parser.add_argument("--model", default="onnx/model_int8.onnx")
    parser.add_argument("--out", type=Path, default=Path("depth.png"))
    parser.add_argument("--f-px", type=float, default=None,
                        help="horizontal focal length in pixels of the original image")
    parser.add_argument("--max-side", type=int, default=1088)
    parser.add_argument("--provider", default="CPUExecutionProvider")
    args = parser.parse_args(argv)

    image = Image.open(args.image)
    focal = args.f_px or exif_focal_px(image)
    resized, scale = resize_to_multiple(image, args.max_side)
    if focal is None:
        focal = 0.8660254 * resized.width
        print(f"no EXIF focal length and no --f-px: assuming 60 deg HFOV, f_px={focal:.1f}")
    else:
        focal *= scale

    pixels = np.asarray(resized, dtype=np.float32) / 255.0
    pixels = pixels.transpose(2, 0, 1)[None]
    session = ort.InferenceSession(resolve_model(args.model),
                                   providers=[args.provider, "CPUExecutionProvider"])
    inverse, depth = session.run(None, {"pixel_values": pixels,
                                        "f_px": np.array([focal], np.float32)})
    depth = depth[0]
    colorize(depth, args.out)
    finite = depth[np.isfinite(depth)]
    print(f"{resized.width}x{resized.height}, f_px={focal:.1f}, "
          f"depth {finite.min():.2f}-{finite.max():.2f} m, median {np.median(finite):.2f} m")
    print(f"wrote {args.out}")
    return 0


if __name__ == "__main__":
    sys.exit(main())