LuminaWebsite/tools/stitch_map_screenshots.py
Maaxxs 4e414cba63 Karte: screenshot stitcher and sharper tiles
Adds tools/stitch_map_screenshots.py, which assembles overlapping in-game
map screenshots into one large image. How far the map can be zoomed in
sharply depends only on the source resolution - the tiler stops at 1:1 - so
the way to a sharp map is capturing a grid of screenshots at maximum in-game
zoom rather than one full-map screenshot.

Offsets are found by FFT phase correlation and verified by the normalised
cross correlation of the actual overlap, so filename order does not matter.
Because phase correlation is cyclic, both readings of every peak are tried
per axis - shifts beyond half the image width are the normal case at 35%
overlap. Overlaps are composited by nearest image centre, which keeps seams
away from the frame edges without the blur of feathering. Verified against a
reference image: 12 shuffled screenshots with UI bands reassemble
pixel-identically.

Sharpness on the website side: the tile layer now uses detectRetina, so
high-density displays get the next tile level drawn at half size instead of
an upscaled, blurry top level. Default JPEG quality raised from 82 to 88,
which suits map labels better.

The GD check in make_map_tiles.php now reports the loaded php.ini, the
extension_dir and the exact lines to add - a stock Windows/scoop PHP loads no
php.ini at all, so the previous one-line error left no way forward.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 13:56:28 +02:00

326 lines
13 KiB
Python

