Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 5 min read

Hybrid WebGPU Segmentation & RGB Color-Keying in Web Workers: 4K Canvas Memory, Counters & Edge Halos

Moving image background removal from a GPU backend into a zero-upload browser runtime is rarely as simple as compiling an ONNX model to WebAssembly. When you execute segmentation entirely inside client-side memoryβ€”withou

Moving image background removal from a GPU backend into a zero-upload browser runtime is rarely as simple as compiling an ONNX model to WebAssembly. When you execute segmentation entirely inside client-side memoryβ€”without transmitting pixel buffers to a serverβ€”three concrete computer-vision and memory-management problems surface immediately:

  1. 4K Activation Buffer Exhaustion: Feeding a raw 12-megapixel (4000Γ—3000) photograph directly into an in-browser segmentation graph allocates hundreds of megabytes of intermediate Float32 tensor activations, triggering tab reloads on mobile browsers with strict per-tab memory ceilings.
  2. Opaque Interior Typographic Counters (O, A, B, P, R): Salient-object neural networks (such as briaai/RMBG-1.4 or ISNet) optimize for outer object silhouettes. On flat vector wordmarks, stamps, or photographed ink signatures, the network frequently treats enclosed background holes inside letters as part of the foreground (alpha = 255).
  3. Semi-Transparent Foreground Contamination (0 < Ξ± < 245): Boundary pixels along hair curls and curved shoulders record an optical linear combination of foreground color $F$ and studio background light $B$: $$C_{\text{observed}} = \alpha F + (1 - \alpha) B$$ Applying an alpha mask directly to $C_{\text{observed}}$ leaves a visible white or chroma halo whenever the cutout is composited over a dark UI or gradient.

To solve all three inside standard TypedArray memory, we open-sourced browser-alpha-matting (MIT), a zero-dependency JavaScript/TypeScript alpha-matting kernel that fuses off-main-thread WebGPU/WASM neural saliency masks with deterministic 3D Euclidean RGB color-keying, separable $O(W \cdot H)$ morphological refinement, and iterative foreground color decontamination.

1. Architecture: Decoupling Proxy Inference from Native 4K Compositing

Instead of downscaling the user's output image (a common shortcut in freemium cloud APIs) or running full-resolution neural inference on the main thread, a browser-native pipeline splits execution across two threads and two coordinate spaces:

Main Thread (HTML5 Canvas / UI @ 60 FPS)          Dedicated Module Web Worker
────────────────────────────────────────          ───────────────────────────
1. Decode source image (e.g. 4000Γ—3000 RGBA)
2. Downsample 1024px proxy buffer
3. Transferable postMessage([rgba.buffer]) ─────► 4. Probe navigator.gpu (WebGPU)
                                                     └─ fallback: multi-thread WASM
                                                  5. Run RMBG-1.4 -> 8-bit proxy alpha
6. Bilinear upsample proxy -> 4000Γ—3000    ◄───── 6. Transferable postMessage([alpha.buffer])
7. Run Euclidean RGB Color-Key pass
8. Fuse masks + Separable Shift/Feather
9. Foreground Color Decontamination -> PNG/WebP

Zero-Copy Transferable Web Worker Bridge

Passing a 16 MB Uint8ClampedArray across postMessage via structured cloning duplicates memory on both heaps. Transferring ownership of the underlying ArrayBuffer keeps IPC overhead near zero:

export function createMattingWorkerBridge(workerUrl) {
  const worker = new Worker(workerUrl, { type: 'module' });
  let nextId = 1;
  const pending = new Map();

  worker.onmessage = ({ data }) => {
    const entry = pending.get(data?.id);
    if (!entry) return;
    pending.delete(data.id);
    if (data.error) entry.reject(new Error(data.error));
    else entry.resolve({ alpha: new Uint8Array(data.alphaBuffer), device: data.device });
  };

  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: () => worker.terminate(),
  };
}

Inside the worker, probing navigator.gpu?.requestAdapter() selects device: 'webgpu' when available and gracefully falls back to device: 'wasm' on older browsers.

2. Hybrid Dual-Engine Mask Fusion: Neural Contours + Euclidean RGB Counters

