view tools/cut_sheet.py @ 28:b0658e7fcee2

Added tag 0.9.1 for changeset 75deda08db90
author ark
date 2026-10-20 17:19 +0200
parents 2c4fed8baed9
children
line wrap: on
line source

"""
cut the sprites out of a scanned drawing sheet and write them to art/.

    python3 tools/cut_sheet.py art/art_sources/source_sheet_2.jpg

the boxes below are set by hand for source_sheet_2.jpg, in sheet pixels, at
the sheet's own scale. each box holds one drawing with an inked outline. the
largest connected outline in a box is the drawing; other ink in the box, such
as a neighbour's edge, is dropped. the inside of the outline keeps the
scanned colour, the paper is whitened, the outside becomes transparent.

the t*p strips are made of four boxes each, levels 2-5, laid out side by side
with empty columns between them, as the build expects (see images.py).

coins and maps are not on the sheet in inked form and are not written.
"""

import sys
from pathlib import Path

from PIL import Image, ImageDraw, ImageFilter

ART = Path(__file__).resolve().parent.parent / "art"

# box padding, so the outline never touches the crop border
PAD = 12
# outline ink is darker than this luminance
INK_LUM = 150
# outside the outline, pixels fade from opaque at INK_LUM to transparent here
LUM_CLEAR = 245
# paper is lighter than this and becomes white; darker colours are scaled
PAPER_LUM = 235
# other outlines in a box are kept if they reach this share of the largest
# and do not touch the box border
KEEP_SHARE = 0.05
# empty columns between the levels of a tower strip
STRIP_GAP = 40

SPRITES = {
    "hpm": (284, 204, 424, 260),
    "m0": (280, 280, 428, 412),
    "m1": (496, 264, 628, 388),
    "m2": (676, 276, 780, 376),
    "m3": (804, 248, 916, 364),
    "m4": (924, 244, 1040, 368),
    "t1": (236, 564, 436, 696),
    "t0": (476, 528, 632, 684),
    "t2": (688, 512, 816, 668),
    "t3": (872, 500, 1040, 652),
    "hpb": (172, 730, 450, 785),
    "b0": (200, 780, 440, 950),
    "b1": (436, 760, 648, 950),
    "b2": (688, 700, 828, 904),
    "b3": (896, 712, 1040, 896),
    "p1": (236, 1044, 300, 1096),
    "p0": (520, 980, 568, 1080),
    "p2": (720, 1008, 784, 1076),
    "p3": (920, 976, 996, 1052),
}

STRIPS = {
    "t1p": [(1284, 464, 1508, 600), (1552, 424, 1808, 592),
            (1816, 404, 2044, 560), (2080, 392, 2456, 548)],
    "t0p": [(2544, 360, 2712, 540), (2736, 340, 2960, 548),
            (2980, 300, 3226, 572), (3226, 290, 3500, 580)],
    "t2p": [(1320, 672, 1452, 840), (1536, 656, 1648, 828),
            (1720, 616, 1856, 812), (1920, 592, 2064, 796)],
    "t3p": [(2120, 596, 2292, 788), (2312, 616, 2560, 804),
            (2580, 620, 2800, 800), (2816, 552, 3036, 788)],
}


def outlines(walls):
    """
    return the connected parts of a mask as (count, seed, touches border),
    largest first. walls is an L image with 255 for ink.
    """
    w, h = walls.size
    work = walls.copy()
    px = work.load()
    parts = []
    for y in range(h):
        for x in range(w):
            if px[x, y] != 255:
                continue
            ImageDraw.floodfill(work, (x, y), 100)
            part = work.point(lambda v: 255 if v == 100 else 0)
            count = part.histogram()[255]
            l, t, r, b = part.getbbox()
            border = l == 0 or t == 0 or r == w or b == h
            ImageDraw.floodfill(work, (x, y), 50)
            px = work.load()
            parts.append((count, (x, y), border))
    parts.sort(reverse=True)
    return parts


def cut(sheet, box):
    """cut one drawing out of the sheet. returns a trimmed RGBA image."""
    l, t, r, b = box
    src = sheet.crop((max(0, l - PAD), max(0, t - PAD),
                      min(sheet.width, r + PAD), min(sheet.height, b + PAD)))
    # pad with paper where the box reaches the sheet edge
    im = Image.new("RGB", (r - l + 2 * PAD, b - t + 2 * PAD), (255, 255, 255))
    im.paste(src, (max(0, l - PAD) - (l - PAD), max(0, t - PAD) - (t - PAD)))
    w, h = im.size
    lum = im.convert("L")

    ink = lum.point(lambda v: 255 if v < INK_LUM else 0)
    # close one pixel gaps in the outline
    walls = ink.filter(ImageFilter.MaxFilter(3))

    parts = outlines(walls)
    largest = parts[0][0]
    for i, (count, seed, border) in enumerate(parts):
        if i == 0 or (count >= KEEP_SHARE * largest and not border):
            ImageDraw.floodfill(walls, seed, 200)
    kept = walls.point(lambda v: 255 if v == 200 else 0)

    # outside: flood fill from a corner, then grow back by the closed gap
    ImageDraw.floodfill(kept, (0, 0), 128, thresh=0)
    outside = kept.point(lambda v: 255 if v == 128 else 0)
    drawing = outside.point(lambda v: 0 if v else 255)
    outside = outside.filter(ImageFilter.MaxFilter(3))
    # only ink right next to the drawing counts as its edge
    near = drawing.filter(ImageFilter.MaxFilter(5))

    ramp = lum.point(lambda v: max(0, min(255, (LUM_CLEAR - v) * 255 // (LUM_CLEAR - INK_LUM))))
    alpha = Image.composite(ramp, Image.new("L", (w, h), 255), outside)
    alpha = Image.composite(alpha, Image.new("L", (w, h), 0), near)

    rgb = im.point(lambda v: min(255, v * 255 // PAPER_LUM))
    out = rgb.convert("RGBA")
    out.putalpha(alpha)
    return out.crop(out.getbbox())


def strip(levels):
    """lay out level images side by side, centred vertically."""
    w = sum(im.width for im in levels) + STRIP_GAP * (len(levels) + 1)
    h = max(im.height for im in levels) + 2 * STRIP_GAP
    out = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    x = STRIP_GAP
    for im in levels:
        out.paste(im, (x, (h - im.height) // 2))
        x += im.width + STRIP_GAP
    return out


def main(path):
    sheet = Image.open(path).convert("RGB")
    for name, box in SPRITES.items():
        im = cut(sheet, box)
        im.save(ART / f"{name}.png")
        print(f"{name}: {im.width}x{im.height}")
    for name, boxes in STRIPS.items():
        im = strip([cut(sheet, box) for box in boxes])
        im.save(ART / f"{name}.png")
        print(f"{name}: {im.width}x{im.height}")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: cut_sheet.py SHEET")
    main(sys.argv[1])