File size: 7,214 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Per training frame: how far each pixel is, and which pixels are sky.

    python depth.py DATA [--build BUILD] [--model depth-anything/Depth-Anything-V2-Small-hf]

A single-image depth model knows what matching between frames cannot: the shape of a wall or a floor without
texture, and that a sky is infinitely far (it has nothing to match, and splats trained on it fill it with dark
smoke near the camera). What the model does not know is size and distance; the triangulated points know
those. Per image the model's output m (larger = nearer, 0 = infinitely far) is fitted to the points the image
sees as 1/depth = a*m + b, robustly.

With --build the floor is looked for a third time, in these depths. Walking speed has three measurements:
tracked ground points (rough), the floor among the triangulated points (fine, but it needs texture: heavily
compressed footage of a wooden floor left it the desk tops and a speed of 2.9 for 1.3), and the floor in
these depths (a tenth to a third out on some scenes). The fine one stands unless the two rough ones agree with
each other and not with it; BUILD/controller.json gets the result and all three.

Writes DATA/depth/NAME.npy (half size, the reconstruction's units, 0 where unknown or sky; only for images
with enough points) and DATA/sky/NAME.png (white = sky) for the frames that show any. Runs on CUDA, on Apple's
GPU or on the CPU. Needs torch, transformers, numpy, Pillow."""
import argparse, json
from pathlib import Path

import numpy as np
import torch
from PIL import Image, ImageFilter
from transformers import pipeline

parser = argparse.ArgumentParser(); parser.add_argument("data", type=Path)
parser.add_argument("--model", default="depth-anything/Depth-Anything-V2-Small-hf"); parser.add_argument("--build", type=Path, default=None)
args = parser.parse_args()
meta = json.loads((args.data / "poses.json").read_text()); W, H, focal = int(meta["width"]), int(meta["height"]), float(meta["focal"])
pts = np.load(args.data / "points.npz"); points = pts["points"].astype(np.float64)
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
model = pipeline("depth-estimation", model=args.model, device=device)
shown = np.asarray(Image.open(args.data / "mask.png").convert("L").resize((W // 2, H // 2))) > 127 if (args.data / "mask.png").is_file() else True
for folder in ("depth", "sky"):
    (args.data / folder).mkdir(exist_ok=True)
written, skies, misfit, heights = 0, 0, [], []
centres = np.array([frame["centre"] for frame in meta["poses"]])
grid_v, grid_u = np.mgrid[4:H // 2:8, 4:W // 2:8]                                # a pixel in eight of the half-size depth
for i, frame in enumerate(meta["poses"]):
    stem = Path(frame["name"]).stem
    m = model(Image.open(args.data / "images" / frame["name"]).convert("RGB"))["predicted_depth"]
    m = torch.nn.functional.interpolate(m.reshape(1, 1, *m.shape[-2:]).float(), (H // 2, W // 2), mode="bilinear")[0, 0].cpu().numpy().astype(np.float64)
    sky = (m < 0.02 * np.percentile(m, 99)) & shown
    sky = np.asarray(Image.fromarray((sky * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(3))) > 0     # not up to the very edge of things
    if sky.mean() >= 0.005:
        Image.fromarray((sky * 255).astype(np.uint8)).resize((W, H), Image.NEAREST).save(args.data / "sky" / (stem + ".png")); skies += 1
    else:
        sky[:] = False
    R = np.array(frame["rotation"]).T; cam = (points[pts["seen_point"][pts["seen_image"] == i]] - np.array(frame["centre"])) @ R.T
    u, v, z = cam[:, 0] / cam[:, 2] * focal + W / 2, cam[:, 1] / cam[:, 2] * focal + H / 2, cam[:, 2]
    ok = (z > 0.05) & (u >= 0) & (u < W - 1) & (v >= 0) & (v < H - 1)
    if ok.sum() < 30:
        continue
    seen, wanted = m[(v[ok] / 2).astype(int), (u[ok] / 2).astype(int)], 1 / z[ok]
    weight = np.ones(len(seen))
    for _ in range(8):                                   # robust line fit: points on the wrong side of an edge lose their say
        A = np.column_stack([seen, np.ones(len(seen))]) * weight[:, None]
        a, b = np.linalg.lstsq(A, wanted * weight, rcond=None)[0]
        left = np.abs(a * seen + b - wanted); weight = 1 / np.maximum(1.0, left / (2 * (np.median(left) + 1e-9)))
    if a <= 0:
        continue
    inverse = a * m + b
    np.save(args.data / "depth" / (stem + ".npy"), np.where((inverse > 1e-3) & ~sky, 1 / np.maximum(inverse, 1e-3), 0).astype(np.float16))
    written += 1; misfit.append(float(np.median(left / wanted)))
    if i % 3 == 0:                                       # where these depths put things, for the floor
        z = np.where((inverse > 1e-3) & ~sky, 1 / np.maximum(inverse, 1e-3), 0)[grid_v, grid_u].ravel(); ok = z > 0
        cam = np.column_stack([(grid_u.ravel() * 2 - W / 2) / focal * z, (grid_v.ravel() * 2 - H / 2) / focal * z, z])[ok]
        world = np.array(frame["centre"]) + cam @ np.array(frame["rotation"]).T
        near = np.min(np.linalg.norm(world[:, None, [0, 2]] - centres[None, ::5, [0, 2]], axis=2), axis=1)
        heights.append(np.column_stack([world[:, 1], near]))
if skies < 0.2 * len(meta["poses"]):                     # a dark window in a few frames is not a sky: all or nothing
    for marked in (args.data / "sky").glob("*.png"):
        marked.unlink()
    skies = 0
if args.build and heights:
    c = json.loads((args.build / "controller.json").read_text()); eye = c["eye_m"]
    h = np.concatenate(heights); high = (h[h[:, 1] < 1.5 * eye, 0] - (np.median(centres[:, 1]) - eye)) / eye      # in eye heights above where the floor should be
    edges = np.arange(-3.01, 0.9, 0.02); counts = np.convolve(np.histogram(high, edges)[0], [1, 2, 3, 2, 1], "same")
    high = high[high < 0.9]                               # what lies below the eye
    for k in range(1, len(counts) - 1):                  # from below: the first height where a sixteenth of that gathers
        gathered = np.abs(high - (edges[k] + 0.01)) < 0.06
        if counts[k] >= counts[k - 1] and counts[k] >= counts[k + 1] and gathered.mean() >= 0.06:
            floor = float(np.median(high[gathered]))
            ways = {**c.get("walk_from", {}), "depths": round(c["walk_m_s"] / (1 - floor), 3)}
            # The floor among the points is the fine instrument; it is overruled only when the two rough ones
            # agree with each other and not with it.
            points, tracking = ways.get("points", c["walk_m_s"]), ways.get("tracking")
            off = lambda a, b: abs(a / b - 1) > 0.25
            chosen = ways["depths"] if tracking and off(points, ways["depths"]) and off(points, tracking) and not off(ways["depths"], tracking) else points
            for key in ("sprint_m_s", "walk_m_s"):
                if key in c:
                    c[key] = round(c[key] * chosen / ways.get("points", c["walk_m_s"]), 3)
            c["walk_from"] = ways
            (args.build / "controller.json").write_text(json.dumps(c, indent=1) + "\n")
            print(f"walking speed by {ways}: {c['walk_m_s']} m/s")
            break
print(f"{written} of {len(meta['poses'])} images got a depth (median misfit to the triangulated points {np.median(misfit) if misfit else 0:.1%}); "
      f"{skies} show sky")