Cotton code
48 lines · 2.2 KB · PythonRaw
#!/usr/bin/env python3"""Pull the magenta key's spill out of a cut-out object.    python3 scripts/gen-tools/despill.py [--threshold N] <tool-x.png> [<tool-y.png> ...]     (in place)`--threshold` (default 35) is how far red AND blue must sit above green for a pixel to count as the key's hue;an object the generator itself tinted (film stock wound on a reel came out aubergine) wants a lower one, and anobject with a real purple in it wants the default left alone.The first sheet of objects was keyed off a flat magenta ground (`cut_sheet.py`), and the key left two thingsbehind: a magenta fringe one or two pixels wide round every edge, and magenta showing THROUGH an object whereverthe ground was visible — a cassette's tape window, a reel's spool, the gap between a key and its tag. Both arethe same colour, so both come out the same way: any pixel whose hue is the key's (red AND blue well above green)has red and blue pulled down to green, which turns the fringe neutral and the see-through magenta into the greyof a shadow. Burgundy (blue near green), red (blue low) and blue (red low) are untouched, which is why a journalcover, a dart and an airmail stripe survive. Pillow + numpy (`/usr/bin/python3`)."""import sysimport numpy as npfrom PIL import ImageTHRESHOLD = 35   # how far red AND blue must sit above green to count as the key's hue (the default)KEEP = 22        # how far above green red and blue may stay — a touch of warmth, never a castdef despill(path, threshold=THRESHOLD):    im = Image.open(path).convert("RGBA")    a = np.asarray(im).astype(np.int16)    r, g, b, alpha = a[..., 0], a[..., 1], a[..., 2], a[..., 3]    key = (r - g > threshold) & (b - g > threshold) & (alpha > 0)    r2, b2 = r.copy(), b.copy()    r2[key] = np.minimum(r[key], g[key] + KEEP)    b2[key] = np.minimum(b[key], g[key] + KEEP)    out = np.dstack([r2, g, b2, alpha]).clip(0, 255).astype(np.uint8)    Image.fromarray(out).save(path)    print(f"{path}: {int(key.sum())} px pulled")if __name__ == "__main__":    args = sys.argv[1:]    threshold = THRESHOLD    if args[:1] == ["--threshold"]:        threshold = int(args[1])        args = args[2:]    if not args:        raise SystemExit(__doc__)    for p in args:        despill(p, threshold)