#!/usr/bin/env node // Post-process rembg PNGs to remove the gray halo around the cutout. // // rembg leaves a thin ring of low-alpha pixels at the subject boundary // whose RGB carries the original pigment colour. Composited over a // different bg colour at preview time they show as a gray-brown halo // around the silhouette. // // Strategy: morphological erosion of the alpha channel. Shrinks the // opaque region by ~1 pixel which removes the noisy outer ring while // leaving the bulk of the watercolor / vector body untouched. RGB is // preserved so the visible colour doesn't shift. // // Usage: // node scripts/clean-alpha.mjs [file2.png ...] // // Operates in place. Original is preserved as .pre-clean.bak import fs from 'node:fs'; import path from 'node:path'; import sharp from 'sharp'; // Pixels with alpha below this are nuked outright (the noise ring rembg // leaves around the silhouette). Tune via env if a style needs softer // or harder edges. const FLOOR = Number(process.env.ALPHA_FLOOR || '80'); // How many pixels to erode the alpha mask. 1 is usually enough to wipe // the halo; 2 is stronger for very fluffy / feathered subjects. const ERODE = Number(process.env.ALPHA_ERODE || '1'); async function cleanFile(filePath) { const src = sharp(filePath); const meta = await src.metadata(); if (meta.channels !== 4) { console.error(` ✗ ${path.basename(filePath)}: not RGBA (channels=${meta.channels})`); return; } // 1. Extract alpha + RGB separately so we can manipulate the mask // without touching pigment colour. const rgb = await sharp(filePath).removeAlpha().raw().toBuffer({ resolveWithObject: true }); const alphaRaw = await sharp(filePath).extractChannel('alpha').raw().toBuffer({ resolveWithObject: true }); const a = Buffer.from(alphaRaw.data); // mutable copy // 2. Floor: kill all pixels under FLOOR. Removes the faint noise ring. let killed = 0; for (let i = 0; i < a.length; i++) { if (a[i] < FLOOR) { a[i] = 0; killed++; } } // 3. Erode: for each opaque-ish pixel, look at neighbours; if any // neighbour is transparent, scale down this pixel's alpha. Done // ERODE times. Slim, effective halo trim that keeps the subject's // intended soft edge. const w = alphaRaw.info.width, h = alphaRaw.info.height; let eroded = 0; let work = a; for (let pass = 0; pass < ERODE; pass++) { const next = Buffer.from(work); for (let y = 1; y < h - 1; y++) { for (let x = 1; x < w - 1; x++) { const idx = y * w + x; if (work[idx] === 0) continue; // Min alpha in 3x3 neighbourhood — classic morphological erode let minN = work[idx]; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const n = work[(y + dy) * w + (x + dx)]; if (n < minN) minN = n; } } if (minN < work[idx]) { next[idx] = minN; eroded++; } } } work = next; } // 4. Re-merge cleaned alpha back over the original RGB. const out = Buffer.alloc(w * h * 4); for (let i = 0; i < w * h; i++) { out[i * 4] = rgb.data[i * 3]; out[i * 4 + 1] = rgb.data[i * 3 + 1]; out[i * 4 + 2] = rgb.data[i * 3 + 2]; out[i * 4 + 3] = work[i]; } const bak = filePath + '.pre-clean.bak'; if (!fs.existsSync(bak)) { fs.copyFileSync(filePath, bak); } await sharp(out, { raw: { width: w, height: h, channels: 4 } }).png().toFile(filePath); console.log(` ✓ ${path.basename(filePath)} — floor killed ${killed}, erode trimmed ${eroded} px`); } const files = process.argv.slice(2); if (files.length === 0) { console.error('Usage: node scripts/clean-alpha.mjs [file.png ...]'); process.exit(1); } console.log(`Alpha floor: ${FLOOR}`); for (const f of files) { try { await cleanFile(f); } catch (e) { console.error(` ✗ ${f}: ${e.message}`); } }