#!/usr/bin/env python3
"""Cut the six blank card faces out of their generations and write the imagesets.
python3 scripts/gen-cards/export_card_faces.py --faces
.png>
The generations come from `make_card_faces.py` — one master and six edits of it,
each a single blank aged card lying on a flat magenta ground. This takes each
one, cuts the card off the ground, corrects the panel to the stock's authored
colour, and writes `apps/loom/Sources/CottonPaper/Media.xcassets/stock-.imageset`
at 480 x 640 @2x.
**Why the card is cut on ALPHA and not clipped in SwiftUI.** The card's edge is
worn, bumped and very slightly frayed — that edge is the single detail that says
"a photograph of a card" rather than "a rounded rectangle". A `RoundedRectangle`
clip in SwiftUI would cut it off straight. So the ground is keyed here, once,
and the app draws the PNG as it is.
**Why the panel colour is corrected here and not asked for in the prompt.** It
was asked for, twice, with hexes in the prompt, and the model answered a salmon
rose and an olive grey both times: an image model does not take a colour
instruction as a constraint. The six stocks have to read as one run of quiet
paper against the plaster — a saturated one fights the ground, which is the note
the owner sent the drawn cards back with — so the tint is the one thing decided
here rather than there. The correction is a per-channel gain over the PANEL
only, masked well inside the ivory rim: it re-papers the panel without touching
the rim, the printed frame's contrast, the foxing, the vignette or the worn
edge, all of which are the photograph's and stay the photograph's.
**Where the six colours live.** In `TINTS` below, and nowhere else. They were
sampled off the owner's own reference sheet (the panel of Todos, Calendar,
Messages, Photos, Locations and News). They are not palette tokens: a stock is
baked into its photograph exactly as a project cap's enamel is baked into
`cap-red.png`, and a token nothing reads at runtime is noise. `ToolCardTint`
names the ASSET; the colour is in the pixels.
Needs Pillow + numpy (`python3 -m pip install --break-system-packages pillow numpy`).
"""
import argparse
import json
import pathlib
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
ROOT = pathlib.Path(__file__).resolve().parents[2]
CATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"
# The six stocks, sampled off the owner's reference sheet. Quiet, aged, and far
# enough apart that no two tools read as the same paper — `ToolCardTintTests`
# holds the map that decides which tool gets which.
TINTS = {
"cream": "#E6D2B6",
"sage": "#B5B294",
"rose": "#D8B3A0",
"slate": "#A6B2BA",
"tan": "#D9BB96",
"grey": "#C4BBAE",
}
SIDE = (480, 640) # 3:4, the reference sheet's own proportion; @2x that is a 240 x 320 pt
# face, and the widest card the app draws is under 130 pt
# 2x, the scale every other imageset in this catalogue is written at. The card
# is always drawn `.resizable()` into an explicit frame, so the declared scale
# only decides the picture's intrinsic POINT size; matching the catalogue keeps
# one convention rather than two.
SCALE = 2
# The panel mask, as a fraction of card width. Wide enough to stay clear of the
# ivory rim: a gain that reaches the rim turns a bright ivory pixel the tint's
# own hue, which showed up as a mint-green ring around the rose card.
MARGIN = 0.075
# Where the panel's own colour is measured — well inside the printed frame, so
# neither the frame nor the rim drags the average.
SAMPLE = 0.20
# How far a channel may be pushed. A stock that needed more than this is a
# generation to redo, not a number to stretch.
GAIN_RANGE = (0.6, 1.6)
# How many pixels of the keyed edge are thrown away, at the generation's own
# resolution. Odd, because `MinFilter` wants an odd window.
ERODE = 7
# Where the ground's hue ends and the card's begins — green as a fraction of
# red. The card's own darkest pixel is a brown edge at about 0.68.
GROUND_HUE = 0.55
def cut(path: pathlib.Path) -> tuple[Image.Image, Image.Image]:
"""The card, off its ground, by distance from the ground's own colour."""
image = Image.open(path).convert("RGB")
pixels = np.asarray(image).astype(float)
border = np.concatenate([
pixels[:8].reshape(-1, 3), pixels[-8:].reshape(-1, 3),
pixels[:, :8].reshape(-1, 3), pixels[:, -8:].reshape(-1, 3),
])
ground = np.median(border, axis=0)
distance = np.sqrt(((pixels - ground) ** 2).sum(axis=2))
alpha = np.clip((distance - 45) / 45.0, 0, 1)
# The card CASTS A SHADOW on the ground, and a shadow is far from the
# ground's colour, so distance alone calls that shadow "card" and the cut
# comes away with a dark maroon skirt under it. A shadow of a crimson ground
# is still crimson-HUED, and nothing on an aged card is: the darkest thing
# on one is a worn brown edge, whose green sits around two thirds of its
# red. So anything whose green falls below `GROUND_HUE` of its red is the
# ground, lit or unlit, and is not the card.
red, green = pixels[..., 0], pixels[..., 1]
alpha[(green < red * GROUND_HUE) & (red > 5)] = 0
ys, xs = np.where(alpha > 0.5)
box = (xs.min(), ys.min(), xs.max() + 1, ys.max() + 1)
pixels = pixels[box[1]:box[3], box[0]:box[2]]
alpha = alpha[box[1]:box[3], box[0]:box[2]]
# ERODE rather than despill, and erode HARD: the keyed ring two or three
# pixels wide still carries the ground's colour, and on a crimson ground
# pulling it toward neutral turns it green. A soft threshold is not enough
# — it keeps those pixels at a lower alpha and their colour with them,
# which drew a maroon line down the right edge of every card on the phone.
# So the mask is shrunk by `ERODE` pixels and then feathered by one, which
# costs a pixel of a worn edge and nothing else.
mask = Image.fromarray((alpha * 255).astype(np.uint8))
mask = mask.filter(ImageFilter.MinFilter(ERODE)).filter(ImageFilter.GaussianBlur(radius=1))
alpha = np.asarray(mask).astype(float) / 255
# Flood what is OUTSIDE the card with the card's own colour before the
# resize. The ground is still in those pixels, and a Lanczos kernel at the
# boundary mixes it back in whatever the alpha says — which put a
# near-black line along the bottom edge of the sage and cream cards on the
# phone. Filling first means the only thing the kernel can mix is card.
fill = np.median(pixels[alpha > 0.9], axis=0)
pixels = pixels * alpha[..., None] + fill[None, None, :] * (1 - alpha[..., None])
card = Image.fromarray(pixels.round().clip(0, 255).astype(np.uint8)).resize(SIDE, Image.LANCZOS)
return card, Image.fromarray((alpha * 255).astype(np.uint8)).resize(SIDE, Image.LANCZOS)
def mask(inset: float) -> np.ndarray:
"""A feathered rounded rectangle inset by `inset` of the card's width."""
width, height = SIDE
edge = int(round(width * inset))
shape = Image.new("L", SIDE, 0)
ImageDraw.Draw(shape).rounded_rectangle(
[edge, edge, width - 1 - edge, height - 1 - edge], radius=int(width * 0.075), fill=255
)
return np.asarray(shape.filter(ImageFilter.GaussianBlur(radius=width * 0.004))).astype(float) / 255
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--faces", required=True, help="a directory of face-.png")
arguments = parser.parse_args()
faces = pathlib.Path(arguments.faces)
panel, sample = mask(MARGIN), mask(SAMPLE)
for tint, target in TINTS.items():
card, alpha = cut(faces / f"face-{tint}.png")
pixels = np.asarray(card).astype(float)
measured = (pixels * sample[..., None]).sum(axis=(0, 1)) / sample.sum()
wanted = np.array([int(target[i:i + 2], 16) for i in (1, 3, 5)], float)
gain = np.clip(wanted / np.maximum(measured, 1), *GAIN_RANGE)
field = 1.0 + (gain[None, None, :] - 1.0) * panel[..., None]
out = Image.fromarray(np.clip(pixels * field, 0, 255).round().astype(np.uint8))
out.putalpha(alpha)
name = f"stock-{tint}"
folder = CATALOGUE / f"{name}.imageset"
folder.mkdir(parents=True, exist_ok=True)
out.save(folder / f"{name}.png", "PNG", optimize=True)
(folder / "Contents.json").write_text(
json.dumps(
{
"images": [{"filename": f"{name}.png", "idiom": "universal", "scale": f"{SCALE}x"}],
"info": {"author": "xcode", "version": 1},
},
indent=2,
)
+ "\n"
)
size = (folder / f"{name}.png").stat().st_size
print(f"{name}: {SIDE[0]}x{SIDE[1]} @{SCALE}x {size / 1024:.0f} KB "
f"panel {'#%02X%02X%02X' % tuple(measured.round().astype(int))} → {target}")
if __name__ == "__main__":
main()