File size: 2,958 Bytes
16231ab | 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 | """Equirectangular panorama -> 4 perspective views (yaw 0/90/180/270, 90 degree FOV, 512 x 512), the view format of
all training pairs. Non-panoramas (aspect < 1.8) are copied, downscaled to at most 1024 px."""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]
import math
from pathlib import Path
import numpy as np
from PIL import Image
from scipy.ndimage import map_coordinates
YAWS = (0, 90, 180, 270)
def perspective_view(pano: np.ndarray, yaw_deg: float, size: int, fov_deg: float = 90.0) -> np.ndarray:
"""Equirectangular (H, W, 3) -> square perspective view looking at yaw_deg, pitch 0.
The panorama covers 360 degrees horizontally; its vertical extent is 360 * H / W degrees
centred on the horizon (180 for a full 2:1 panorama, less for one cropped top and bottom).
"""
height, width = pano.shape[:2]
vertical_span = 2 * math.pi * height / width
half = math.tan(math.radians(fov_deg) / 2)
grid = (np.arange(size) + 0.5) / size * 2 - 1
x, y = np.meshgrid(grid * half, -grid * half)
yaw = math.radians(yaw_deg)
dx = x * math.cos(yaw) + math.sin(yaw)
dz = -x * math.sin(yaw) + math.cos(yaw)
lon = np.arctan2(dx, dz)
lat = np.arctan2(y, np.hypot(dx, dz))
u = np.mod((lon / (2 * math.pi) + 0.5) * width - 0.5, width)
v = np.clip((0.5 - lat / vertical_span) * height - 0.5, 0, height - 1)
# Pad one column so bilinear sampling wraps across the 0/360-degree seam.
padded = np.concatenate([pano, pano[:, :1]], axis=1)
channels = [map_coordinates(padded[..., c], [v, u], order=1, mode="nearest") for c in range(3)]
return np.clip(np.stack(channels, -1), 0, 255).astype(np.uint8)
def make_views(image_path: Path, views_dir: Path, stem: str, size: int,
min_aspect: float = 1.8) -> tuple[list[Path], bool]:
with Image.open(image_path) as image:
width, height = image.size
is_pano = width / height >= min_aspect
outputs = [views_dir / f"{stem}_yaw{yaw:03d}.jpg" for yaw in YAWS] if is_pano else [views_dir / f"{stem}.jpg"]
if all(p.exists() for p in outputs):
return outputs, is_pano
views_dir.mkdir(parents=True, exist_ok=True)
rgb = image.convert("RGB")
if not is_pano:
rgb.thumbnail((1024, 1024))
rgb.save(outputs[0], quality=92)
return outputs, False
if width > 4096:
rgb = rgb.resize((4096, round(4096 * height / width)), Image.BICUBIC)
pano = np.asarray(rgb, dtype=np.float32)
for yaw, path in zip(YAWS, outputs):
Image.fromarray(perspective_view(pano, yaw, size)).save(path, quality=92)
return outputs, True
|