/** * Traditional (non-learned) image segmentation. * * This file is the "classic computer vision" baseline for the mini-lab. Nothing * here is trained on data: every decision comes from pixel statistics. That is * exactly the point of the experiment — students can see where a purely * hand-designed rule succeeds and where it falls apart. * * Implemented methods: * - global binary threshold with a manual cutoff * - Otsu's method (automatic cutoff from the histogram) * - adaptive local-mean threshold (handles uneven lighting) * followed by optional morphological cleanup and connected-component labelling. */ /** Rec. 601 luminance, the standard greyscale conversion. */ export function toGrayscale(imageData) { const { data, width, height } = imageData; const gray = new Uint8ClampedArray(width * height); for (let i = 0, p = 0; i < gray.length; i++, p += 4) { gray[i] = (data[p] * 0.299 + data[p + 1] * 0.587 + data[p + 2] * 0.114) | 0; } return gray; } export function buildHistogram(gray) { const histogram = new Uint32Array(256); for (let i = 0; i < gray.length; i++) histogram[gray[i]]++; return histogram; } /** * Otsu's method: pick the threshold that maximises between-class variance. * Equivalent to minimising the weighted sum of the two class variances. * * A perfectly bimodal histogram has a whole plateau of thresholds with the same * variance. Reporting the middle of that plateau rather than its first value * keeps the cutoff away from the noise of the lower mode. */ export function otsuThreshold(histogram, total) { let sum = 0; for (let t = 0; t < 256; t++) sum += t * histogram[t]; let sumBackground = 0; let weightBackground = 0; let bestVariance = -1; let plateauLow = 0; let plateauHigh = 0; for (let t = 0; t < 256; t++) { weightBackground += histogram[t]; if (weightBackground === 0) continue; const weightForeground = total - weightBackground; if (weightForeground === 0) break; sumBackground += t * histogram[t]; const meanBackground = sumBackground / weightBackground; const meanForeground = (sum - sumBackground) / weightForeground; const delta = meanBackground - meanForeground; // Between-class variance, scaled by the class weights. const variance = weightBackground * weightForeground * delta * delta; if (variance > bestVariance + 1e-9) { bestVariance = variance; plateauLow = t; plateauHigh = t; } else if (Math.abs(variance - bestVariance) <= 1e-9) { plateauHigh = t; } } return Math.round((plateauLow + plateauHigh) / 2); } /** Mean grey value inside a clamped window, using a summed-area table. */ function buildIntegral(gray, width, height) { const integral = new Uint32Array((width + 1) * (height + 1)); for (let y = 0; y < height; y++) { let rowSum = 0; for (let x = 0; x < width; x++) { rowSum += gray[y * width + x]; integral[(y + 1) * (width + 1) + (x + 1)] = integral[y * (width + 1) + (x + 1)] + rowSum; } } return integral; } /** * Adaptive thresholding: compare each pixel with the mean of its local window. * Unlike a global cutoff this survives a lighting gradient, which is why it was * the workhorse of document scanning long before learned segmentation. */ export function adaptiveThreshold(gray, width, height, blockSize, constant) { const integral = buildIntegral(gray, width, height); const stride = width + 1; const radius = Math.max(1, Math.floor(blockSize / 2)); const mask = new Uint8Array(width * height); for (let y = 0; y < height; y++) { const y0 = Math.max(0, y - radius); const y1 = Math.min(height - 1, y + radius); for (let x = 0; x < width; x++) { const x0 = Math.max(0, x - radius); const x1 = Math.min(width - 1, x + radius); const area = (x1 - x0 + 1) * (y1 - y0 + 1); const sum = integral[(y1 + 1) * stride + (x1 + 1)] - integral[y0 * stride + (x1 + 1)] - integral[(y1 + 1) * stride + x0] + integral[y0 * stride + x0]; mask[y * width + x] = gray[y * width + x] > sum / area - constant ? 1 : 0; } } return mask; } /** * 3x3 dilation: a pixel survives if any neighbour in the window is foreground. */ function dilate(mask, width, height) { const out = new Uint8Array(mask.length); for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let hit = 0; for (let dy = -1; dy <= 1 && !hit; dy++) { const ny = y + dy; if (ny < 0 || ny >= height) continue; for (let dx = -1; dx <= 1; dx++) { const nx = x + dx; if (nx < 0 || nx >= width) continue; if (mask[ny * width + nx]) { hit = 1; break; } } } out[y * width + x] = hit; } } return out; } /** * 3x3 erosion: a pixel survives only if every neighbour in the window is * foreground. Out-of-frame neighbours are ignored rather than treated as * background, so blobs touching the border are not shaved off. */ function erode(mask, width, height) { const out = new Uint8Array(mask.length); for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let keep = 1; for (let dy = -1; dy <= 1 && keep; dy++) { const ny = y + dy; if (ny < 0 || ny >= height) continue; for (let dx = -1; dx <= 1; dx++) { const nx = x + dx; if (nx < 0 || nx >= width) continue; if (!mask[ny * width + nx]) { keep = 0; break; } } } out[y * width + x] = keep; } } return out; } /** * Morphological opening followed by closing: the opening deletes specks the * threshold invented, the closing fills pinholes inside real objects. * Classic segmentation almost always needs this manual cleanup step — a detail * the learned models handle implicitly. */ export function denoiseMask(mask, width, height) { const opened = dilate(erode(mask, width, height), width, height); return erode(dilate(opened, width, height), width, height); } /** * Two-pass connected-component labelling (union-find, 8-connectivity). * * Returns `components` sorted by area, largest first, plus the `labels` map so * callers can paint each blob in its own colour — the same per-region view the * learned models get, rather than a bounding box. */ export function labelComponents(mask, width, height, minArea = 1) { const labels = new Int32Array(width * height).fill(-1); const parent = []; const find = (a) => { while (parent[a] !== a) { parent[a] = parent[parent[a]]; a = parent[a]; } return a; }; const union = (a, b) => { const ra = find(a); const rb = find(b); if (ra !== rb) parent[rb] = ra; }; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const i = y * width + x; if (!mask[i]) continue; const neighbours = []; if (x > 0 && labels[i - 1] >= 0) neighbours.push(labels[i - 1]); if (y > 0) { if (labels[i - width] >= 0) neighbours.push(labels[i - width]); if (x > 0 && labels[i - width - 1] >= 0) neighbours.push(labels[i - width - 1]); if (x < width - 1 && labels[i - width + 1] >= 0) neighbours.push(labels[i - width + 1]); } if (neighbours.length === 0) { labels[i] = parent.length; parent.push(parent.length); } else { const smallest = Math.min(...neighbours); labels[i] = smallest; for (const n of neighbours) union(smallest, n); } } } // Second pass: resolve every pixel to its root label and gather statistics. const stats = new Map(); for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const i = y * width + x; if (labels[i] < 0) continue; const root = find(labels[i]); labels[i] = root; let entry = stats.get(root); if (!entry) { entry = { label: root, area: 0, xmin: x, ymin: y, xmax: x, ymax: y, sumX: 0, sumY: 0 }; stats.set(root, entry); } entry.area++; entry.sumX += x; entry.sumY += y; if (x < entry.xmin) entry.xmin = x; if (y < entry.ymin) entry.ymin = y; if (x > entry.xmax) entry.xmax = x; if (y > entry.ymax) entry.ymax = y; } } const components = [...stats.values()] .filter((component) => component.area >= minArea) .map((component) => ({ ...component, cx: component.sumX / component.area, cy: component.sumY / component.area, })) .sort((a, b) => b.area - a.area); return { components, labels }; } /** * Run the whole classic pipeline for one image. * * @returns {{mask: Uint8Array, labels: Int32Array, threshold: number, * foreground: number, components: object[], * histogram: Uint32Array, method: string}} */ export function runThreshold(imageData, options = {}) { const method = options.method || 'otsu'; const { width, height } = imageData; const gray = toGrayscale(imageData); const histogram = buildHistogram(gray); const total = width * height; let mask; let threshold; if (method === 'adaptive') { const blockSize = options.blockSize ?? 35; const constant = options.constant ?? 10; mask = adaptiveThreshold(gray, width, height, blockSize, constant); // Report the equivalent global cutoff so the slider still means something. threshold = otsuThreshold(histogram, total); } else { threshold = method === 'otsu' ? otsuThreshold(histogram, total) : Math.round(options.threshold ?? 128); mask = new Uint8Array(total); for (let i = 0; i < total; i++) mask[i] = gray[i] > threshold ? 1 : 0; } if (options.invert) { for (let i = 0; i < mask.length; i++) mask[i] = mask[i] ? 0 : 1; } if (options.denoise) { mask = denoiseMask(mask, width, height); } let foreground = 0; for (let i = 0; i < mask.length; i++) foreground += mask[i]; // Ignore specks: anything under 0.05% of the frame is noise, not an object. const minArea = Math.max(1, Math.round(total * 0.0005)); const { components, labels } = labelComponents(mask, width, height, minArea); return { mask, labels, threshold, foreground, components, histogram, method }; }