File size: 3,802 Bytes
b7e49b8 | 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 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Render the card's demo image: the shipped sample next to its depth as served (inverse depth, colour-mapped, sky
black), with the focal length and the depth range in the caption strip.
# from a running server (the container under test)
python code/scripts/make_demo.py --url http://127.0.0.1:20000 --out media/demo_sample.png
# from a saved /predict response made with "include_inverse_depth": true
python code/scripts/make_demo.py --response resp.json --out media/demo_sample.png
Needs numpy and Pillow (not the package itself).
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
CODE = Path(__file__).resolve().parents[1]
SAMPLE_DIR = CODE / "tt_depthpro2" / "samples" / "kropa_street"
def turbo(x: np.ndarray) -> np.ndarray:
"""A smooth blue -> green -> yellow -> red colour map of values in [0, 1] (polynomial fit of Google's Turbo,
Apache-2.0), uint8 RGB."""
x = np.clip(x, 0.0, 1.0)[..., None]
r = 0.13572138 + x * (4.61539260 + x * (-42.66032258 + x * (132.13108234 + x * (-152.94239396 + x * 59.28637943))))
g = 0.09140261 + x * (2.19418839 + x * (4.84296658 + x * (-14.18503333 + x * (4.27729857 + x * 2.82956604))))
b = 0.10667330 + x * (12.64194608 + x * (-60.58204836 + x * (110.36276771 + x * (-89.90310912 + x * 27.34824973))))
return (np.clip(np.concatenate([r, g, b], -1), 0, 1) * 255).astype(np.uint8)
def render(image: Image.Image, inv: np.ndarray, resp: dict) -> Image.Image:
inv = inv.astype(np.float32)
sky = ~(inv > 0)
lo, hi = np.percentile(inv[~sky], [2, 98]) if (~sky).any() else (0.0, 1.0)
rgb = turbo((inv - lo) / max(hi - lo, 1e-12))
rgb[sky] = 0
w, h = image.size
canvas = Image.new("RGB", (2 * w, h + 28), (255, 255, 255))
canvas.paste(image.convert("RGB"), (0, 0))
canvas.paste(Image.fromarray(rgb).resize((w, h), Image.Resampling.BILINEAR), (w, 0))
st = resp.get("stats_m") or {}
text = (f"Depth Pro 2 {resp.get('size')} on a Tenstorrent p150: inverse depth (near = red, sky = black); "
f"f_px {resp.get('focallength_px', 0):.0f} ({resp.get('focal_source')}), depth median "
f"{st.get('median', 0):.1f} m, 5-95 % {st.get('p05', 0):.1f}-{st.get('p95', 0):.1f} m")
ImageDraw.Draw(canvas).text((6, h + 8), text, fill=(0, 0, 0))
return canvas
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
src = ap.add_mutually_exclusive_group(required=True)
src.add_argument("--url")
src.add_argument("--response", type=Path)
ap.add_argument("--out", type=Path, required=True)
a = ap.parse_args()
meta = json.loads((SAMPLE_DIR / "sample.json").read_text())
img_path = SAMPLE_DIR / meta["file"]
if a.url:
sys.path.insert(0, str(CODE / "tt_depthpro2" / "server"))
import client # noqa: E402 (stdlib client of this package)
code, resp = client.post_json(a.url, "/predict", client.sample_request(include_inverse_depth=True))
if code != 200:
raise SystemExit(f"/predict HTTP {code}: {str(resp)[:300]}")
else:
resp = json.loads(a.response.read_text())
if not isinstance(resp.get("inverse_depth"), dict) or "data" not in resp["inverse_depth"]:
raise SystemExit("the response has no inverse_depth array (request it with include_inverse_depth: true)")
inv = np.load(io.BytesIO(base64.b64decode(resp["inverse_depth"]["data"])))
a.out.parent.mkdir(parents=True, exist_ok=True)
render(Image.open(img_path), inv, resp).save(a.out)
print(f"wrote {a.out}")
return 0
if __name__ == "__main__":
sys.exit(main())
|