import type { RasterMask } from '../types'; export type AutoMaskKind = 'subject' | 'sky' | 'background'; /** * On-device mask estimation for the three selections that matter most in an * event edit: the subject, the sky and the background around the subject. * * The estimator works from a downsampled preview and is deliberately * model-free: there is nothing to download and it runs in a few milliseconds. * It builds a coarse colour histogram of the frame's border (the usual studio, * venue or sky background), scores every pixel against that model plus a centre * prior, splits the score map with an Otsu threshold, then keeps the connected * regions that actually matter and fills interior holes. The result is a * low-resolution raster the normal mask pipeline feathers and scales, and it is * editable like any brush mask, so a missed edge can be fixed by hand. */ export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Promise { const width = Math.max(128, Math.min(384, Math.round(bitmap.width / 12))); const height = Math.max(48, Math.round((width * bitmap.height) / Math.max(1, bitmap.width))); const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d', { willReadFrequently: true }); if (!ctx) throw new Error('Could not analyse the image for a mask'); ctx.drawImage(bitmap, 0, 0, width, height); const image = ctx.getImageData(0, 0, width, height); const mask = segmentMask(image.data, width, height, kind); return { data: encodeBase64(mask), width, height }; } /** * Pure segmentation step, exported so it can be exercised without a canvas. * Returns one byte per pixel: 255 inside the selection, 0 outside. */ export function segmentMask( data: Uint8ClampedArray | Uint8Array, width: number, height: number, kind: AutoMaskKind, ): Uint8Array { const count = width * height; if (!count) return new Uint8Array(0); const border = borderModel(data, width, height); const score = new Float32Array(count); const luma = new Float32Array(count); for (let y = 0; y < height; y++) { const ny = y / Math.max(1, height - 1); for (let x = 0; x < width; x++) { const i = y * width + x; const o = i * 4; const r = data[o] / 255; const g = data[o + 1] / 255; const b = data[o + 2] / 255; const value = 0.2126 * r + 0.7152 * g + 0.0722 * b; luma[i] = value; const maxc = Math.max(r, g, b); const minc = Math.min(r, g, b); const sat = maxc > 0.001 ? (maxc - minc) / maxc : 0; if (kind === 'sky') { // Blue excess, brightness and height above the horizon. A foreground // building keeps a hard edge, which the component pass protects. const blue = Math.max(0, b - (r + g) * 0.5); score[i] = blue * 2.4 + Math.max(0, value - 0.35) * 0.55 + (1 - ny) * 0.42 - sat * 0.18; continue; } // Background probability from the border histogram, softened so a pixel // next to a slightly different bin still reads as background. const bg = border.probability(r, g, b); const centre = 1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2)); const chroma = Math.min( 1, Math.sqrt((r - border.mean[0]) ** 2 + (g - border.mean[1]) ** 2 + (b - border.mean[2]) ** 2) / 1.2, ); // Skin and clothing usually sit near the centre and differ in chroma from // a neutral wall; the histogram alone would eat a white shirt. const subject = (1 - bg) * 0.46 + centre * 0.28 + chroma * 0.17 + sat * 0.09; score[i] = kind === 'background' ? 1 - subject : subject; } } const threshold = otsuThreshold(score); const mask = new Uint8Array(count); for (let i = 0; i < count; i++) mask[i] = score[i] >= threshold ? 255 : 0; keepLargeRegions(mask, width, height); if (kind !== 'background') fillHoles(mask, width, height); smooth(mask, width, height); smooth(mask, width, height); return mask; } interface BorderModel { /** 4×4×4 RGB histogram of the frame's edge, normalised to the fullest bin. */ probability: (r: number, g: number, b: number) => number; mean: [number, number, number]; } function borderModel( data: Uint8ClampedArray | Uint8Array, width: number, height: number, ): BorderModel { const bins = new Float32Array(64); let mr = 0; let mg = 0; let mb = 0; let n = 0; const ring = Math.max(1, Math.round(Math.min(width, height) * 0.03)); const sample = (x: number, y: number) => { const o = (y * width + x) * 4; const r = data[o]; const g = data[o + 1]; const b = data[o + 2]; bins[((r >> 6) << 4) | ((g >> 6) << 2) | (b >> 6)] += 1; mr += r; mg += g; mb += b; n += 1; }; for (let y = 0; y < height; y++) { const edgeRow = y < ring || y >= height - ring; for (let x = 0; x < width; x++) { if (edgeRow || x < ring || x >= width - ring) sample(x, y); } } // Blur the histogram across neighbouring bins: real backgrounds are not // quantised to 64 colours, and a hard lookup would call a wall foreground. const soft = new Float32Array(64); for (let r = 0; r < 4; r++) { for (let g = 0; g < 4; g++) { for (let b = 0; b < 4; b++) { const index = (r << 4) | (g << 2) | b; let total = 0; for (let dr = -1; dr <= 1; dr++) { for (let dg = -1; dg <= 1; dg++) { for (let db = -1; db <= 1; db++) { const rr = r + dr; const gg = g + dg; const bb = b + db; if (rr < 0 || rr > 3 || gg < 0 || gg > 3 || bb < 0 || bb > 3) continue; total += bins[(rr << 4) | (gg << 2) | bb] * (dr === 0 && dg === 0 && db === 0 ? 3 : 1); } } } soft[index] = total; } } } const max = soft.reduce((best, value) => Math.max(best, value), 0) || 1; return { probability: (r, g, b) => { const value = soft[((Math.min(3, r * 4) | 0) << 4) | ((Math.min(3, g * 4) | 0) << 2) | (Math.min(3, b * 4) | 0)]; return Math.min(1, value / max); }, mean: n ? [mr / n / 255, mg / n / 255, mb / n / 255] : [0.5, 0.5, 0.5], }; } /** Otsu split of the score histogram: adapts to flat and busy frames alike. */ export function otsuThreshold(values: Float32Array): number { let min = Infinity; let max = -Infinity; for (let i = 0; i < values.length; i++) { min = Math.min(min, values[i]); max = Math.max(max, values[i]); } if (!Number.isFinite(min) || max - min < 1e-4) return max + 1; const bins = 64; const hist = new Float64Array(bins); for (let i = 0; i < values.length; i++) { const bin = Math.min(bins - 1, Math.floor(((values[i] - min) / (max - min)) * bins)); hist[bin] += 1; } const total = values.length; let sum = 0; for (let i = 0; i < bins; i++) sum += i * hist[i]; let sumB = 0; let wB = 0; let best = 0; let bestVariance = -1; for (let i = 0; i < bins; i++) { wB += hist[i]; if (!wB) continue; const wF = total - wB; if (!wF) break; sumB += i * hist[i]; const mB = sumB / wB; const mF = (sum - sumB) / wF; const variance = wB * wF * (mB - mF) ** 2; if (variance > bestVariance) { bestVariance = variance; best = i; } } // Otsu's split lies between bin `best` and the next: taking the upper edge // puts the threshold above the lower mode rather than inside it. return min + ((best + 1) / bins) * (max - min); } /** Drops specks: keeps every region at least a fifth of the largest one. */ export function keepLargeRegions(mask: Uint8Array, width: number, height: number) { const labels = new Int32Array(mask.length).fill(-1); const sizes: number[] = []; const stack: number[] = []; for (let start = 0; start < mask.length; start++) { if (!mask[start] || labels[start] !== -1) continue; const label = sizes.length; let size = 0; stack.push(start); labels[start] = label; while (stack.length) { const index = stack.pop() as number; size++; const x = index % width; const y = (index - x) / width; const visit = (nx: number, ny: number) => { if (nx < 0 || ny < 0 || nx >= width || ny >= height) return; const next = ny * width + nx; if (!mask[next] || labels[next] !== -1) return; labels[next] = label; stack.push(next); }; visit(x - 1, y); visit(x + 1, y); visit(x, y - 1); visit(x, y + 1); } sizes.push(size); } const largest = sizes.reduce((best, value) => Math.max(best, value), 0); const min = largest * 0.2; for (let i = 0; i < mask.length; i++) { if (!mask[i]) continue; const label = labels[i]; if (label >= 0 && sizes[label] < min) mask[i] = 0; } } /** Fills enclosed background so a subject's face and clothes stay covered. */ export function fillHoles(mask: Uint8Array, width: number, height: number) { const outside = new Uint8Array(mask.length); const stack: number[] = []; const push = (x: number, y: number) => { if (x < 0 || y < 0 || x >= width || y >= height) return; const index = y * width + x; if (mask[index] || outside[index]) return; outside[index] = 1; stack.push(index); }; for (let x = 0; x < width; x++) { push(x, 0); push(x, height - 1); } for (let y = 0; y < height; y++) { push(0, y); push(width - 1, y); } while (stack.length) { const index = stack.pop() as number; const x = index % width; const y = (index - x) / width; push(x - 1, y); push(x + 1, y); push(x, y - 1); push(x, y + 1); } for (let i = 0; i < mask.length; i++) { if (!mask[i] && !outside[i]) mask[i] = 255; } } function smooth(mask: Uint8Array, width: number, height: number) { const copy = new Uint8Array(mask); for (let y = 1; y < height - 1; y++) { for (let x = 1; x < width - 1; x++) { const i = y * width + x; let sum = 0; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) sum += copy[i + dy * width + dx]; } mask[i] = sum / 9 >= 128 ? 255 : 0; } } } function encodeBase64(bytes: Uint8Array): string { let binary = ''; const chunk = 0x8000; for (let i = 0; i < bytes.length; i += chunk) { binary += String.fromCharCode(...bytes.subarray(i, i + chunk)); } return btoa(binary); }