Offloading Neural Segmentation Without Blocking 60 FPS
Running a saliency segmentation model such as briaai/RMBG-1.4 directly on the browser main thread stalls requestAnimationFrame callbacks, pointer input, and canvas repaints for hundreds of milliseconds per frame. Moving WebGPU and WebAssembly inference into a type: 'module' Web Worker keeps UI rendering responsive at 60 FPS, provided the image payload does not trigger a costly structured-clone copy.
For a 4K image (4000 x 3000 RGBA), a single Uint8ClampedArray occupies 48 MB. By passing [copy.buffer] in the Transferable list of worker.postMessage, ownership of the underlying ArrayBuffer transfers in $O(1)$ time. Creating new Uint8ClampedArray(rgba) isolates the transfer so the caller retains its original pixel buffer even after copy.buffer is detached on the main thread.
export function createMattingWorkerBridge(workerUrl) {
const worker = new Worker(workerUrl, { type: 'module' });
let nextId = 1;
const pending = new Map();
worker.onmessage = (event) => {
const msg = event.data;
if (!msg || !pending.has(msg.id)) return;
const { resolve, reject } = pending.get(msg.id);
pending.delete(msg.id);
if (msg.error) {
reject(new Error(msg.error));
} else {
resolve({
alpha: new Uint8Array(msg.alphaBuffer),
device: msg.device || 'wasm',
});
}
};
worker.onerror = (err) => {
for (const { reject } of pending.values()) {
reject(new Error(err.message || 'Matting Web Worker runtime error'));
}
pending.clear();
};
return {
segmentRgba(rgba, width, height) {
const id = nextId++;
const copy = new Uint8ClampedArray(rgba);
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
worker.postMessage(
{ id, type: 'segment', rgbaBuffer: copy.buffer, width, height },
[copy.buffer]
);
});
},
terminate() {
pending.clear();
worker.terminate();
},
};
}
Decoupling Proxy Inference From Native 4K Resolution
Executing neural inference at native 4K resolution frequently exhausts WebAssembly linear memory or WebGPU staging buffers. Instead, the worker runs briaai/RMBG-1.4 on a fixed proxy tensor (for example 1024 x 1024) and returns a compact 8-bit Uint8Array mask. The main or worker post-processor then restores native dimensions via upsampleAlphaBilinear, sampling pixel centers (x + 0.5) * scaleX - 0.5 with clamped edge coordinates and zero heap allocations per pixel.
export function upsampleAlphaBilinear(proxyAlpha, proxyW, proxyH, targetW, targetH) {
if (proxyW === targetW && proxyH === targetH) {
return new Uint8Array(proxyAlpha);
}
const out = new Uint8Array(targetW * targetH);
const scaleX = proxyW / targetW;
const scaleY = proxyH / targetH;
const maxX = proxyW - 1;
const maxY = proxyH - 1;
for (let y = 0; y < targetH; y++) {
const gy = (y + 0.5) * scaleY - 0.5;
const y0 = gy < 0 ? 0 : gy > maxY ? maxY : gy | 0;
const y1 = y0 < maxY ? y0 + 1 : maxY;
const wy = gy < 0 ? 0 : gy > maxY ? 0 : gy - y0;
const invWy = 1 - wy;
const row0 = y0 * proxyW;
const row1 = y1 * proxyW;
const outRow = y * targetW;
for (let x = 0; x < targetW; x++) {
const gx = (x + 0.5) * scaleX - 0.5;
const x0 = gx < 0 ? 0 : gx > maxX ? maxX : gx | 0;
const x1 = x0 < maxX ? x0 + 1 : maxX;
const wx = gx < 0 ? 0 : gx > maxX ? 0 : gx - x0;
const invWx = 1 - wx;
const top = proxyAlpha[row0 + x0] * invWx + proxyAlpha[row0 + x1] * wx;
const bottom = proxyAlpha[row1 + x0] * invWx + proxyAlpha[row1 + x1] * wx;
out[outRow + x] = Math.round(top * invWy + bottom * wy);
}
}
return out;
}
Recovering Typographic Counters With 3D Euclidean RGB Fusion
Saliency CNNs reliably segment outer object silhouettes, yet they routinely fill enclosed interior background pockets—such as the counters inside O, A, B, P, and R or closed handle cutouts—as solid foreground. Computing a deterministic 3D Euclidean RGB distance mask in extractColorKeyAlpha solves this without retraining the network: pixels within tolerance of the target backdrop [kr, kg, kb] drop to 0, while pixels across [tolerance, tolerance + softness] ramp smoothly using Math.sqrt(distSq) only on transition pixels.
export function extractColorKeyAlpha(rgba, width, height, options = {}) {
const [kr, kg, kb] = options.keyRgb ?? [255, 255, 255];
const tolerance = Math.max(0, Number(options.tolerance ?? 30));
const softness = Math.max(1, Number(options.softness ?? 18));
const totalPixels = width * height;
const alpha = new Uint8Array(totalPixels);
const innerSq = tolerance * tolerance;
const outer = tolerance + softness;
const outerSq = outer * outer;
const invRamp = 1 / softness;
for (let i = 0; i < totalPixels; i++) {
const idx = i * 4;
const srcA = rgba[idx + 3];
if (srcA === 0) {
alpha[i] = 0;
continue;
}
const dr = rgba[idx] - kr;
const dg = rgba[idx + 1] - kg;
const db = rgba[idx + 2] - kb;
const distSq = dr * dr + dg * dg + db * db;
if (distSq <= innerSq) {
alpha[i] = 0;
} else if (distSq >= outerSq) {
alpha[i] = srcA;
} else {
const dist = Math.sqrt(distSq);
const t = (dist - tolerance) * invRamp;
alpha[i] = Math.round(srcA * Math.min(1, Math.max(0, t)));
}
}
return alpha;
}
Finally, fuseHybridAlpha combines both Uint8Array buffers in 'neural-with-counters' mode. Wherever the neural mask is confident inside an object (na >= interiorConfidence, defaulting to 200) while the Euclidean key identifies trapped backdrop (ca < 64), the color-key value carves out the counter; soft neural hair and boundary transitions remain intact everywhere else.
export function fuseHybridAlpha(neuralAlpha, colorKeyAlpha, options = {}) {
if (neuralAlpha.length !== colorKeyAlpha.length) {
throw new RangeError('neuralAlpha and colorKeyAlpha buffers must have identical length');
}
const mode = options.mode ?? 'neural-with-counters';
const interiorConfidence = options.interiorConfidence ?? 200;
const len = neuralAlpha.length;
const out = new Uint8Array(len);
if (mode === 'min') {
for (let i = 0; i < len; i++) {
out[i] = neuralAlpha[i] < colorKeyAlpha[i] ? neuralAlpha[i] : colorKeyAlpha[i];
}
return out;
}
if (mode === 'max') {
for (let i = 0; i < len; i++) {
out[i] = neuralAlpha[i] > colorKeyAlpha[i] ? neuralAlpha[i] : colorKeyAlpha[i];
}
return out;
}
for (let i = 0; i < len; i++) {
const na = neuralAlpha[i];
const ca = colorKeyAlpha[i];
if (na === 0) {
out[i] = 0;
} else if (na >= interiorConfidence && ca < 64) {
out[i] = ca;
} else {
out[i] = na;
}
}
return out;
}
References
- Open-Source Repository (MIT): https://github.com/utilvo/browser-alpha-matting
- Interactive GitHub Pages Demo: https://utilvo.github.io/browser-alpha-matting/
- Live Full-Pipeline Browser Sandbox: https://utilvo.com/background-remover