"""Register an AI-regenerated square base to the rotated source and keep the real pixels. python tools/align_square.py # fix sources/overall/overall-square.png in place python tools/align_square.py --image build/x.png --out build/y.png python tools/align_square.py --dry-run # report the fit, write build/align-square-preview.png python tools/align_square.py --no-tone-match # paste the corners as generated Image-to-image models asked to "fill only the corners" of the rotated base tend to re-render the whole picture and move it a little: the August 2026 Gemini pass came back scaled by 0.99 and shifted by (26, 54) px. Every map's `place` is in rotated overall-map pixels, so such a base puts all detail maps ~45 px (almost 3000 world px) off their zone outlines. This tool 1. measures the generated image against the rotated source with phase correlation on a grid of patches and fits an affine transform to the inliers (reported; the residual should be well under a pixel), 2. warps the generated image back into the source frame, 3. pastes the rotated source over everything that is a real pixel (alpha 255; the antialiased rim is blended by alpha), so only the four outpainted corner triangles come from the generator, and 4. tone-matches each corner to the real pixels just inside the seam: the per-channel offset between the two 8 px bands either side of the edge is measured in windows along the edge, smoothed, and added to the corner pixels with a weight that fades from 1 at the seam to 0 `--fade` px into the corner. The generator brightens/dehazes the interior to match its corners; this puts the corners back next to the darker original. The result is then what square_base.py promises: real pixels 100% untouched. Run tools/sea_corner.py afterwards for the flat open-sea corner, then retile the base (python tools/build.py overall). The fit is written to build/align-square.json. """ from __future__ import annotations import argparse import json import sys from pathlib import Path import numpy as np from PIL import Image from common import BUILD, CONFIG, ROOT CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right") def phase_shift(a: np.ndarray, b: np.ndarray) -> tuple[int, int, float]: """Integer (dx, dy) that moves `b` onto `a`, and the correlation peak.""" a = a - a.mean() b = b - b.mean() win = np.outer(np.hanning(a.shape[0]), np.hanning(a.shape[1])) fa, fb = np.fft.fft2(a * win), np.fft.fft2(b * win) r = fa * np.conj(fb) r /= np.abs(r) + 1e-9 r = np.fft.ifft2(r).real iy, ix = np.unravel_index(np.argmax(r), r.shape) dy = iy if iy <= a.shape[0] // 2 else iy - a.shape[0] dx = ix if ix <= a.shape[1] // 2 else ix - a.shape[1] return int(dx), int(dy), float(r.max()) def fit_affine(image_l: np.ndarray, source_l: np.ndarray, real: np.ndarray, patch: int = 192, step: int = 80) -> tuple[np.ndarray, dict]: """Affine A (2x3) with image(A p) == source(p), fitted to patch shifts.""" h, w = source_l.shape pts = [] half = patch // 2 for y in range(half + 64, h - half - 64, step): for x in range(half + 64, w - half - 64, step): win = (slice(y - half, y + half), slice(x - half, x + half)) if real[win].mean() < 0.99 or source_l[win].std() < 6: continue # not all real, or flat sea dx, dy, peak = phase_shift(image_l[win], source_l[win]) if peak > 0.03 and abs(dx) < 120 and abs(dy) < 120: pts.append((x, y, dx, dy, peak)) if len(pts) < 12: raise SystemExit(f"only {len(pts)} usable patches; is this the same map?") pts = np.array(pts, dtype=np.float64) src = pts[:, :2] dst = src + pts[:, 2:4] ones = np.ones((len(pts), 1)) keep = np.ones(len(pts), dtype=bool) for _ in range(6): wgt = pts[keep, 4:5] m = np.hstack([src[keep], ones[keep]]) * wgt ax = np.linalg.lstsq(m, dst[keep, 0] * wgt[:, 0], rcond=None)[0] ay = np.linalg.lstsq(m, dst[keep, 1] * wgt[:, 0], rcond=None)[0] pred = np.hstack([src, ones]) @ np.c_[ax, ay] res = np.hypot(*(pred - dst).T) keep = res < max(6.0, 2.0 * np.median(res[keep])) a = np.array([ax, ay]) info = { "patches": int(len(pts)), "inliers": int(keep.sum()), "inlier_rms_px": float(np.sqrt((res[keep] ** 2).mean())), "scale_x": float(np.hypot(a[0, 0], a[1, 0])), "scale_y": float(np.hypot(a[0, 1], a[1, 1])), "rotation_deg": float(np.degrees(np.arctan2(a[1, 0], a[0, 0]))), "shift_at_centre": [float(v) for v in (a @ [w / 2, h / 2, 1] - [w / 2, h / 2])], "affine": [[float(v) for v in row] for row in a], } return a, info def warp_back(image: Image.Image, a: np.ndarray, pad: int = 96) -> Image.Image: """out(p) = image(A p); edge-replicated so the border never goes black.""" arr = np.pad(np.asarray(image), ((pad, pad), (pad, pad), (0, 0)), mode="edge") data = (a[0, 0], a[0, 1], a[0, 2] + pad, a[1, 0], a[1, 1], a[1, 2] + pad) return Image.fromarray(arr).transform(image.size, Image.AFFINE, data, resample=Image.BICUBIC) def corner_geometry(alpha: np.ndarray): """Per corner: (triangle mask, signed distance to the edge in px (+ into the corner, - into the map), coordinate along the edge).""" h, w = alpha.shape xs = np.arange(w, dtype=np.int32)[None, :] ys = np.arange(h, dtype=np.int32)[:, None] empty = alpha == 0 left = np.broadcast_to(xs < w / 2, (h, w)) top = np.broadcast_to(ys < h / 2, (h, w)) quads = {"top_left": left & top, "top_right": ~left & top, "bottom_left": left & ~top, "bottom_right": ~left & ~top} diag = {"top_left": xs + ys, "top_right": (w - 1 - xs) + ys, "bottom_left": xs + (h - 1 - ys), "bottom_right": (w - 1 - xs) + (h - 1 - ys)} along = {"top_left": xs - ys, "top_right": xs + ys, "bottom_left": xs + ys, "bottom_right": xs - ys} out = {} for name in CORNERS: mask = empty & quads[name] if not mask.any(): continue d = np.broadcast_to(diag[name], (h, w)) edge = int(d[mask].max()) out[name] = (mask, (edge - d) / np.sqrt(2.0), np.broadcast_to(along[name], (h, w))) return out def tone_match(out: np.ndarray, alpha: np.ndarray, fade: int, band: int = 8, window: int = 32) -> dict: """Add the seam offset (real band - corner band) to each corner, fading out.""" real = alpha == 255 report = {} for name, (mask, dist, along) in corner_geometry(alpha).items(): inner = real & (dist < -2) & (dist > -2 - band) outer = mask & (dist > 1) & (dist < 1 + band) if not inner.any() or not outer.any(): continue t_all = along[mask] t0, t1 = int(along[inner | outer].min()), int(along[inner | outer].max()) bins = np.arange(t0, t1 + window, window) offsets = np.full((len(bins) - 1, 3), np.nan) ti, to = along[inner], along[outer] for i in range(len(bins) - 1): si = (ti >= bins[i]) & (ti < bins[i + 1]) so = (to >= bins[i]) & (to < bins[i + 1]) if si.sum() >= 8 and so.sum() >= 8: offsets[i] = out[inner][si].mean(0) - out[outer][so].mean(0) good = ~np.isnan(offsets[:, 0]) if good.sum() < 2: continue centres = (bins[:-1] + bins[1:]) / 2 # Fill gaps by interpolation, then smooth with a short gaussian. for c in range(3): offsets[:, c] = np.interp(centres, centres[good], offsets[good, c]) k = np.exp(-0.5 * (np.arange(-3, 4) / 1.5) ** 2) k /= k.sum() padded = np.pad(offsets, ((3, 3), (0, 0)), mode="edge") smooth = np.stack([np.convolve(padded[:, c], k, mode="valid") for c in range(3)], axis=1) weight = np.clip(1.0 - dist[mask] / float(fade), 0.0, 1.0)[:, None] off = np.stack([np.interp(t_all, centres, smooth[:, c]) for c in range(3)], axis=1) px = out[mask].astype(np.float64) + off * weight out[mask] = np.clip(np.rint(px), 0, 255).astype(np.uint8) report[name] = {"mean_offset": [float(v) for v in smooth.mean(0)], "max_abs_offset": float(np.abs(smooth).max())} return report def seam_step(rgb: np.ndarray, alpha: np.ndarray, band: int = 3) -> dict: """Mean |RGB step| across the diamond edge per corner (diagnostic).""" real = alpha == 255 steps = {} for name, (mask, dist, _) in corner_geometry(alpha).items(): inner = real & (dist < -1) & (dist > -1 - band) outer = mask & (dist > 0) & (dist < band) if inner.any() and outer.any(): steps[name] = float(np.abs(rgb[inner].mean(0) - rgb[outer].mean(0)).mean()) return steps def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--image", type=Path, help="generated square base (default: maps.json world.image)") parser.add_argument("--out", type=Path, help="where to write (default: overwrite --image)") parser.add_argument("--source", type=Path, default=ROOT / "sources" / "overall" / "overall.jpeg", help="unrotated source the square image was made from") parser.add_argument("--rotate", type=float, default=45.0, help="degrees CCW square_base.py used") parser.add_argument("--fade", type=int, default=220, help="px over which the corner tone correction fades out (0 = no fade limit)") parser.add_argument("--no-tone-match", action="store_true", help="paste the corners as generated") parser.add_argument("--dry-run", action="store_true", help="report the fit and write build/align-square-preview.png only") args = parser.parse_args(argv) image_path = args.image if image_path is None: raw = json.loads(CONFIG.read_text(encoding="utf-8")) image_path = ROOT / raw["world"]["image"] image = Image.open(image_path).convert("RGB") rotated = Image.open(args.source).convert("RGBA").rotate( args.rotate, expand=True, resample=Image.BICUBIC) if rotated.size != image.size: raise SystemExit(f"rotated source is {rotated.size}, image is {image.size}; " "use the --source/--rotate square_base.py used") source = np.asarray(rotated.convert("RGB")) alpha = np.asarray(rotated.getchannel("A")) real = alpha == 255 before = seam_step(np.asarray(image), alpha) a, info = fit_affine(np.asarray(image.convert("L"), dtype=np.float64), np.asarray(rotated.convert("L"), dtype=np.float64), real) print(f"fit: {info['inliers']}/{info['patches']} patches, rms {info['inlier_rms_px']:.2f} px; " f"scale ({info['scale_x']:.4f}, {info['scale_y']:.4f}), rotation {info['rotation_deg']:.3f} deg, " f"shift at centre ({info['shift_at_centre'][0]:+.1f}, {info['shift_at_centre'][1]:+.1f}) px") if info["inlier_rms_px"] > 2.0: print("warning: the generated image is not an affine transform of the source " "(rms > 2 px); the corners will not meet the real pixels cleanly") warped = np.asarray(warp_back(image, a)) out = warped.copy() out[real] = source[real] rim = (alpha > 0) & (alpha < 255) k = alpha[rim].astype(np.float64)[:, None] / 255.0 out[rim] = np.clip(np.rint(source[rim] * k + warped[rim] * (1 - k)), 0, 255).astype(np.uint8) assert np.array_equal(out[real], source[real]), "real pixels must not change" tone = {} if not args.no_tone_match: tone = tone_match(out, alpha, args.fade if args.fade > 0 else 10 ** 6) assert np.array_equal(out[real], source[real]), "real pixels must not change" after = seam_step(out, alpha) for name in CORNERS: if name in before: extra = f", tone offset {tone[name]['mean_offset']}" if name in tone else "" print(f"{name}: seam step {before[name]:.1f} -> {after[name]:.1f}{extra}") info.update({"image": str(image_path.relative_to(ROOT)) if image_path.is_relative_to(ROOT) else str(image_path), "tone_match": tone, "seam_step_before": before, "seam_step_after": after}) BUILD.mkdir(exist_ok=True) (BUILD / "align-square.json").write_text(json.dumps(info, indent=2), encoding="utf-8") if args.dry_run: preview = BUILD / "align-square-preview.png" Image.fromarray(out).save(preview) print(f"preview written to {preview.relative_to(ROOT)}; {image_path.name} unchanged") return out_path = (args.out or image_path).resolve() Image.fromarray(out).save(out_path, optimize=True, compress_level=9) try: shown = out_path.relative_to(ROOT) except ValueError: shown = out_path print(f"wrote {shown}") if __name__ == "__main__": main(sys.argv[1:])