#!/usr/bin/env python3 """cut_sheet.py name1 name2 ... Keys out a flat magenta ground, splits into cells (reading order), trims each object on alpha, pads 6%, centres on a transparent 600x600 square, writes /tool-.png. """ import sys, numpy as np from PIL import Image sheet, cols, rows, out = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4] names = sys.argv[5:] im = Image.open(sheet).convert("RGB") a = np.asarray(im).astype(np.int16) r, g, b = a[..., 0], a[..., 1], a[..., 2] # magenta-ness: high r and b, low g. soft key with despill. key = (r - g).clip(0, 255) + (b - g).clip(0, 255) # 0..510 alpha = np.clip((360 - key) / 120.0, 0, 1) # fully opaque below 240, transparent above 360 alpha = (alpha * 255).astype(np.uint8) rgb = a.copy() # despill: pull magenta fringe toward neutral where alpha is partial spill = (alpha < 255) rgb[..., 0][spill] = np.minimum(rgb[..., 0][spill], (g[spill] + 40)) rgb[..., 2][spill] = np.minimum(rgb[..., 2][spill], (g[spill] + 40)) rgba = np.dstack([rgb.clip(0, 255).astype(np.uint8), alpha]) H, W = alpha.shape cw, ch = W / cols, H / rows i = 0 for ry in range(rows): for cx in range(cols): if i >= len(names): break cell = rgba[int(ry*ch):int((ry+1)*ch), int(cx*cw):int((cx+1)*cw)] m = cell[..., 3] > 200 # keep only the band of rows / columns that contains the largest object: drop bleed from neighbouring cells def band(mask_1d, centre): runs=[]; start=None for k,v in enumerate(mask_1d): if v and start is None: start=k if not v and start is not None: runs.append((start,k)); start=None if start is not None: runs.append((start,len(mask_1d))) if not runs: return None return max(runs, key=lambda r: r[1]-r[0]) rb = band((m.sum(axis=1) > 0), None) if rb: keep = np.zeros_like(m); keep[rb[0]:rb[1], :] = True; m &= keep cb = band((m.sum(axis=0) > 0), None) if cb: keep = np.zeros_like(m); keep[:, cb[0]:cb[1]] = True; m &= keep cell = cell.copy(); cell[..., 3][~m & (cell[..., 3] > 0)] = 0 if m.sum() < 500: print("EMPTY", names[i]); i += 1; continue ys, xs = np.where(m) y0, y1, x0, x1 = ys.min(), ys.max()+1, xs.min(), xs.max()+1 obj = Image.fromarray(cell[y0:y1, x0:x1]) w, h = obj.size side = int(max(w, h) * 1.12) canvas = Image.new("RGBA", (side, side), (0, 0, 0, 0)) canvas.paste(obj, ((side - w)//2, (side - h)//2), obj) canvas = canvas.resize((600, 600), Image.LANCZOS) canvas.save(f"{out}/tool-{names[i]}.png") print("wrote", names[i], w, h) i += 1