Saliency networks excel on complex 3D scenesβ€”such as separating a white sneaker from a concrete floorβ€”where color alone fails. Conversely, deterministic 3D Euclidean RGB distance excels at stripping uniform backdrops inside enclosed glyph counters.

First, we compute an 8-bit color-key alpha mask with an inner deadzone tolerance and a linear anti-aliasing ramp softness:

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) 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 {
      alpha[i] = Math.round(srcA * ((Math.sqrt(distSq) - tolerance) * invRamp));
    }
  }
  return alpha;
}

Next, fuseHybridAlpha retains soft neural hair/fur transitions along uncertain outer boundaries while allowing confident color-key zeroing (colorKeyAlpha < 64) to carve out trapped interior holes inside high-confidence regions (neuralAlpha >= 200):

export function fuseHybridAlpha(neuralAlpha, colorKeyAlpha, interiorConfidence = 200) {
  const out = new Uint8Array(neuralAlpha.length);
  for (let i = 0; i < neuralAlpha.length; 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;
}

3. Bilinear Proxy Upsampling & Separable $O(W \cdot H)$ Feathering

Once the 1024px neural alpha mask returns from the Web Worker, upsampleAlphaBilinear maps it back onto the full naturalWidth Γ— naturalHeight grid in pure Uint8Array math without allocating intermediate offscreen DOM canvases.

To smooth stair-stepped mask edges at 4K without paying an $O(W \cdot H \cdot r^2)$ 2D convolution penalty, featherAlphaSeparable runs two iterations of a horizontal + vertical sliding-window accumulator (approximating a Gaussian tent kernel in strict $O(W \cdot H)$ time independent of blur radius $r$):

export function featherAlphaSeparable(alpha, width, height, radiusPx) {
  const r = Math.max(0, Math.round(radiusPx));
  if (r === 0) return new Uint8Array(alpha);

  let src = new Uint8Array(alpha);
  const tmp = new Uint8Array(width * height);
  const dst = new Uint8Array(width * height);
  const kernelSize = 2 * r + 1;

  for (let pass = 0; pass < 2; pass++) {
    for (let y = 0; y < height; y++) {
      const row = y * width;
      let sum = src[row] * (r + 1);
      for (let ix = 1; ix <= r; ix++) sum += src[row + Math.min(width - 1, ix)];
      for (let x = 0; x < width; x++) {
        tmp[row + x] = Math.round(sum / kernelSize);
        sum += src[row + Math.min(width - 1, x + r + 1)] - src[row + Math.max(0, x - r)];
      }
    }
    for (let x = 0; x < width; x++) {
      let sum = tmp[x] * (r + 1);
      for (let iy = 1; iy <= r; iy++) sum += tmp[Math.min(height - 1, iy) * width + x];
      for (let y = 0; y < height; y++) {
        dst[y * width + x] = Math.round(sum / kernelSize);
        sum += tmp[Math.min(height - 1, y + r + 1) * width + x] - tmp[Math.max(0, y - r) * width + x];
      }
    }
    src = new Uint8Array(dst);
  }
  return dst;
}

4. Eliminating White Fringes: Iterative Foreground Color Decontamination

Even an accurate sub-pixel alpha mask exhibits a bright halo on dark backgrounds if boundary RGB values still contain background light. Rather than solving a global Poisson system across 12 million pixels, iterative 8-connected foreground propagation marches pure opaque interior colors (alpha >= 245) outward across 2–4 boundary rings, weighting replacement strength by 1 - alpha / 255:

// Inside each propagation ring for boundary pixels (0 < alpha < 245):
const fgWeight = 1 - a / 255;
out[p]     = Math.round(out[p]     * (1 - fgWeight) + neighborPureR * fgWeight);
out[p + 1] = Math.round(out[p + 1] * (1 - fgWeight) + neighborPureG * fgWeight);
out[p + 2] = Math.round(out[p + 2] * (1 - fgWeight) + neighborPureB * fgWeight);

This keeps 100% of opaque interior pixels bit-identical to the camera source while neutralizing bright studio halos along fine hair strands and anti-aliased edges.

Source Code & Live Browser Sandbox

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.