The overall source is a feathered "cropped map" sitting on a uniform dark background: its whole left, bottom and right margins and most of its top edge are flat (#121818). Everything outside it is sea, so the AI-outpainted land in all four corners of overall-square.png was wrong, not just bottom-left. tools/sea_corner.py now fills all four corner triangles by default with that background colour (--color sample restores per-corner sampling) and feathers flat-background pixels within 96 px inside the diamond toward the fill, so the diamond outline no longer shows where the source margin was a little brighter; textured content is untouched and the result is idempotent (real pixels are re-read from the rotated source). Overall tiles rebuilt. Co-Authored-By: Claude Fable 5 <[email protected]>
172 lines
8.2 KiB
Python
172 lines
8.2 KiB
Python
"""Fill outpainted corner triangles of the square base map with flat sea colour.
|
|
|
|
python tools/sea_corner.py # all four corners, flat #121818
|
|
python tools/sea_corner.py bottom_left # one corner only
|
|
python tools/sea_corner.py --color sample # per-corner median of the sea next to it
|
|
python tools/sea_corner.py --dry-run # write build/sea-corner-preview.png only
|
|
|
|
tools/square_base.py rotates sources/overall/overall.jpeg by 45 degrees and
|
|
outpaints the four empty corner triangles with AI imagery. But the source is
|
|
a feathered "cropped map" lying on a uniform dark sea background (its whole
|
|
left, bottom and right margins and most of the top are flat, median #121818),
|
|
so anything outside it is sea and the invented coastline/land in the corners
|
|
is wrong. This replaces the corners with one flat colour. The corner region
|
|
is exactly the rotated source's alpha == 0 area in that quadrant. The source's
|
|
own flat margin just inside the diamond is a little brighter than the fill in
|
|
places, which would draw the diamond outline, so --feather (default 96 px)
|
|
eases flat-background pixels next to a filled corner toward the fill colour;
|
|
textured map content is left alone (its hard edge against the sea is what
|
|
"sea outside the map" means). Real pixels are re-read from the rotated source
|
|
so the tool is idempotent. Re-run after regenerating overall-square.png, then
|
|
retile the base:
|
|
|
|
rm -rf web/tiles/overall && python tools/build.py overall
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from PIL import Image, ImageFilter
|
|
|
|
from common import CONFIG, ROOT
|
|
|
|
CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
|
|
|
|
|
|
def corner_masks(source: Path, rotate: float, size: tuple[int, int]):
|
|
"""(rotated source RGB, its alpha, {corner: empty-triangle mask}, {corner: distance map}).
|
|
|
|
The distance map gives, for every pixel, its distance in px to the corner
|
|
triangle (0 inside it); the triangle's edge is a 45-degree line, so this
|
|
is just the offset along the diagonal axis.
|
|
"""
|
|
rotated = Image.open(source).convert("RGBA").rotate(rotate, expand=True, resample=Image.BICUBIC)
|
|
if rotated.size != size:
|
|
raise SystemExit(f"rotated source is {rotated.size}, square image is {size}; "
|
|
"use the same --source/--rotate square_base.py used")
|
|
rgb = np.array(rotated.convert("RGB"))
|
|
alpha = np.array(rotated.getchannel("A"))
|
|
h, w = alpha.shape
|
|
yy, xx = np.mgrid[0:h, 0:w]
|
|
empty = alpha == 0
|
|
left, top = xx < w / 2, yy < h / 2
|
|
quadrants = {
|
|
"top_left": left & top,
|
|
"top_right": ~left & top,
|
|
"bottom_left": left & ~top,
|
|
"bottom_right": ~left & ~top,
|
|
}
|
|
diagonals = { # grows away from the corner point
|
|
"top_left": xx + yy,
|
|
"top_right": (w - 1 - xx) + yy,
|
|
"bottom_left": xx + (h - 1 - yy),
|
|
"bottom_right": (w - 1 - xx) + (h - 1 - yy),
|
|
}
|
|
masks, distances = {}, {}
|
|
for name, quadrant in quadrants.items():
|
|
mask = empty & quadrant
|
|
masks[name] = mask
|
|
edge = diagonals[name][mask].max() if mask.any() else -1
|
|
distances[name] = np.clip(diagonals[name] - edge, 0, None) / np.sqrt(2.0)
|
|
return rgb, alpha, masks, distances
|
|
|
|
|
|
def flatness(rgb: np.ndarray) -> np.ndarray:
|
|
"""1 where the image is featureless background, 0 where it has texture."""
|
|
grey = Image.fromarray(rgb).convert("L")
|
|
g = np.array(grey, dtype=np.float32)
|
|
blur = np.array(grey.filter(ImageFilter.GaussianBlur(6)), dtype=np.float32)
|
|
detail = Image.fromarray(np.abs(g - blur).astype(np.uint8)).filter(ImageFilter.BoxBlur(8))
|
|
return np.clip(1.0 - np.array(detail, dtype=np.float32) / 4.0, 0.0, 1.0)
|
|
|
|
|
|
def sample_colour(rgb: np.ndarray, alpha: np.ndarray, corner: np.ndarray, band: int) -> tuple[int, int, int]:
|
|
"""Median of real pixels within `band` px of the corner's edge."""
|
|
dilated = np.array(Image.fromarray((corner * 255).astype(np.uint8))
|
|
.filter(ImageFilter.MaxFilter(2 * band + 1))) > 0
|
|
selection = dilated & (alpha > 0)
|
|
if not selection.any():
|
|
raise SystemExit("no real pixels next to that corner to sample from")
|
|
return tuple(int(v) for v in np.median(rgb[selection], axis=0))
|
|
|
|
|
|
def parse_colour(value: str) -> tuple[int, int, int] | None:
|
|
if value == "sample":
|
|
return None
|
|
value = value.lstrip("#")
|
|
if len(value) != 6:
|
|
raise argparse.ArgumentTypeError("colour must be #rrggbb")
|
|
return tuple(int(value[i:i + 2], 16) for i in (0, 2, 4))
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
parser.add_argument("corners", nargs="*", choices=CORNERS,
|
|
help="corners to fill (default: all four)")
|
|
parser.add_argument("--image", type=Path, help="square base image (default: maps.json world.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("--color", type=parse_colour, default=(0x12, 0x18, 0x18),
|
|
help="fill colour #rrggbb, or 'sample' for the per-corner median of "
|
|
"the real pixels next to the corner (default: #121818, the "
|
|
"source's flat background)")
|
|
parser.add_argument("--band", type=int, default=20, help="sampling band width in px")
|
|
parser.add_argument("--noise", type=float, default=0.0,
|
|
help="gaussian grain sigma to add to the fill (0 = perfectly flat)")
|
|
parser.add_argument("--feather", type=int, default=96,
|
|
help="px over which flat background next to a filled corner eases "
|
|
"into the fill colour (0 = leave every real pixel untouched)")
|
|
parser.add_argument("--dry-run", action="store_true", help="write a preview, keep the image")
|
|
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")
|
|
rgb = np.array(image)
|
|
source_rgb, alpha, masks, distances = corner_masks(args.source, args.rotate, image.size)
|
|
real = alpha == 255
|
|
flat = flatness(source_rgb) if args.feather > 0 else None
|
|
|
|
out = rgb.copy()
|
|
for corner in dict.fromkeys(args.corners or CORNERS):
|
|
mask = masks[corner]
|
|
colour = args.color or sample_colour(rgb, alpha, mask, args.band)
|
|
fill = np.empty((int(mask.sum()), 3), dtype=np.float64)
|
|
fill[:] = colour
|
|
if args.noise > 0:
|
|
fill += np.random.default_rng(0).normal(0, args.noise, fill.shape)
|
|
out[mask] = np.clip(np.rint(fill), 0, 255).astype(np.uint8)
|
|
feathered = 0
|
|
if args.feather > 0:
|
|
band = real & (distances[corner] > 0) & (distances[corner] < args.feather)
|
|
weight = flat[band] * (1.0 - distances[corner][band] / args.feather)
|
|
base = source_rgb[band].astype(np.float64) # untouched originals: idempotent
|
|
blended = base + (np.array(colour, dtype=np.float64) - base) * weight[:, None]
|
|
out[band] = np.clip(np.rint(blended), 0, 255).astype(np.uint8)
|
|
feathered = int((weight > 0.01).sum())
|
|
print(f"{corner}: {int(mask.sum())} px -> #{colour[0]:02x}{colour[1]:02x}{colour[2]:02x}"
|
|
+ (f" (+noise sigma {args.noise})" if args.noise > 0 else "")
|
|
+ (f", feathered {feathered} flat px" if feathered else ""))
|
|
|
|
if args.dry_run:
|
|
preview = ROOT / "build" / "sea-corner-preview.png"
|
|
Image.fromarray(out).save(preview)
|
|
print(f"preview written to {preview.relative_to(ROOT)}; {image_path.name} unchanged")
|
|
return
|
|
if args.feather <= 0:
|
|
assert np.array_equal(out[alpha > 0], rgb[alpha > 0]), "real pixels must not change"
|
|
Image.fromarray(out).save(image_path, optimize=True)
|
|
print(f"wrote {image_path.relative_to(ROOT)}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|