#!/usr/bin/env python3
"""Setzt ueberlappende Screenshots der Ingame-Karte zu einem grossen Bild zusammen.
Gedacht als Vorstufe zu tools/make_map_tiles.php: je mehr Pixel das zusammengesetzte
Bild hat, desto weiter laesst sich die Karte auf der Website scharf heranzoomen. Statt
die ganze Karte auf einen Screenshot zu quetschen, zoomst du im Spiel also maximal
hinein und faehrst die Karte in einem Raster ab - dieses Script findet die Ueberlappungen
von allein und baut daraus ein Bild.
Aufruf:
python tools/stitch_map_screenshots.py <screenshot-ordner> -o verteron.png
python tools/stitch_map_screenshots.py shots/ -o verteron.png --crop=0,60,0,120
Optionen:
-o, --output Zieldatei (PNG empfohlen, verlustfrei). Standard: stitched.png
--crop Raender wegschneiden, die auf jedem Screenshot gleich sind
(Chat, Minimap, Kartenrahmen) als links,oben,rechts,unten in Pixeln.
Wichtig: UI-Elemente ueber der Karte verwirren die Zuordnung.
--min-score Ab welcher Uebereinstimmung ein Bild akzeptiert wird (0..1,
Standard 0.55). Niedriger = toleranter, aber fehleranfaelliger.
--scale Vorab-Verkleinerung nur fuer die Suche (Standard 0.5). Kleiner =
schneller, groesser = genauer bei wenig Struktur.
--dry-run Nur die gefundene Anordnung ausgeben, nichts schreiben.
Voraussetzungen: Python 3.8+, numpy und Pillow (pip install numpy pillow).
Aufnahme-Hinweise:
* Immer dieselbe Zoomstufe im Spiel - das Script verschiebt Bilder nur, es dreht
und skaliert sie nicht.
* Mindestens ~30% Ueberlappung zwischen benachbarten Screenshots.
* In Bahnen abfahren (eine Reihe komplett, dann die naechste), das ist am robustesten.
* Fenstermodus ohne Rahmen, damit alle Screenshots exakt gleich gross sind.
* --crop lieber ein paar Pixel zu grosszuegig setzen als zu knapp: mitten im Bild
ueberdeckt ein Nachbar-Screenshot einen stehen gebliebenen UI-Streifen zwar wieder,
am aeusseren Kartenrand gibt es diesen Nachbarn aber nicht.
* Je mehr Pixel am Ende herauskommen, desto weiter laesst sich auf der Website scharf
hineinzoomen. Mehr Pixel bekommst du ueber mehr Screenshots (im Spiel weiter
hineinzoomen) und ueber eine hoehere Renderaufloesung (NVIDIA DSR / AMD VSR).
"""
import argparse
import os
import sys
try:
import numpy as np
from PIL import Image
except ImportError:
sys.exit("numpy und Pillow werden benoetigt: pip install numpy pillow")
Image.MAX_IMAGE_PIXELS = None # sehr grosse Ergebnisbilder sind hier gewollt
IMAGE_SUFFIXES = ('.png', '.jpg', '.jpeg', '.bmp', '.webp')
def load_images(folder, crop):
"""Laedt alle Bilder eines Ordners (alphabetisch) und schneidet die Raender ab."""
names = sorted(n for n in os.listdir(folder) if n.lower().endswith(IMAGE_SUFFIXES))
if not names:
sys.exit(f"Keine Bilder in {folder} gefunden ({', '.join(IMAGE_SUFFIXES)}).")
images = []
size = None
for name in names:
image = Image.open(os.path.join(folder, name)).convert('RGB')
if crop:
left, top, right, bottom = crop
box = (left, top, image.width - right, image.height - bottom)
if box[2] <= box[0] or box[3] <= box[1]:
sys.exit(f"--crop schneidet {name} komplett weg.")
image = image.crop(box)
if size is None:
size = image.size
elif image.size != size:
sys.exit(f"{name} ist {image.size[0]}x{image.size[1]}, erwartet {size[0]}x{size[1]}. "
"Alle Screenshots muessen gleich gross sein (Fenstermodus ohne Rahmen).")
images.append((name, np.asarray(image, dtype=np.float32)))
return images
def to_gray(rgb):
return rgb[:, :, 0] * 0.299 + rgb[:, :, 1] * 0.587 + rgb[:, :, 2] * 0.114
def correlation_surface(a, b):
"""Phasenkorrelation zweier gleich grosser Graustufenbilder.
Ueber die FFT, dadurch unempfindlich gegen Helligkeitsunterschiede und genau auf
reine Verschiebungen zugeschnitten - das ist unser Fall, die Ingame-Karte wird nur
verschoben, nicht gedreht oder skaliert. Zurueck kommt die komplette
Korrelationsflaeche; welche Spitze darin die richtige ist, entscheidet erst
overlap_score().
"""
fa = np.fft.rfft2(a - a.mean())
fb = np.fft.rfft2(b - b.mean())
cross = fa * np.conj(fb)
magnitude = np.abs(cross)
magnitude[magnitude == 0] = 1e-9
return np.fft.irfft2(cross / magnitude, s=a.shape)
def candidate_shifts(surface, count):
"""Die staerksten Spitzen der Korrelationsflaeche als Verschiebungs-Kandidaten.
Die FFT rechnet zyklisch: eine Spitze bei x kann eine Verschiebung um x nach rechts
ODER um x-Breite nach links bedeuten. Bei Panorama-Aufnahmen sind Verschiebungen
groesser als die halbe Bildbreite der Normalfall (bei 35% Ueberlappung sind es 65%
der Breite), deshalb werden beide Lesarten je Achse als Kandidat ausgegeben und
spaeter an der tatsaechlichen Ueberlappung geprueft.
"""
height, width = surface.shape
flat = surface.ravel()
count = min(count, flat.size)
top = np.argpartition(flat, -count)[-count:]
top = top[np.argsort(flat[top])[::-1]]
shifts = []
for index in top:
y, x = divmod(int(index), width)
for dy in {y, y - height}:
for dx in {x, x - width}:
shifts.append((dy, dx))
return shifts
def overlap_score(a, b, dy, dx):
"""Bewertet eine Verschiebung an der tatsaechlichen Ueberlappung.
Die Spitze der Phasenkorrelation allein sagt wenig - erst der normierte
Korrelationskoeffizient im ueberlappenden Bereich zeigt, ob dort wirklich dasselbe
zu sehen ist. Ergebnis zwischen -1 und 1.
"""
height, width = a.shape
ay0, by0 = max(0, dy), max(0, -dy)
ax0, bx0 = max(0, dx), max(0, -dx)
h = min(height - ay0, height - by0)
w = min(width - ax0, width - bx0)
# Zu kleine Ueberlappungen sind statistisch wertlos.
if h < height * 0.12 or w < width * 0.12:
return -1.0
pa = a[ay0:ay0 + h, ax0:ax0 + w].ravel()
pb = b[by0:by0 + h, bx0:bx0 + w].ravel()
pa = pa - pa.mean()
pb = pb - pb.mean()
denominator = float(np.sqrt((pa * pa).sum() * (pb * pb).sum()))
if denominator < 1e-9:
return -1.0
return float((pa * pb).sum() / denominator)
def find_offset(gray_a, gray_b, small_a, small_b, scale):
"""Verschiebung von b gegenueber a, in Pixeln des Originalbildes.
Dreistufig: Kandidaten aus der Korrelationsflaeche des verkleinerten Bildes, grobe
Vorauswahl ebenfalls im Kleinen (schnell), dann Feinsuche auf Pixelgenauigkeit im
Original.
"""
candidates = candidate_shifts(correlation_surface(small_a, small_b), 8)
scored = [(overlap_score(small_a, small_b, dy, dx), dy, dx) for dy, dx in candidates]
scored.sort(reverse=True)
best = (0, 0, -1.0)
for _, dy, dx in scored[:3]:
fy, fx = int(round(dy / scale)), int(round(dx / scale))
score = overlap_score(gray_a, gray_b, fy, fx)
if score > best[2]:
best = (fy, fx, score)
# Die Verkleinerung kostet Genauigkeit - im Original nachjustieren.
radius = max(2, int(round(1 / scale)) + 1)
dy, dx = best[0], best[1]
for oy in range(-radius, radius + 1):
for ox in range(-radius, radius + 1):
score = overlap_score(gray_a, gray_b, dy + oy, dx + ox)
if score > best[2]:
best = (dy + oy, dx + ox, score)
return best
def main():
parser = argparse.ArgumentParser(
description='Setzt ueberlappende Karten-Screenshots zu einem grossen Bild zusammen.')
parser.add_argument('folder', help='Ordner mit den Screenshots')
parser.add_argument('-o', '--output', default='stitched.png', help='Zieldatei (Standard: stitched.png)')
parser.add_argument('--crop', default=None, help='Raender abschneiden: links,oben,rechts,unten')
parser.add_argument('--min-score', type=float, default=0.55, help='Mindest-Uebereinstimmung 0..1 (Standard 0.55)')
parser.add_argument('--scale', type=float, default=0.5, help='Verkleinerung fuer die Suche (Standard 0.5)')
parser.add_argument('--dry-run', action='store_true', help='Nur die Anordnung zeigen, nichts schreiben')
args = parser.parse_args()
crop = None
if args.crop:
try:
crop = tuple(int(v) for v in args.crop.split(','))
if len(crop) != 4 or any(v < 0 for v in crop):
raise ValueError
except ValueError:
sys.exit('--crop erwartet vier nicht-negative Zahlen: links,oben,rechts,unten')
scale = min(1.0, max(0.1, args.scale))
images = load_images(args.folder, crop)
height, width = images[0][1].shape[:2]
print(f'{len(images)} Screenshots, je {width}x{height} Pixel')
grays = [to_gray(rgb) for _, rgb in images]
smalls = []
for gray in grays:
if scale < 1.0:
small = np.asarray(
Image.fromarray(gray).resize(
(max(8, int(gray.shape[1] * scale)), max(8, int(gray.shape[0] * scale))),
Image.BILINEAR),
dtype=np.float32)
else:
small = gray
smalls.append(small)
# Das erste Bild legt den Nullpunkt fest, alle weiteren werden relativ dazu
# eingeordnet. Ein Bild wird nur gesetzt, wenn es zu einem bereits gesetzten
# Bild sicher genug passt - der Rest kommt in der naechsten Runde dran.
placed = {0: (0, 0)}
print(f' [1/{len(images)}] {images[0][0]} -> Nullpunkt')
pending = set(range(1, len(images)))
while pending:
progress = False
for index in sorted(pending):
best = None
for anchor in placed:
dy, dx, score = find_offset(grays[anchor], grays[index],
smalls[anchor], smalls[index], scale)
if best is None or score > best[2]:
best = (dy, dx, score, anchor)
dy, dx, score, anchor = best
if score < args.min_score:
continue
ay, ax = placed[anchor]
placed[index] = (ay + dy, ax + dx)
pending.discard(index)
progress = True
print(f' [{len(placed)}/{len(images)}] {images[index][0]} -> '
f'an {images[anchor][0]}, Versatz y{ay + dy:+d} x{ax + dx:+d}, '
f'Uebereinstimmung {score:.2f}')
if not progress:
break
if pending:
print('\nNicht zugeordnet (zu wenig Ueberlappung oder zu wenig Struktur im Bild):',
file=sys.stderr)
for index in sorted(pending):
print(f' - {images[index][0]}', file=sys.stderr)
print('Hilft meistens: mehr Ueberlappung aufnehmen, --crop fuer feste UI-Elemente '
'setzen oder --min-score senken.', file=sys.stderr)
offsets = [placed[i] for i in sorted(placed)]
min_y = min(y for y, _ in offsets)
min_x = min(x for _, x in offsets)
max_y = max(y for y, _ in offsets) + height
max_x = max(x for _, x in offsets) + width
canvas_height, canvas_width = max_y - min_y, max_x - min_x
print(f'\nErgebnis: {canvas_width} x {canvas_height} Pixel '
f'({canvas_width * canvas_height / 1_000_000:.1f} Megapixel)')
if args.dry_run:
return
canvas = np.zeros((canvas_height, canvas_width, 3), dtype=np.float32)
# Fuer jedes Zielpixel gewinnt der Screenshot, dessen Mitte am naechsten liegt.
# Das haelt die Naht weg von den Bildraendern (wo Vignettierung/UI-Reste sitzen)
# und bleibt dabei pixelscharf - anders als weiches Ueberblenden.
best_distance = np.full((canvas_height, canvas_width), np.inf, dtype=np.float32)
yy = np.abs(np.arange(height, dtype=np.float32) - (height - 1) / 2)[:, None]
xx = np.abs(np.arange(width, dtype=np.float32) - (width - 1) / 2)[None, :]
center_distance = np.maximum(yy / height, xx / width)
for index in sorted(placed):
y, x = placed[index]
y -= min_y
x -= min_x
region = best_distance[y:y + height, x:x + width]
mask = center_distance < region
region[mask] = center_distance[mask]
canvas[y:y + height, x:x + width][mask] = images[index][1][mask]
result = Image.fromarray(np.clip(canvas, 0, 255).astype(np.uint8))
# Nicht abgedeckte Raender abschneiden (entstehen bei versetzten Bahnen).
covered = np.isfinite(best_distance)
rows = np.where(covered.any(axis=1))[0]
cols = np.where(covered.any(axis=0))[0]
if len(rows) and len(cols):
result = result.crop((int(cols[0]), int(rows[0]), int(cols[-1]) + 1, int(rows[-1]) + 1))
result.save(args.output)
print(f'Gespeichert: {args.output} ({result.width} x {result.height})')
key = os.path.splitext(os.path.basename(args.output))[0].lower()
print('\nWeiter mit:')
print(f' php -d memory_limit=4G tools/make_map_tiles.php {key} "{args.output}" --name="{key.capitalize()}"')
if __name__ == '__main__':
main()