"""Write an interactive 4D viewer of the predictions of demo.py as one self-contained HTML file.
python visualize.py outputs/demo/predictions.npz [-o viewer.html]
Open the file in a browser; it needs neither a server nor Python. The scene is in the camera frame
of the anchor frame. Clips too long to embed are written as a folder (viewer.html + data/*.js).
"""
import argparse
import base64
import colorsys
import gzip
import json
import os
import warnings
import cv2
import numpy as np
VIEWER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "viewer")
VENDOR = ["three.min.js", "OrbitControls.js", "LineSegmentsGeometry.js", "LineMaterial.js", "LineSegments2.js"]
RADIUS_CLIP = 2.5 # positions are quantised to [-2.5, 2.5] scene radii, as on the project page
MAX_INLINE = 25e6 # bytes of data embedded in a single file
def trajectory_colors(n: int) -> np.ndarray:
"""One color per trajectory, as in the paper's figures: a full-saturation hue sweep from red to violet."""
t = np.linspace(0.0, 1.0, n) if n > 1 else np.array([0.5])
return (np.array([colorsys.hsv_to_rgb(0.78 * v, 1.0, 1.0) for v in t]).reshape(-1, 3) * 255).astype(np.uint8)
def b64gz(arr: np.ndarray) -> str:
"""Byte-shuffle (all low bytes, then all high bytes) + gzip + base64, decoded by the viewer."""
raw = np.ascontiguousarray(arr)
if raw.dtype.itemsize > 1:
raw = raw.view(np.uint8).reshape(-1, raw.dtype.itemsize).T
return base64.b64encode(gzip.compress(np.ascontiguousarray(raw).tobytes(), 6, mtime=0)).decode()
def edge_keep(points: np.ndarray, tol: float = 0.05, grow: int = 5) -> np.ndarray:
"""(T, H, W) mask of the pixels that are not flying pixels, i.e. where the log-distance to the
camera changes by less than `tol` per pixel, dilated by `grow` pixels as on the project page."""
keep = np.ones(points.shape[:3], bool)
for t, p in enumerate(points):
lr = np.log(np.linalg.norm(np.nan_to_num(p), axis=-1) + 1e-6).astype(np.float32)
g = np.hypot(cv2.Sobel(lr, cv2.CV_32F, 1, 0, ksize=3), cv2.Sobel(lr, cv2.CV_32F, 0, 1, ksize=3)) / 8
keep[t] = cv2.dilate((~(g <= tol)).astype(np.uint8), np.ones((grow, grow), np.uint8)) == 0
return keep
def conf_rank(conf: np.ndarray) -> np.ndarray:
"""Per-pixel confidence percentile in [0, 100] (uint8), so the viewer can threshold by percentile."""
rank = np.empty(conf.size, np.float64)
rank[np.argsort(conf, axis=None, kind="stable")] = np.arange(conf.size)
return (100 * rank / max(conf.size - 1, 1)).reshape(conf.shape).astype(np.uint8)
def jpeg(img: np.ndarray, width: int = 360) -> str:
h, w = img.shape[:2]
img = cv2.resize((img * 255).astype(np.uint8), (width, round(h * width / w)), interpolation=cv2.INTER_AREA)
ok, buf = cv2.imencode(".jpg", cv2.cvtColor(img, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 82])
return "data:image/jpeg;base64," + base64.b64encode(buf.tobytes()).decode()
def coherent(disp, mask, max_dev, r=2):
"""(h, w) mask of the tracks in `mask` whose displacements (T, h, w, 3) stay within `max_dev` of
their own travel from the median displacement of the masked tracks in a (2r+1)^2 neighborhood.
Rejects tracks that start on the boundary of a moving object and partly follow its background."""
d = np.where(mask[None, ..., None], disp, np.nan)
d = np.pad(d, ((0, 0), (r, r), (r, r), (0, 0)), constant_values=np.nan)
win = np.lib.stride_tricks.sliding_window_view(d, (2 * r + 1, 2 * r + 1), axis=(1, 2)) # (T, h, w, 3, k, k)
ys, xs = np.nonzero(mask) # only the masked tracks are tested
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # all-NaN windows of tracks with NaN displacements
ref = np.nanmedian(win[:, ys, xs].reshape(len(win), len(ys), 3, -1), axis=-1)
dev = np.linalg.norm(disp[:, ys, xs] - ref, axis=-1).max(axis=0)
travel = np.linalg.norm(disp[:, ys, xs], axis=-1).max(axis=0)
keep = np.zeros_like(mask)
keep[ys, xs] = dev <= max_dev * travel
return keep
def select_tracks(tracks, conf, anchor, grid, max_tracks, min_motion, max_dev, min_group=10, min_conf=0.05):
"""Pixels on a `grid` of confident anchor pixels, sampled to `max_tracks` in image order, either among
the moving ones (tracks travelling more than `min_motion` of their distance from the anchor camera and
moving coherently with their neighbors) or among all."""
H, W = conf.shape[1:]
ys, xs = np.mgrid[grid // 2:H:grid, grid // 2:W:grid]
# A low cut: small moving objects in front of a large textured background (rollerblade) can have most
# of their pixels in the lowest fifth of the confidence.
keep = conf[anchor, ys, xs] >= np.quantile(conf[anchor], min_conf)
xyz = tracks[:, ys, xs]
# Relative to each point's own distance from the anchor camera: depth errors grow with distance, and
# a far background that drifts by a few percent must not count as moving.
motion = np.linalg.norm(xyz - xyz[anchor], axis=-1).max(axis=0)
moving = keep & (motion > min_motion * np.linalg.norm(xyz[anchor], axis=-1))
moving = coherent(xyz - xyz[anchor], moving, max_dev)
padded = np.pad(moving, 1) # drop isolated pixels (depth edges): keep those with >= 5 of 8 moving neighbors
neighbors = sum(padded[1 + dy:padded.shape[0] - 1 + dy, 1 + dx:padded.shape[1] - 1 + dx]
for dy in (-1, 0, 1) for dx in (-1, 0, 1) if dy or dx)
moving = moving & (neighbors >= 5)
# and drop the small groups left over, e.g. from a drifting patch of sky
n, labels, stats, _ = cv2.connectedComponentsWithStats(moving.astype(np.uint8), connectivity=8)
moving = np.isin(labels, np.flatnonzero(stats[:, cv2.CC_STAT_AREA] >= min_group)) & moving
moving = moving[keep]
ys, xs = ys[keep], xs[keep]
print(f"{moving.sum()} of {len(ys)} candidate tracks are moving")
sets = {}
for name, sel in (("moving", np.flatnonzero(moving)), ("all", np.arange(len(ys)))):
sel = sel[np.linspace(0, len(sel) - 1, min(len(sel), max_tracks)).astype(int)] if len(sel) else sel
sets[name] = ys[sel], xs[sel] # image order, so neighboring queries get neighboring hues
return sets
def export(pred, args):
"""The viewer's data as a list of payloads: the scene description, the dense tracks and the
per-frame point maps in chunks of frames."""
images, points, tracks, conf = pred["images"], pred["points"], pred["tracks"], pred["conf"]
T, H, W = conf.shape
a, s = args.anchor, args.stride
# Normalise to the scene's centre and radius and flip OpenCV (y down) to three.js (y up) axes.
ref = points[a][(conf[a] >= np.quantile(conf[a], 0.2)) & np.isfinite(points[a]).all(-1)]
center = np.median(ref, axis=0)
radius = float(np.percentile(np.linalg.norm(ref - center, axis=-1), 90))
to_view = lambda p: (p - center) / radius * np.array([1.0, -1.0, -1.0])
inside = lambda v: np.isfinite(v).all(-1) & (np.linalg.norm(v, axis=-1) < RADIUS_CLIP)
quant = lambda v: np.round(np.clip(np.nan_to_num(v) / RADIUS_CLIP, -1, 1) * 32767).astype(np.int16)
edge = edge_keep(points)[:, ::s, ::s].reshape(T, -1)
rank = np.stack([conf_rank(c[::s, ::s]) for c in conf]).reshape(T, -1)
rgb = (images[:, ::s, ::s] * 255).astype(np.uint8).reshape(T, -1, 3)
# Reconstruction: every frame's point map at the anchor's viewpoint.
recon = []
for t0 in range(0, T, args.chunk):
pos, col, cnf, counts = [], [], [], []
for t in range(t0, min(t0 + args.chunk, T)):
v = to_view(points[t, ::s, ::s].reshape(-1, 3))
keep = inside(v) & edge[t]
pos.append(quant(v[keep]))
col.append(rgb[t][keep])
cnf.append(rank[t][keep])
counts.append(int(keep.sum()))
recon.append(dict(kind="recon", first=t0, counts=counts, pos=b64gz(np.concatenate(pos)),
col=b64gz(np.concatenate(col)), conf=b64gz(np.concatenate(cnf))))
# Tracking: the anchor's pixels carried to every frame, as frame-to-frame deltas that are zero
# wherever the scene is static (int16 wraps exactly).
v = to_view(tracks[:, ::s, ::s].reshape(T, -1, 3))
keep = inside(v[a]) & edge[a] & np.isfinite(v).all(-1).all(0)
q = quant(v[:, keep])
delta = np.diff(q, axis=0, prepend=np.zeros_like(q[:1]))
track = dict(kind="track", n=int(keep.sum()), pos=b64gz(delta.transpose(0, 2, 1)), # (T, 3, N)
col=b64gz(rgb[a][keep]), conf=b64gz(rank[a][keep]))
# Trajectories of the displayed tracks, for the moving pixels only and for all of them.
sets = select_tracks(tracks, conf, a, args.track_grid, args.max_tracks, args.min_motion,
args.max_dev)
trails = {name: dict(uv=np.round(np.stack([xs / W, ys / H], 1), 4).tolist(),
colors=trajectory_colors(len(ys)).tolist(), pos=b64gz(quant(to_view(tracks[:, ys, xs]))))
for name, (ys, xs) in sets.items()}
# Camera frustums (apex and four image corners).
c2w, focal = pred["cam2world"].astype(np.float64), pred["focal"]
depth = 0.075 * radius
corners = np.array([[0, 0, 0], [-W / 2, -H / 2, 1], [W / 2, -H / 2, 1], [W / 2, H / 2, 1], [-W / 2, H / 2, 1]])
frustums = [to_view((corners * [depth / f, depth / f, depth]) @ c[:3, :3].T + c[:3, 3])
for c, f in zip(c2w, focal)]
# Initial view: behind, beside and above the anchor camera, looking at the moving points if any,
# otherwise at the median depth along the optical axis.
ys, xs = sets["moving"]
if len(ys):
target = to_view(np.nanmedian(tracks[:, ys, xs].reshape(-1, 3), axis=0))
else:
target = to_view(c2w[a, :3, 3] + c2w[a, :3, 2] * np.median(np.linalg.norm(ref, axis=-1)))
offset = to_view(c2w[a, :3, 3]) - target
offset *= max(1.6, 0.8 / np.linalg.norm(offset))
az, el = np.radians(-25), np.radians(-15)
offset = np.array([[np.cos(az), 0, np.sin(az)], [0, 1, 0], [-np.sin(az), 0, np.cos(az)]]) @ offset
offset = np.array([[1, 0, 0], [0, np.cos(el), -np.sin(el)], [0, np.sin(el), np.cos(el)]]) @ offset
# Point size: three.js draws a point of size p about 0.32 p wide (36 deg field of view), so 4x the
# spacing of the subsampled pixels closes the gaps between them.
pitch = s * np.median(np.linalg.norm(ref, axis=-1)) / np.median(focal) / radius
meta = dict(kind="meta", name=args.name, T=T, w=W, h=H, anchor=a, pointSize=round(float(4 * pitch), 5),
cam=dict(pos=np.round(target + offset, 4).tolist(), target=np.round(target, 4).tolist()),
frustums=np.round(np.stack(frustums), 4).tolist(), trails=trails,
frames=[jpeg(im) for im in images])
return [meta, track] + recon
def viewer_page(name=""):
"""The viewer's page (with a {{SCRIPTS}} placeholder for the data) and its inlined scripts."""
read = lambda path: open(os.path.join(VIEWER, path)).read()
scripts = "".join(f"\n" for f in VENDOR)
scripts += f"\n"
return read("template.html").replace("{{TITLE}}", name), scripts
def write_empty_viewer(out, message="") -> str:
"""Writes the viewer without data: a blank canvas showing the message and inert controls (the web demo
shows it until the first result). Returns out."""
page, scripts = viewer_page()
data = f"\n"
with open(out, "w") as f:
f.write(page.replace("{{SCRIPTS}}", data + scripts))
return out
def write_viewer(pred, out, name="", anchor=0, stride=2, track_grid=4, max_tracks=400, min_motion=0.3,
max_dev=0.25, chunk=16, max_inline=MAX_INLINE) -> str:
"""Writes the viewer of the predictions to out; returns the path of the page (a folder's
viewer.html if the data is larger than max_inline bytes). The options are those of the command line."""
args = argparse.Namespace(name=name, anchor=anchor, stride=stride, track_grid=track_grid, max_tracks=max_tracks,
min_motion=min_motion, max_dev=max_dev, chunk=chunk)
payloads = [f"F4RT.add({json.dumps(p, separators=(',', ':'))});\n" for p in export(pred, args)]
page, scripts = viewer_page(name)
size = sum(map(len, payloads))
if size <= max_inline:
data = "".join(f"\n" for p in payloads)
with open(out, "w") as f:
f.write(page.replace("{{SCRIPTS}}", data + scripts))
print(f"Wrote {out} ({os.path.getsize(out) / 1e6:.1f} MB); open it in a browser")
return out
# Too large to embed: a folder whose page loads the data by \n'
page_path = os.path.join(folder, "viewer.html")
with open(page_path, "w") as f:
f.write(page.replace("{{SCRIPTS}}", tags + scripts))
print(f"Data too large to embed ({size / 1e6:.0f} MB): wrote the folder {folder}/; open {page_path}")
return page_path
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("predictions", help="predictions.npz written by demo.py")
parser.add_argument("-o", "--output", help="output HTML file (default: viewer.html next to the predictions)")
parser.add_argument("--stride", type=int, default=2, help="pixel subsampling of the point clouds")
parser.add_argument("--track_grid", type=int, default=4, help="pixel spacing of the candidate tracks")
parser.add_argument("--max_tracks", type=int, default=400, help="number of displayed tracks")
parser.add_argument("--min_motion", type=float, default=0.3,
help="a track is moving if it travels more than this fraction of its distance from the "
"anchor camera")
parser.add_argument("--max_dev", type=float, default=0.25,
help="drop moving tracks that deviate from their neighbors by more than this fraction "
"of their travel (boundaries of moving objects)")
parser.add_argument("--anchor", type=int, default=0, help="the anchor frame used in demo.py")
parser.add_argument("--chunk", type=int, default=16, help="frames per point-map payload")
args = parser.parse_args()
out = args.output or os.path.join(os.path.dirname(os.path.abspath(args.predictions)), "viewer.html")
name = os.path.basename(os.path.dirname(os.path.abspath(args.predictions)))
opts = {k: v for k, v in vars(args).items() if k not in ("predictions", "output")}
write_viewer(np.load(args.predictions), out, name, **opts)
if __name__ == "__main__":
main()