LuminaWebsite/tools/stitch_map_screenshots.py
Maaxxs 3058456046 Karte: warn about the two ways a map ends up cropped or blurry
Both failure modes showed up in real use and neither was flagged anywhere.

A single screenshot in the folder produced a "stitch" of one image with no
warning at all, and the resulting ~900px map is upscaled on screen. The
stitcher now says plainly that there is nothing to stitch, prints the
resulting zoom levels, and warns below 4000px edge length; make_map_tiles.php
warns on the same threshold, so it catches the case regardless of which tool
is used.

The documented --crop example was copied verbatim and silently removed 180px
from the bottom of a real map. The example is gone: the plain command has no
--crop, and the option is now described as optional with values that must be
measured on one's own screenshots. The stitcher also reports what --crop
removes on every run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 14:44:55 +02:00

356 lines
15 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 math
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')
# Der haeufigste Fehler ist ein zu grosszuegiges --crop, das Teile der Karte selbst
# abschneidet - das faellt sonst erst auf der fertigen Website auf.
if crop and any(crop):
print(f' --crop schneidet weg: links {crop[0]}, oben {crop[1]}, '
f'rechts {crop[2]}, unten {crop[3]} Pixel')
print(' (Das sind DEINE Werte - pruefe am Ergebnis, dass davon nichts zur Karte gehoerte.)')
if len(images) == 1:
print('', file=sys.stderr)
print('ACHTUNG: In dem Ordner liegt nur ein einziges Bild, es gibt also nichts', file=sys.stderr)
print('zusammenzusetzen. Dieses Script verbindet VIELE ueberlappende Screenshots', file=sys.stderr)
print('zu einem grossen Bild. Ein einzelner Vollbild-Screenshot hat zu wenig Pixel,', file=sys.stderr)
print('um auf der Website scharf zu bleiben: im Spiel maximal hineinzoomen und die', file=sys.stderr)
print('Karte in Bahnen abfahren, mit rund 30% Ueberlappung.', file=sys.stderr)
print('', file=sys.stderr)
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})')
# Aus der Kantenlaenge folgt direkt, wie weit sich die Karte spaeter scharf
# heranzoomen laesst - darauf hier hinweisen statt es hinterher raten zu lassen.
longest = max(result.width, result.height)
levels = max(0, math.ceil(math.log2(longest / 256)))
print(f'Daraus entstehen die Zoomstufen 0 bis {levels}.')
if longest < 4000:
print('', file=sys.stderr)
print(f'HINWEIS: {longest} Pixel Kantenlaenge sind wenig. Damit die Karte auch nah', file=sys.stderr)
print('herangezoomt scharf bleibt, sollten es mindestens 4000 sein, gerne mehr.', file=sys.stderr)
print('Mehr Pixel gibt es ueber mehr Screenshots (im Spiel weiter hineinzoomen)', file=sys.stderr)
print('und eine hoehere Renderaufloesung (NVIDIA DSR / AMD VSR).', file=sys.stderr)
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()