comparison tools/images.py @ 1:5492efd60e2c

first prototype + updated art sheet
author ark
date 2026-10-18 14:50 +0200
parents
children 910b26feca76
comparison
equal deleted inserted replaced
0:7af9dd4e2595 1:5492efd60e2c
1 """
2 image steps of the build: sprite trimming, tower level strips, map copies.
3
4 all functions take and return pillow images or file paths. no numpy; the
5 per-pixel loops run on crops of a few hundred pixels and stay fast enough.
6 """
7
8 from PIL import Image, ImageDraw, ImageFilter
9
10 # pencil lines in the tower strips are darker than this luminance
11 INK_LUM = 225
12 # light pixels outside a drawing fade from opaque at LUM_OPAQUE to
13 # transparent at LUM_CLEAR, which removes the white paper halo
14 LUM_OPAQUE = 200
15 LUM_CLEAR = 250
16 # gaps in the pencil outline up to about twice this many pixels are closed
17 # before the inside is filled
18 GAP_CLOSE = 2
19
20
21 def trim(im):
22 """return the image cropped to its non-transparent pixels."""
23 box = im.getbbox()
24 return im.crop(box) if box else im
25
26
27 def darken(im, factor):
28 """return a copy with the colour scaled by factor, alpha unchanged."""
29 r, g, b, a = im.split()
30 r, g, b = (c.point(lambda v: int(v * factor)) for c in (r, g, b))
31 return Image.merge("RGBA", (r, g, b, a))
32
33
34 def split_strip(im):
35 """
36 split a strip of drawings side by side at columns without pencil.
37
38 returns a list of crops, left to right. column runs narrower than
39 4 pixels count as specks and are dropped.
40 """
41 w, h = im.size
42 data = im.tobytes()
43 used = [False] * w
44 for y in range(h):
45 row = y * w * 4
46 for x in range(w):
47 i = row + x * 4
48 if data[i + 3] and data[i] + data[i + 1] + data[i + 2] < 3 * INK_LUM:
49 used[x] = True
50 runs = []
51 start = None
52 for x, u in enumerate(used + [False]):
53 if u and start is None:
54 start = x
55 elif not u and start is not None:
56 if x - start > 3:
57 runs.append((start, x))
58 start = None
59 # cut halfway between drawings so nothing of a drawing is lost
60 crops = []
61 for i, (a, b) in enumerate(runs):
62 left = 0 if i == 0 else (runs[i - 1][1] + a) // 2
63 right = w if i == len(runs) - 1 else (b + runs[i + 1][0]) // 2
64 crops.append(im.crop((left, 0, right, h)))
65 return crops
66
67
68 def fill_inside(im):
69 """
70 fill the inside of a pencil outline drawing with white.
71
72 the outside is found by a flood fill from the image border over pixels
73 that are not pencil. outline gaps are closed first by thickening the
74 pencil lines, and the outside is grown back by the same amount
75 afterwards. light pixels outside become transparent. returns a new
76 image, trimmed.
77 """
78 pad = GAP_CLOSE + 2
79 src = Image.new("RGBA", (im.width + 2 * pad, im.height + 2 * pad))
80 src.paste(im, (pad, pad))
81 w, h = src.size
82 data = src.tobytes()
83
84 ink = bytearray(w * h)
85 for i in range(w * h):
86 j = i * 4
87 if data[j + 3] > 64 and data[j] + data[j + 1] + data[j + 2] < 3 * INK_LUM:
88 ink[i] = 255
89 size = 2 * GAP_CLOSE + 1
90 walls = Image.frombytes("L", (w, h), bytes(ink)).filter(ImageFilter.MaxFilter(size))
91
92 # outside: flood fill from a corner, which the padding keeps free
93 ImageDraw.floodfill(walls, (0, 0), 128, thresh=0)
94 outside = walls.point(lambda v: 255 if v == 128 else 0)
95 outside = outside.filter(ImageFilter.MaxFilter(size)).tobytes()
96
97 out = bytearray(w * h * 4)
98 for i in range(w * h):
99 j = i * 4
100 r, g, b, a = data[j:j + 4]
101 lum = (r + g + b) / 3
102 if outside[i]:
103 # fade light pixels out, keep pencil
104 if lum >= LUM_CLEAR:
105 a = 0
106 elif lum > LUM_OPAQUE:
107 a = int(a * (LUM_CLEAR - lum) / (LUM_CLEAR - LUM_OPAQUE))
108 out[j:j + 4] = bytes((r, g, b, a))
109 else:
110 # composite over white
111 k = a / 255
112 out[j:j + 4] = bytes((int(r * k + 255 * (1 - k)),
113 int(g * k + 255 * (1 - k)),
114 int(b * k + 255 * (1 - k)), 255))
115 return trim(Image.frombytes("RGBA", (w, h), bytes(out)))
116
117
118 def tower_levels(path):
119 """return the four level images (levels 2-5) of a t*p strip."""
120 strip = Image.open(path).convert("RGBA")
121 levels = [fill_inside(c) for c in split_strip(strip)]
122 if len(levels) != 4:
123 raise ValueError(f"{path}: found {len(levels)} drawings, expected 4")
124 return levels
125
126
127 def map_copy(src, dst, quality):
128 """write the map scan as jpeg. maps are opaque, so nothing is lost."""
129 im = Image.open(src)
130 if im.mode == "RGBA" and im.getextrema()[3][0] < 255:
131 raise ValueError(f"{src}: map has transparent pixels, jpeg would lose them")
132 im.convert("RGB").save(dst, quality=quality, optimize=True)