Branchwell

Lumen & Gesso / website / scripts / clean-alpha.mjs

1#!/usr/bin/env node
2// Post-process rembg PNGs to remove the gray halo around the cutout.
3//
4// rembg leaves a thin ring of low-alpha pixels at the subject boundary
5// whose RGB carries the original pigment colour. Composited over a
6// different bg colour at preview time they show as a gray-brown halo
7// around the silhouette.
8//
9// Strategy: morphological erosion of the alpha channel. Shrinks the
10// opaque region by ~1 pixel which removes the noisy outer ring while
11// leaving the bulk of the watercolor / vector body untouched. RGB is
12// preserved so the visible colour doesn't shift.
13//
14// Usage:
15// node scripts/clean-alpha.mjs <file1.png> [file2.png ...]
16//
17// Operates in place. Original is preserved as <file>.pre-clean.bak
18
19import fs from 'node:fs';
20import path from 'node:path';
21import sharp from 'sharp';
22
23// Pixels with alpha below this are nuked outright (the noise ring rembg
24// leaves around the silhouette). Tune via env if a style needs softer
25// or harder edges.
26const FLOOR = Number(process.env.ALPHA_FLOOR || '80');
27// How many pixels to erode the alpha mask. 1 is usually enough to wipe
28// the halo; 2 is stronger for very fluffy / feathered subjects.
29const ERODE = Number(process.env.ALPHA_ERODE || '1');
30
31async function cleanFile(filePath) {
32 const src = sharp(filePath);
33 const meta = await src.metadata();
34 if (meta.channels !== 4) {
35 console.error(` ✗ ${path.basename(filePath)}: not RGBA (channels=${meta.channels})`);
36 return;
37 }
38
39 // 1. Extract alpha + RGB separately so we can manipulate the mask
40 // without touching pigment colour.
41 const rgb = await sharp(filePath).removeAlpha().raw().toBuffer({ resolveWithObject: true });
42 const alphaRaw = await sharp(filePath).extractChannel('alpha').raw().toBuffer({ resolveWithObject: true });
43
44 const a = Buffer.from(alphaRaw.data); // mutable copy
45
46 // 2. Floor: kill all pixels under FLOOR. Removes the faint noise ring.
47 let killed = 0;
48 for (let i = 0; i < a.length; i++) {
49 if (a[i] < FLOOR) { a[i] = 0; killed++; }
50 }
51
52 // 3. Erode: for each opaque-ish pixel, look at neighbours; if any
53 // neighbour is transparent, scale down this pixel's alpha. Done
54 // ERODE times. Slim, effective halo trim that keeps the subject's
55 // intended soft edge.
56 const w = alphaRaw.info.width, h = alphaRaw.info.height;
57 let eroded = 0;
58 let work = a;
59 for (let pass = 0; pass < ERODE; pass++) {
60 const next = Buffer.from(work);
61 for (let y = 1; y < h - 1; y++) {
62 for (let x = 1; x < w - 1; x++) {
63 const idx = y * w + x;
64 if (work[idx] === 0) continue;
65 // Min alpha in 3x3 neighbourhood — classic morphological erode
66 let minN = work[idx];
67 for (let dy = -1; dy <= 1; dy++) {
68 for (let dx = -1; dx <= 1; dx++) {
69 const n = work[(y + dy) * w + (x + dx)];
70 if (n < minN) minN = n;
71 }
72 }
73 if (minN < work[idx]) { next[idx] = minN; eroded++; }
74 }
75 }
76 work = next;
77 }
78
79 // 4. Re-merge cleaned alpha back over the original RGB.
80 const out = Buffer.alloc(w * h * 4);
81 for (let i = 0; i < w * h; i++) {
82 out[i * 4] = rgb.data[i * 3];
83 out[i * 4 + 1] = rgb.data[i * 3 + 1];
84 out[i * 4 + 2] = rgb.data[i * 3 + 2];
85 out[i * 4 + 3] = work[i];
86 }
87
88 const bak = filePath + '.pre-clean.bak';
89 if (!fs.existsSync(bak)) {
90 fs.copyFileSync(filePath, bak);
91 }
92 await sharp(out, { raw: { width: w, height: h, channels: 4 } }).png().toFile(filePath);
93 console.log(` ✓ ${path.basename(filePath)} — floor killed ${killed}, erode trimmed ${eroded} px`);
94}
95
96const files = process.argv.slice(2);
97if (files.length === 0) {
98 console.error('Usage: node scripts/clean-alpha.mjs <file.png> [file.png ...]');
99 process.exit(1);
100}
101console.log(`Alpha floor: ${FLOOR}`);
102for (const f of files) {
103 try {
104 await cleanFile(f);
105 } catch (e) {
106 console.error(` ✗ ${f}: ${e.message}`);
107 }
108}