CaveWorld3D / project /scripts /apply_field_perspective.py
xiaojie06's picture
Archive CaveWorld3D project files 路 5
1d15e3f verified
Raw History Blame Contribute Delete
9.53 kB
"""Select a perspective refiner on development views, then apply it to geometry-aligned single-photo panoramas."""
import argparse
import hashlib
import json
from pathlib import Path
import cv2
import numpy as np
from PIL import Image
from scipy.ndimage import distance_transform_edt
import torch
from measured_dataset import inputs
from register_cave_panorama import (
build_atlas,
directions,
orient,
ray_grid,
registration,
sample_panorama,
)
from score_field_camera import scores
from train_field_panorama import attach_field_adapter, load_field_weights
from train_field_perspective import (
case,
conditioning,
photo,
pipeline,
project_known,
sample,
)
from train_measured_panorama import pack, record
def render_patch(
pipe, src, guide, initial, caption, strength, seed, steps, condition=None
):
initial = Image.fromarray(initial)
z, shape = pack(pipe, initial, *initial.size)
row = dict(condition or conditioning(pipe, src, guide, caption), shape=shape)
return sample(pipe, row, seed, steps, initial=z, strength=strength)
def blend(base, pred, mode):
if mode == "full":
return pred
a, b = base.astype("f4"), pred.astype("f4")
# Retain coarse site layout and lamp positions, while replacing local texture.
d = b - a
low = cv2.GaussianBlur(d, (0, 0), 5.0)
return np.rint(a + 0.85 * (d - low) + 0.22 * low).clip(0, 255).astype("uint8")
def calibration(a, pipe):
data, caps = inputs(a.data, "grounded.json")
rows = [
r
for r in data["development"]
if (a.panels / r["name"] / "panorama.png").is_file()
]
if len({r["source"] for r in rows}) < 2:
raise ValueError("Two development sources are required")
variants = {"prior": {}}
details = {}
for idx, r in enumerate(rows):
src, guide, gt, known, mask = case(r, a.size, 0)
small = Image.fromarray(src)
small.thumbnail((740, 740))
small = np.asarray(small)
pano = photo(a.panels / r["name"] / "panorama.png")
cv2.setRNGSeed(8128)
alignment = registration(small, pano)
sh, sw = src.shape[:2]
t = photo(r["real_target"])
th, tw = t.shape[:2]
tan = np.tan(np.radians(r["estimated_dfov_deg"] / 2))
hf = np.degrees(2 * np.arctan(sw / np.hypot(sw, sh) * tan))
tex, _ = build_atlas(small, pano, alignment, hf, 2048)
vf = np.degrees(2 * np.arctan(min(tw, th) / np.hypot(tw, th) * tan))
rays = (
ray_grid(a.size, a.size, vf)
@ np.array(r["target_to_source_rotation"], "f4").T
)
base = sample_panorama(tex, rays)
cond = conditioning(pipe, src, guide, caps[r["condition"]])
panels = [gt, base]
variants["prior"][r["source"]] = scores(base, gt, mask)
for strength in (0.38, 0.68):
pred = render_patch(
pipe,
src,
guide,
base,
caps[r["condition"]],
strength,
143 + idx,
a.steps,
cond,
)
for mode in ("full", "detail"):
name = f"{strength:.2f}_{mode}"
v = blend(base, pred, mode)
variants.setdefault(name, {})[r["source"]] = scores(v, gt, mask)
panels.append(v)
Image.fromarray(np.hstack(panels)).resize((180 * len(panels), 180)).save(
a.out / (r["source"] + ".jpg"), quality=94
)
details[r["source"]] = dict(
kept=int(mask.sum()), registration=alignment["method"]
)
def cost(s):
return float(
s["mae"]
+ 0.09 * (1 - s["ssim"])
+ 0.04 * min(abs(np.log(max(0.01, s["gradient_ratio"]))), 2)
+ 0.06 * abs(s["luma_bias"])
)
avg = {
k: float(np.mean([cost(s) for s in v.values()])) for k, v in variants.items()
}
choice = min((k for k in avg if k != "prior"), key=avg.get)
record(
a.out / "settings.json",
dict(
selected_trained=choice,
best_with_identity=min(avg, key=avg.get),
scores=variants,
objective=avg,
criterion="MAE + .09*(1-SSIM) + .04*capped_abs_log_gradient_ratio + .06*abs_luminance_bias",
details=details,
seed=143,
size=a.size,
steps=a.steps,
),
)
def tiles(a, pipe):
src = photo(a.photo)
prior = np.array(Image.open(a.texture / "atlas/atlas.jpg").convert("RGB"))
h, w = prior.shape[:2]
mask = (
np.array(
Image.open(a.base / "geometry/observed.png").resize(
(w, h), Image.Resampling.BILINEAR
)
)
> 0
)
guard = (np.minimum(distance_transform_edt(~mask) / max(3, w / 180), 1)).astype(
"f4"
)
rule = json.loads(a.settings.read_text())["selected_trained"]
strength, mode = rule.split("_")
strength = float(strength)
grid = ray_grid(a.size, a.size, 82)
meta = []
preds = []
for i, (yaw, pitch) in enumerate(
(y, p) for y in (-100, -50, 0, 50, 100) for p in (-26, 26)
):
rotation = orient(yaw, pitch).astype("f4")
rays = grid @ rotation.T
guide, known = project_known(src, rays, a.hfov)
anchor = sample_panorama(prior, rays)
pred = render_patch(
pipe, src, guide, anchor, a.caption, strength, a.seed + 1009 * i, a.steps
)
pred = blend(anchor, pred, mode)
preds.append((rotation, pred))
meta.append(
dict(
yaw=yaw,
pitch=pitch,
source_fraction=float(known.mean()),
tile_seed=a.seed + 1009 * i,
)
)
out = prior.copy()
counts = [0, 0]
for y in range(0, h, 64):
yy, xx = np.mgrid[y : min(y + 64, h), :w].astype("f4")
rays = directions((xx + 0.5) / w, (yy + 0.5) / h)
sumrgb = np.zeros_like(rays)
sw = np.zeros(rays.shape[:2], "f4")
for rotation, pred in preds:
view = rays @ rotation
z = view[..., 2]
xy = (
view[..., :2] / np.maximum(z[..., None], 0.001) / np.tan(np.radians(41))
)
edge = np.maximum(abs(xy[..., 0]), abs(xy[..., 1]))
alpha = (
np.clip((1 - edge) / 0.18, 0, 1) ** 2 * (z > 0) * np.maximum(z, 0) ** 8
)
pos = ((xy + 1) * a.size - 1) / 2
rgb = cv2.remap(
pred,
pos[..., 0].astype("f4"),
pos[..., 1].astype("f4"),
cv2.INTER_LINEAR,
)
sumrgb += rgb * alpha[..., None]
sw += alpha
influence = np.minimum(sw / 0.14, 1) * guard[y : y + len(yy)]
colors = sumrgb / np.maximum(sw[..., None], 1e-6)
out[y : y + len(yy)] = (
np.rint(
prior[y : y + len(yy)] * (1 - influence[..., None])
+ colors * influence[..., None]
)
.clip(0, 255)
.astype("uint8")
)
counts[0] += int((influence > 0.05).sum())
counts[1] += int(influence.size)
target = a.out / "atlas"
target.mkdir(exist_ok=True)
Image.fromarray(out).save(target / "atlas.jpg", quality=96, subsampling=0)
record(
a.out / "request.json",
dict(
photo_sha256=hashlib.sha256(a.photo.read_bytes()).hexdigest(),
adapter_sha256=hashlib.sha256(a.adapter.read_bytes()).hexdigest()
if a.adapter
else None,
initial_texture_sha256=hashlib.sha256(
(a.texture / "atlas/atlas.jpg").read_bytes()
).hexdigest(),
camera_hfov=a.hfov,
seed=a.seed,
steps=a.steps,
size=a.size,
settings=rule,
caption=a.caption,
surface_fraction=counts[0] / counts[1],
tiles=meta,
),
)
def main():
p = argparse.ArgumentParser(description=__doc__)
sub = p.add_subparsers(dest="command", required=True)
c = sub.add_parser("calibrate")
t = sub.add_parser("apply")
for group in (c, t):
group.add_argument("--models", type=Path, required=True)
group.add_argument("--out", type=Path, required=True)
group.add_argument("--adapter", type=Path)
group.add_argument("--size", type=int, default=640)
group.add_argument("--steps", type=int, default=18)
for key in ("data", "panels"):
c.add_argument("--" + key, type=Path, required=True)
for key in ("photo", "base", "texture", "settings"):
t.add_argument("--" + key, type=Path, required=True)
t.add_argument("--hfov", type=float, required=True)
t.add_argument("--seed", type=int, default=143)
t.add_argument(
"--caption",
default="Documentary photograph in low light at an underground construction site.",
)
a = p.parse_args()
a.out.mkdir(parents=True, exist_ok=True)
cv2.setNumThreads(1)
pipe = pipeline(a.models)
attach_field_adapter(pipe.transformer)
if a.adapter:
load_field_weights(pipe.transformer, a.adapter)
pipe.transformer.eval()
with torch.inference_mode():
if a.command == "calibrate":
calibration(a, pipe)
else:
tiles(a, pipe)
if __name__ == "__main__":
main()