File size: 4,347 Bytes
b08bfc4 | 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 | """Generate frozen, image-only conditioning predictions for source-disjoint field training."""
import argparse
from collections import Counter
import hashlib
from pathlib import Path
import random
import cv2
import numpy as np
import torch
from cave_lens_model import network, restore, read_rgb
from cave_surface_model import predictions
from evaluate_cave_lens import frame, paired_rows
from inventory_cave_outpaint import read, write
from train_cave_lens import aperture
def seed(key):
return int(hashlib.sha256(key.encode()).hexdigest()[:12], 16)
def roster(parent, lens, split):
idx = read(lens / "corpus/index.json")
cameras = [
dict(r, task="camera", uid="camera_" + r["case"])
for r in read(parent / "evidence/cases.json")
]
pairs = [
dict(r, task="registered", uid="pair_" + r["case"]) for r in paired_rows(lens)
]
frames = []
for n, r in enumerate(idx["frames"]):
frames.append(dict(r, task="aperture", uid="view_" + str(n)))
if r["source"].startswith("IMG_"):
frames.append(dict(r, task="aperture", uid="offset_" + str(n)))
rows = [
r for r in cameras + pairs + frames if split == "all61" or r["role"] == "train"
]
assert len({r["uid"] for r in rows}) == len(rows)
return rows
def observation(parent, lens, row, max_edge=576):
if row["task"] == "aperture":
t = read_rgb(lens / "corpus" / row["file"])
k = aperture(*t.shape[:2], random.Random(seed(row["uid"])))
g = t.copy()
v = ~k
else:
ref = frame(parent, lens, row)
g, k, t, v = (ref[s] for s in ("guide", "known", "truth", "mask"))
g = g.copy()
g[~k] = 0
h, w = k.shape
if max(h, w) > max_edge:
size = (
max(8, round(w * max_edge / max(h, w))),
max(8, round(h * max_edge / max(h, w))),
)
frac = cv2.resize(k.astype("f4"), size, interpolation=cv2.INTER_AREA)
g = (
np.rint(
cv2.resize(g.astype("f4"), size, interpolation=cv2.INTER_AREA)
/ np.maximum(frac[..., None], 1e-5)
)
.clip(0, 255)
.astype("u1")
)
k = frac > 0.99
g[~k] = 0
t = cv2.resize(t, size, interpolation=cv2.INTER_AREA)
v = cv2.resize(v.astype("f4"), size, interpolation=cv2.INTER_AREA) > 0.99
return g, k, t, v & ~k
def load_backbones(lens, split):
field = network(lens / "upstream/big-lama.pt")
base = network(lens / "upstream/big-lama.pt")
restore(field, lens / "weights" / split / "epoch-7.safetensors")
return field, base
def main(parent, lens, work, split):
cv2.setNumThreads(1)
torch.set_num_threads(2)
field, base = load_backbones(lens, split)
rows = roster(parent, lens, split)
dst = work / "cache" / split
dst.mkdir(exist_ok=True, parents=True)
usable = []
rejected = []
for i, row in enumerate(rows):
name = dst / (row["uid"] + ".npz")
if name.is_file():
usable.append(row)
continue
g, k, _, _ = observation(parent, lens, row)
if not k.any() or k.all():
rejected.append(
dict(
uid=row["uid"], source=row["source"], known_fraction=float(k.mean())
)
)
continue
p, b, c = predictions(field, base, g, k)
partial = name.with_suffix(".part.npz")
np.savez_compressed(partial, primary=p, alternate=b, official=c)
partial.replace(name)
usable.append(row)
if i % 120 == 0:
print("cache", split, i, len(rows), flush=True)
assert {r["source"] for r in rows} == {r["source"] for r in usable}
write(dst / "roster.json", usable)
write(
dst / "ready.json",
dict(
rows=len(usable),
sources=len({r["source"] for r in usable}),
tasks=Counter(r["task"] for r in usable),
scenes=Counter(r["scene"] for r in usable),
rejected=rejected,
),
)
if __name__ == "__main__":
arg = argparse.ArgumentParser(description=__doc__)
for key in ("parent", "lens", "work"):
arg.add_argument(key, type=Path)
arg.add_argument("split", choices=["heldout", "all61"])
main(**vars(arg.parse_args()))
|