CaveWorld3D / project /scripts /build_field_surface.py
xiaojie06's picture
Archive CaveWorld3D project files 路 5
1d15e3f verified
Raw History Blame Contribute Delete
2.95 kB
"""Build a calibrated, high-resolution photo surface plus a depth-layered generated environment."""
import argparse
import json
from pathlib import Path
import cv2
import numpy as np
from PIL import Image, ImageOps
from build_wide_cave_scene import far_layer
from wide_cave_geometry import Surface, export_glb, grid_faces, panorama_surface
def source_surface(image, depth, hfov):
h, w = depth.shape
scale = 448 / max(w, h)
rows, cols = round(h * scale) + 1, round(w * scale) + 1
v, u = np.meshgrid(
np.linspace(0, 1, rows, dtype="f4"),
np.linspace(0, 1, cols, dtype="f4"),
indexing="ij",
)
z = cv2.remap(
depth,
np.clip(u * w - 0.5, 0, w - 1),
np.clip(v * h - 0.5, 0, h - 1),
cv2.INTER_LINEAR,
borderMode=cv2.BORDER_REPLICATE,
)
fx = w / (2 * np.tan(np.deg2rad(hfov / 2)))
xyz = (
np.stack(((u - 0.5) * w / fx * z, (v - 0.5) * h / fx * z, z), -1)
.reshape(-1, 3)
.astype("f4")
)
face = grid_faces(rows, cols)
zs = z.ravel()[face]
face = face[(zs.min(1) > 0.02) & (zs.max(1) < 1.12 * zs.min(1))]
return Surface(
"source_photo",
xyz,
face.astype("i4"),
np.stack([u, v], -1).reshape(-1, 2),
image,
)
def main():
p = argparse.ArgumentParser(description=__doc__)
for n in ("variant", "photo", "output"):
p.add_argument("--" + n, type=Path, required=True)
args = p.parse_args()
v = args.variant
out = args.output
out.mkdir(parents=True, exist_ok=True)
with np.load(v / "geometry/depth.npz") as f:
radial = f["radial"]
source_z = f["reference_z"]
tex = np.asarray(Image.open(v / "atlas/atlas.jpg").convert("RGB"))
mask = (
np.asarray(
Image.open(v / "geometry/observed.png").resize(
radial.shape[::-1], Image.Resampling.BILINEAR
)
)
/ 255
)
with Image.open(args.photo) as im:
image = ImageOps.exif_transpose(im).convert("RGB")
image.thumbnail((2304, 2304), Image.Resampling.LANCZOS)
image = np.asarray(image)
fov = json.loads((v / "atlas/registration.json").read_text())["reference_hfov"]
front = source_surface(image, source_z, fov)
log = np.log(radial).astype("f4")
smooth = cv2.bilateralFilter(log, 9, 0.12, 3.4)
mix = (1 - mask).astype("f4") * 0.8
d = (np.exp((1 - mix) * log + mix * smooth) * (1 + 0.012 * mask)).astype("f4")
back, bt = far_layer(d, tex)
surfaces = [
panorama_surface("panorama", d, tex, 768, 0.145),
panorama_surface("background", back, bt, 384),
front,
]
export_glb(surfaces, out / "scene.glb")
(out / "surface.json").write_text(
json.dumps(
dict(triangles={s.name: len(s.faces) for s in surfaces}, hfov=fov), indent=2
)
+ "\n"
)
if __name__ == "__main__":
main()