"""Keeps the biggest thing in a cutout and throws the rest away. The background remover leaves specks: a corner of the object that got separated from it, a rim of the black backdrop that survived. They are invisible against a dark game screen and they are also opaque, so trim.py measures the bounding box of the whole scatter and the object ends up somewhere off-centre inside a canvas mostly made of nothing. That is what happened to the book: the sheet drew centred and the painted book sat in the right-hand third of it. Run after trim.py: py -3.12 largest.py tw_book_sheet """ import os import sys import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen import config import numpy as np from PIL import Image from scipy import ndimage MIN_ALPHA = 40 def clean(path: str, out: str) -> None: image = Image.open(path).convert("RGBA") pixels = np.array(image) solid = pixels[:, :, 3] > MIN_ALPHA # Eight-connected, so a diagonal thread still counts as joined - a hinge or # a strap one pixel wide is part of the object, not a speck. labels, count = ndimage.label(solid, structure=np.ones((3, 3), dtype=int)) if count == 0: print(f" {path}: nothing opaque") return sizes = ndimage.sum(solid, labels, range(1, count + 1)) keep = int(np.argmax(sizes)) + 1 biggest = labels == keep dropped = int(solid.sum() - biggest.sum()) pixels[~biggest] = 0 rows = np.any(biggest, axis=1) cols = np.any(biggest, axis=0) top, bottom = np.where(rows)[0][[0, -1]] left, right = np.where(cols)[0][[0, -1]] cropped = Image.fromarray(pixels).crop((left, top, right + 1, bottom + 1)) cropped.save(out) print(f" {path}: {count} pieces, kept the largest, dropped {dropped} px " f"-> {cropped.width}x{cropped.height}") def main() -> int: if len(sys.argv) < 2: print(__doc__) return 1 for name in sys.argv[1:]: path = os.path.join(config.OUTPUT_DIR, f"{name}_trimmed.png") clean(path, path) return 0 if __name__ == "__main__": raise SystemExit(main())