"""Cuts the G.R.A.S.S.A. director portrait (a 3D-ish render on black) into South Park style layers: the body with the lower jaw, the upper head that flaps up when he talks (the moustache rides on it), and the dark mouth. Usage: python cut_layers.py """ import sys, os, json import numpy as np from PIL import Image, ImageDraw, ImageFilter from scipy import ndimage src, out = sys.argv[1], sys.argv[2] os.makedirs(out, exist_ok=True) im = Image.open(src).convert("RGB") a = np.asarray(im).astype(np.float32) H, W = a.shape[:2] mx = a.max(2) # background: flood the near-black from the borders lab, _ = ndimage.label(mx <= 10) edge = set(np.unique(np.concatenate([lab[0], lab[-1], lab[:, 0], lab[:, -1]]))) - {0} bg = np.isin(lab, list(edge)) fg = Image.fromarray(np.where(bg, 0, 255).astype(np.uint8), "L").filter(ImageFilter.MinFilter(3)).filter(ImageFilter.GaussianBlur(0.8)) alpha = np.asarray(fg).astype(np.float32) CUT = 528 # straight across the head, just under the middle of the moustache HEAD_TOP, CHIN = 0, 600 # the head's span at the cut row = alpha[CUT] > 128 xs = np.where(row[150:914])[0] + 150 # the head is the run that contains the face middle mid = 520 left = mid while left > 0 and alpha[CUT, left - 1] > 128: left -= 1 right = mid while right < W - 1 and alpha[CUT, right + 1] > 128: right += 1 # moustache: grey, unsaturated, in the box under the nose sat = a.max(2) - a.min(2) box = np.zeros_like(bg) box[455:575, 380:665] = True must = box & (sat < 34) & (mx > 55) & (mx < 200) mimg = Image.fromarray((must * 255).astype(np.uint8), "L").filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.MinFilter(5)).filter(ImageFilter.MaxFilter(3)) must = np.asarray(mimg) > 128 # the upper head: everything of the figure above the cut, between the ears; plus the moustache wherever it hangs yy, xx = np.mgrid[0:H, 0:W] head = (yy < CUT) & (alpha > 0) # the shoulders reach up beside the head? they don't above the cut, but keep the collar out head |= must head_alpha = np.where(head, alpha, 0) # soften the cut edge by one pixel so it doesn't alias body_alpha = np.where(head & ~((yy >= CUT) & ~must), 0, alpha) body_alpha = np.where(must & (yy >= CUT - 2), alpha, body_alpha) # placeholder, refilled below # the skin under the hanging moustache: interpolate each row from the cheeks either side body = a.copy() for y in range(CUT - 2, 575): m = must[y] if not m.any(): continue x = 380 while x < 665: if m[x]: x0 = x while x < 665 and m[x]: x += 1 x1 = x l = body[y, max(0, x0 - 3)] r = body[y, min(W - 1, x1 + 2)] for k in range(x0, x1): t = (k - x0 + 0.5) / max(1, x1 - x0) body[y, k] = l * (1 - t) + r * t else: x += 1 body_alpha = alpha.copy() body_alpha[yy < CUT] = 0 # crop: the bust, 3:4 X0, X1, Y0 = 150, 914, 0 Y1 = Y0 + int((X1 - X0) * 4 / 3) def save(rgb, al, name): rgba = np.dstack([np.clip(rgb, 0, 255), np.clip(al, 0, 255)]).astype(np.uint8)[Y0:Y1, X0:X1] Image.fromarray(rgba, "RGBA").save(os.path.join(out, name)) # the arms: the render stands in a T-pose, so each arm comes off at the shoulder and is hung down at his side, drawn # behind the coat (the game swings it about the shoulder); the coat's shoulders are cut on a slope where the arms were AY0, AY1 = 572, 752 # the rows the outstretched arms cover LCUT, RCUT = 300, 754 # where the sleeves meet the coat's sides LIN, RIN = 390, 664 # how far in the arm layers reach (hidden behind the coat once hung) PIVOTS = ((338, 648), (716, 648)) HANG = 74 # degrees down from straight out band = (yy >= AY0) & (yy <= AY1) neck = yy < 645 arm_masks = (band & (xx < LIN) & ~(neck & (xx >= LCUT)), band & (xx > RIN) & ~(neck & (xx <= RCUT))) off = band & ((xx < LCUT) | (xx > RCUT)) slope = band & (yy < 640) & ((xx < LCUT + (640 - yy) * 0.9) | (xx > RCUT - (640 - yy) * 0.9)) off |= slope & ~((yy < 618) & (xx > LCUT + 60) & (xx < RCUT - 60)) keep = 1.0 - ndimage.gaussian_filter(off.astype(np.float32), 0.8) body_alpha = body_alpha * np.where(off | (keep < 0.999), keep, 1.0) for name, mask, piv, sgn in (("T_Dir_ArmL.png", arm_masks[0], PIVOTS[0], 1), ("T_Dir_ArmR.png", arm_masks[1], PIVOTS[1], -1)): rgba = np.dstack([np.clip(a, 0, 255), np.where(mask, alpha, 0)]).astype(np.uint8) arm = Image.fromarray(rgba, "RGBA").rotate(sgn * HANG, center=piv, resample=Image.BICUBIC) arm.crop((X0, Y0, X1, Y1)).save(os.path.join(out, name)) print(name, "shoulder", ((piv[0] - X0) / (X1 - X0), (piv[1] - Y0) / (Y1 - Y0))) save(body, body_alpha, "T_Dir_Body.png") # the mouth: nothing but a dark void, a little rounded mw, mh = 512, 128 m = Image.new("RGBA", (mw, mh), (0, 0, 0, 0)) d = ImageDraw.Draw(m) d.rounded_rectangle([0, 0, mw - 1, mh - 1], radius=60, fill=(10, 6, 8, 255)) m.save(os.path.join(out, "T_Dir_Mouth.png")) # the eyes: the pupils come off the head (the whites filled in behind them) and are drawn on their own so they can look # about; a lids layer (everything round the whites) goes back over them, so a pupil never shows on skin or glasses eyes = [] head_rgb = a.copy() lids_alpha = np.zeros_like(alpha) for (x0, x1) in ((360, 520), (535, 700)): y0, y1 = 325, 445 sub = a[y0:y1, x0:x1] smx, smn = sub.max(2), sub.min(2) pupil = ndimage.binary_fill_holes(smx < 60) lab, n = ndimage.label(pupil) if n > 1: sizes = ndimage.sum(pupil, lab, range(1, n + 1)) pupil = lab == (1 + int(np.argmax(sizes))) pupil = ndimage.binary_fill_holes(pupil) white = (smn > 160) & ((smx - smn) < 50) sclera = ndimage.binary_closing(white | pupil, iterations=3) sclera = ndimage.binary_fill_holes(sclera) lab, n = ndimage.label(sclera) if n > 1: sizes = ndimage.sum(sclera, lab, range(1, n + 1)) sclera = lab == (1 + int(np.argmax(sizes))) ys, xs = np.where(pupil) cy, cx = ys.mean(), xs.mean() r = max(xs.max() - xs.min(), ys.max() - ys.min()) / 2 + 1 # the whites behind the pupil, row by row from the white either side fill = ndimage.binary_dilation(pupil, iterations=3) & sclera med = np.median(sub[white & ~fill], axis=0) keep = sclera & ~fill for yy_ in range(sub.shape[0]): row = fill[yy_] if not row.any(): continue xs_ = np.where(row)[0] l_, r_ = xs_.min(), xs_.max() # the nearest white either side on this row, so the shade under the lid carries across lk = np.where(keep[yy_, :l_])[0] rk = np.where(keep[yy_, r_ + 1:])[0] cl = sub[yy_, lk[-1]].astype(float) if len(lk) else med cr = sub[yy_, r_ + 1 + rk[0]].astype(float) if len(rk) else med for xx_ in xs_: t_ = (xx_ - l_ + 0.5) / max(1, r_ - l_ + 1) head_rgb[y0 + yy_, x0 + xx_] = cl * (1 - t_) + cr * t_ # soften the patch so no edge shows patch = head_rgb[y0:y1, x0:x1].copy() blur = np.stack([ndimage.gaussian_filter(patch[..., c], 2.0) for c in range(3)], -1) soft = ndimage.gaussian_filter(ndimage.binary_dilation(fill, iterations=2).astype(float), 1.5) head_rgb[y0:y1, x0:x1] = patch * (1 - soft[..., None]) + blur * soft[..., None] region = np.zeros_like(alpha, dtype=bool) region[y0:y1, x0:x1] = True sc_full = np.zeros_like(region) sc_full[y0:y1, x0:x1] = sclera lids_alpha[region & ~sc_full] = alpha[region & ~sc_full] sy, sx = np.where(sclera) eyes.append(dict(cx=x0 + cx, cy=y0 + cy, r=r, box=[x0 + sx.min(), y0 + sy.min(), x0 + sx.max(), y0 + sy.max()])) print("eye", eyes[-1]) # the head without its pupils, and the lids over them save(head_rgb, head_alpha, "T_Dir_Head.png") save(head_rgb, lids_alpha, "T_Dir_Lids.png") # one pupil: a dark ball with its glint up and to the left, like the render P = 128 pi = Image.new("RGBA", (P, P), (0, 0, 0, 0)) d = ImageDraw.Draw(pi) d.ellipse([2, 2, P - 3, P - 3], fill=(22, 18, 22, 255)) d.ellipse([10, 8, P - 18, P - 20], fill=(34, 30, 34, 255)) d.ellipse([int(P * 0.22), int(P * 0.16), int(P * 0.42), int(P * 0.36)], fill=(250, 250, 250, 255)) pi = pi.filter(ImageFilter.SMOOTH) pi.save(os.path.join(out, "T_Dir_Pupil.png")) # skin for the blinking lids lid_colour = np.median(a[322:336, 420:470].reshape(-1, 3), axis=0) cw, ch = X1 - X0, Y1 - Y0 meta = dict(width=cw, height=ch, cut=(CUT - Y0) / ch, mouthLeft=(left + 22 - X0) / cw, mouthRight=(right - 22 - X0) / cw, eyes=[dict(x=(e["cx"] - X0) / cw, y=(e["cy"] - Y0) / ch, r=e["r"] / cw, box=[(e["box"][0] - X0) / cw, (e["box"][1] - Y0) / ch, (e["box"][2] - X0) / cw, (e["box"][3] - Y0) / ch]) for e in eyes], lid=[round(float(c) / 255, 3) for c in lid_colour]) json.dump(meta, open(os.path.join(out, "director.json"), "w"), indent=1) print(meta)