learnANDlive's picture
Upload folder using huggingface_hub
15daaf3 verified
Raw History Blame Contribute Delete
36.8 kB
import { EXPERIMENTS, getExperiment, colorForIndex, runSemantic, runInstance, prepareSam, segmentWithPoint, } from './segmenter.js'; import { runThreshold, toGrayscale, buildHistogram, otsuThreshold } from './classic.js'; /* ------------------------------------------------------------------ * * DOM * ------------------------------------------------------------------ */ const imageInput = document.querySelector('#image-input'); const experimentGrid = document.querySelector('#experiment-grid'); const experimentBlurb = document.querySelector('#experiment-blurb'); const experimentNote = document.querySelector('#experiment-note'); const runButton = document.querySelector('#run-button'); const statusEl = document.querySelector('#status'); const progressWrap = document.querySelector('#progress-wrap'); const progressBar = document.querySelector('#progress-bar'); const canvasWrap = document.querySelector('#canvas-wrap'); const canvas = document.querySelector('#result-canvas'); const viewSwitch = document.querySelector('#view-switch'); const ctx = canvas.getContext('2d', { willReadFrequently: true }); const samHint = document.querySelector('#sam-hint'); const summary = document.querySelector('#summary'); const tableHead = document.querySelector('#table-head'); const tbody = document.querySelector('#detections-body'); const runtimeBadge = document.querySelector('#runtime-badge'); const resultKicker = document.querySelector('#result-kicker'); const resultTitle = document.querySelector('#result-title'); const sampleGrid = document.querySelector('#sample-grid'); const shuffleButton = document.querySelector('#shuffle-examples'); const compareGrid = document.querySelector('#compare-grid'); const clearCompareButton = document.querySelector('#clear-compare'); const panels = { threshold: document.querySelector('#panel-threshold'), segformer: document.querySelector('#panel-segformer'), maskformer: document.querySelector('#panel-maskformer'), sam: document.querySelector('#panel-sam'), }; const thresholdMethod = document.querySelector('#threshold-method'); const thresholdManual = document.querySelector('#threshold-manual'); const thresholdAdaptive = document.querySelector('#threshold-adaptive'); const cutoff = document.querySelector('#cutoff'); const cutoffValue = document.querySelector('#cutoff-value'); const blockSize = document.querySelector('#block-size'); const blockSizeValue = document.querySelector('#block-size-value'); const adaptiveC = document.querySelector('#adaptive-c'); const adaptiveCValue = document.querySelector('#adaptive-c-value'); const invert = document.querySelector('#invert'); const denoise = document.querySelector('#denoise'); const histogramCanvas = document.querySelector('#histogram'); const confidence = document.querySelector('#confidence'); const confidenceValue = document.querySelector('#confidence-value'); /* ------------------------------------------------------------------ * * Examples * ------------------------------------------------------------------ */ const EXAMPLES = [ { src: './examples/000000039769.jpg', label: 'Two cats on a couch' }, { src: './examples/000000189806.jpg', label: 'Cat and dog indoors' }, { src: './examples/000000010092.jpg', label: 'Bedroom interior' }, { src: './examples/000000037777.jpg', label: 'Kitchen counter' }, { src: './examples/000000210520.jpg', label: 'Dining table' }, { src: './examples/000000397133.jpg', label: 'Busy kitchen' }, { src: './examples/000000167898.jpg', label: 'Bathroom fixtures' }, { src: './examples/000000376310.jpg', label: 'Bathroom objects' }, { src: './examples/000000252219.jpg', label: 'Street scene' }, { src: './examples/000000174482.jpg', label: 'Bicycle in traffic' }, { src: './examples/000000482978.jpg', label: 'Passenger train' }, { src: './examples/000000090208.jpg', label: 'Double-decker buses' }, { src: './examples/000000517523.jpg', label: 'Airplane on approach' }, { src: './examples/000000570448.jpg', label: 'Boat at the shore' }, { src: './examples/000000431876.jpg', label: 'Horses and riders' }, { src: './examples/000000199442.jpg', label: 'Surfer on a wave' }, { src: './examples/000000097278.jpg', label: 'Snowboarder' }, { src: './examples/000000500270.jpg', label: 'Skateboarder mid-trick' }, { src: './examples/000000286458.jpg', label: 'Packed suitcase' }, { src: './examples/000000429281.jpg', label: 'Bananas at a market' }, { src: './examples/000000365886.jpg', label: 'Person with a phone' }, { src: './examples/000000181666.jpg', label: 'Herd in a field' }, { src: './examples/000000087038.jpg', label: 'Skate park' }, { src: './examples/000000063965.jpg', label: 'Cake and person' }, ]; /* ------------------------------------------------------------------ * * State * ------------------------------------------------------------------ */ /** Longest side of the working copy. Keeps every method responsive. */ const WORKING_MAX_SIDE = 768; /** Regions below this share of the frame are noise, not segments. */ const MIN_COVERAGE = 0.004; const MAX_LABELS = 14; const MAX_ROWS = 40; const state = { image: null, working: null, // { canvas, width, height, dataUrl } histogram: null, otsu: null, experiment: EXPERIMENTS[0].key, view: 'overlay', // 'overlay' | 'mask' | 'original' samHandle: null, samResult: null, busy: false, }; const compareEntries = new Map(); /** The last result drawn, kept so the view switch never re-runs a model. */ let lastDraw = null; /* ------------------------------------------------------------------ * * Small helpers * ------------------------------------------------------------------ */ function chooseRandom(items, count) { return [...items] .map((item) => ({ item, sort: Math.random() })) .sort((a, b) => a.sort - b.sort) .slice(0, count) .map(({ item }) => item); } function setBadge(text, mode = '') { runtimeBadge.textContent = text; runtimeBadge.className = `badge ${mode}`.trim(); } function setProgress(data) { let pct = null; if (typeof data?.progress === 'number') { pct = data.progress; } else if (data?.total && typeof data?.loaded === 'number') { pct = (data.loaded / data.total) * 100; } if (pct !== null && Number.isFinite(pct)) { progressWrap.hidden = false; progressBar.style.width = `${Math.max(0, Math.min(100, pct))}%`; } if (data?.status === 'progress' && data?.file) { statusEl.textContent = `Downloading model: ${data.file}`; } } function blobToDataUrl(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(blob); }); } /* ------------------------------------------------------------------ * * Working image * ------------------------------------------------------------------ */ /** * Downscale the chosen photo to a bounded working copy. Every method — the * threshold maths, the three models, and the display canvas — then works on * exactly the same pixels, so their masks line up when you compare them. */ function makeWorkingCopy(image) { const scale = Math.min(1, WORKING_MAX_SIDE / Math.max(image.naturalWidth, image.naturalHeight)); const width = Math.max(1, Math.round(image.naturalWidth * scale)); const height = Math.max(1, Math.round(image.naturalHeight * scale)); const scratch = document.createElement('canvas'); scratch.width = width; scratch.height = height; scratch.getContext('2d').drawImage(image, 0, 0, width, height); return { canvas: scratch, width, height, dataUrl: scratch.toDataURL('image/jpeg', 0.92) }; } function computeHistogram() { if (!state.working) return; const imageData = state.working.canvas .getContext('2d', { willReadFrequently: true }) .getImageData(0, 0, state.working.width, state.working.height); const gray = toGrayscale(imageData); state.histogram = buildHistogram(gray); state.otsu = otsuThreshold(state.histogram, gray.length); drawHistogram(); } /* ------------------------------------------------------------------ * * Drawing * ------------------------------------------------------------------ */ function drawBase() { if (!state.working) return; canvas.width = state.working.width; canvas.height = state.working.height; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(state.working.canvas, 0, 0); canvasWrap.classList.remove('empty'); } /** * Paint one binary mask into an RGBA overlay buffer. * * Masks normally already match the canvas size, but the ratio mapping keeps * this correct even when a model hands back a different resolution. */ function paintMask(overlay, region, alpha) { const width = canvas.width; const height = canvas.height; const { mask, width: maskWidth, height: maskHeight, color } = region; const [r, g, b] = color; const stepX = maskWidth / width; const stepY = maskHeight / height; const data = overlay.data; for (let y = 0; y < height; y++) { const maskRow = Math.min(maskHeight - 1, (y * stepY) | 0) * maskWidth; const outRow = y * width; for (let x = 0; x < width; x++) { const maskX = Math.min(maskWidth - 1, (x * stepX) | 0); // Truthiness, not a 0/255 test: classic.js and SlimSAM emit 0/1 masks while // the pipelines emit 0/255, and summarizeMask already reads them this way. if (!mask[maskRow + maskX]) continue; const i = (outRow + x) * 4; data[i] = r; data[i + 1] = g; data[i + 2] = b; data[i + 3] = alpha; } } } function compositeOverlay(regions, alpha) { // Quantise to a byte here, once. Assigning a fractional alpha into a // Uint8ClampedArray rounds half to even, so 0.5 becomes 0 and the whole // overlay silently composites as fully transparent. const alphaByte = Math.max(0, Math.min(255, Math.round(alpha * 255))); const overlay = ctx.createImageData(canvas.width, canvas.height); for (const region of regions) paintMask(overlay, region, alphaByte); const scratch = document.createElement('canvas'); scratch.width = canvas.width; scratch.height = canvas.height; scratch.getContext('2d').putImageData(overlay, 0, 0); ctx.drawImage(scratch, 0, 0); } function drawChip(text, x, y) { const fontSize = Math.max(12, Math.round(canvas.width / 52)); const pad = Math.round(fontSize * 0.42); ctx.font = `700 ${fontSize}px system-ui, sans-serif`; ctx.textBaseline = 'top'; const metrics = ctx.measureText(text); const boxWidth = metrics.width + pad * 2; const boxHeight = fontSize + pad * 2; const left = Math.min(Math.max(0, x - boxWidth / 2), canvas.width - boxWidth); const top = Math.min(Math.max(0, y - boxHeight / 2), canvas.height - boxHeight); ctx.fillStyle = 'rgba(17, 24, 39, .88)'; ctx.fillRect(left, top, boxWidth, boxHeight); ctx.fillStyle = '#ffffff'; ctx.fillText(text, left + pad, top + pad); } function drawPointMarker(point) { const radius = Math.max(7, Math.round(canvas.width / 110)); ctx.lineWidth = Math.max(2, Math.round(canvas.width / 340)); ctx.beginPath(); ctx.arc(point.x, point.y, radius, 0, Math.PI * 2); ctx.strokeStyle = '#ffffff'; ctx.stroke(); ctx.strokeStyle = '#111827'; ctx.lineWidth = Math.max(1, ctx.lineWidth - 1); ctx.stroke(); ctx.beginPath(); ctx.arc(point.x, point.y, Math.max(2, radius / 3), 0, Math.PI * 2); ctx.fillStyle = '#ffffff'; ctx.fill(); } function drawHistogram() { if (!state.histogram) return; const width = (histogramCanvas.width = 512); const height = (histogramCanvas.height = 118); const hctx = histogramCanvas.getContext('2d'); hctx.clearRect(0, 0, width, height); const peak = Math.max(...state.histogram); if (!peak) return; // A square-root scale keeps the small bins visible next to the background spike. const barWidth = width / 256; for (let i = 0; i < 256; i++) { const barHeight = (Math.sqrt(state.histogram[i]) / Math.sqrt(peak)) * (height - 8); hctx.fillStyle = '#c8cfda'; hctx.fillRect(i * barWidth, height - barHeight, Math.max(1, barWidth), barHeight); } const method = thresholdMethod.value; if (method !== 'adaptive' && state.otsu !== null) { const x = state.otsu * barWidth; hctx.strokeStyle = '#98a2b3'; hctx.setLineDash([3, 3]); hctx.lineWidth = 1.5; hctx.beginPath(); hctx.moveTo(x, 0); hctx.lineTo(x, height); hctx.stroke(); hctx.setLineDash([]); } const active = method === 'binary' ? Number(cutoff.value) : state.otsu; if (active !== null && method !== 'adaptive') { const x = active * barWidth; hctx.strokeStyle = '#111827'; hctx.lineWidth = 2; hctx.beginPath(); hctx.moveTo(x, 0); hctx.lineTo(x, height); hctx.stroke(); } } /* ------------------------------------------------------------------ * * Rendering a result * ------------------------------------------------------------------ */ /** * The three things a result canvas can show. Switching between them is a pure * redraw — no model is re-run — so students can flip back and forth freely. * * overlay the photo with translucent masks on top (default) * mask the masks alone on a flat backdrop: this is literally what a * segmentation model returns, before anyone blends it with a photo * original the untouched photo, for comparison */ function prepareCanvas() { if (!state.working) return false; canvas.width = state.working.width; canvas.height = state.working.height; canvasWrap.classList.remove('empty'); if (state.view === 'mask') { ctx.fillStyle = '#0f1216'; ctx.fillRect(0, 0, canvas.width, canvas.height); } else { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(state.working.canvas, 0, 0); } return true; } /** Masks are drawn solid in the mask view; translucent when blended over a photo. */ function maskAlpha(blended) { return state.view === 'mask' ? 1 : blended; } /** * Turn the classic pipeline's connected components into the same region shape * the learned models return, so all four experiments render identically: one * coloured mask per region, with a numbered label — never a bounding box. * * Each blob is disjoint, so one mask per component repaints the full foreground * the summary reports, just split by connectivity instead of by class. */ function thresholdRegions(result) { const { labels, width, height } = result; const total = width * height; return result.components.slice(0, MAX_ROWS).map((component, index) => { const mask = new Uint8Array(total); for (let i = 0; i < total; i++) { if (labels[i] === component.label) mask[i] = 1; } return { ...component, label: `#${index + 1}`, score: null, coverage: component.area / total, color: colorForIndex(index), mask, width, height, }; }); } function renderThreshold(result) { lastDraw = { kind: 'regions', regions: thresholdRegions(result) }; redraw(); } function renderRegions(regions) { lastDraw = { kind: 'regions', regions }; redraw(); } function renderPromptable(result, selectedIndex) { lastDraw = { kind: 'promptable', result, selected: selectedIndex }; redraw(); } function redraw() { if (!lastDraw || !prepareCanvas()) return; viewSwitch.hidden = false; const showMasks = state.view !== 'original'; const labelled = state.view !== 'original'; if (lastDraw.kind === 'regions') { const { regions } = lastDraw; if (showMasks) compositeOverlay(regions, maskAlpha(0.5)); if (labelled) { const shown = regions.filter((region) => region.coverage >= MIN_COVERAGE).slice(0, MAX_LABELS); for (const region of shown) { const scaleX = canvas.width / region.width; const scaleY = canvas.height / region.height; const text = region.score === null || region.score === undefined ? region.label : `${region.label} ${(region.score * 100).toFixed(0)}%`; drawChip(text, region.cx * scaleX, region.cy * scaleY); } } return; } if (lastDraw.kind === 'promptable') { const { result, selected } = lastDraw; const candidate = result.candidates[selected]; if (candidate && showMasks) compositeOverlay([candidate], maskAlpha(0.55)); if (labelled) drawPointMarker(result.point); } } /* ------------------------------------------------------------------ * * Tables * ------------------------------------------------------------------ */ function setHeaders(labels) { tableHead.innerHTML = ''; for (const label of labels) { const th = document.createElement('th'); th.textContent = label; tableHead.appendChild(th); } } function renderRows(rows, emptyText = 'Nothing passed the current settings.') { tbody.innerHTML = ''; if (!rows.length) { const tr = document.createElement('tr'); tr.className = 'empty-row'; const td = document.createElement('td'); td.colSpan = tableHead.children.length; td.textContent = emptyText; tr.appendChild(td); tbody.appendChild(tr); return; } for (const row of rows) { const tr = document.createElement('tr'); if (row.onClick) { tr.className = 'clickable-row'; tr.addEventListener('click', row.onClick); } for (const value of row.cells) { const td = document.createElement('td'); td.textContent = value; tr.appendChild(td); } tbody.appendChild(tr); } } function showThresholdTable(result) { // Same three columns as the SegFormer table: this experiment answers the same // question (which pixels, how many), so it should not describe its regions // with a bounding box the way a detector would. setHeaders(['Region', 'Coverage', 'Pixels']); const total = result.width * result.height; const rows = result.components.slice(0, MAX_ROWS).map((component, index) => ({ cells: [ `#${index + 1}`, `${((component.area / total) * 100).toFixed(2)}%`, String(component.area), ], })); renderRows(rows); } function showSemanticTable(result) { setHeaders(['Class', 'Coverage', 'Pixels']); const rows = result.regions.slice(0, MAX_ROWS).map((region) => ({ cells: [ region.label, `${(region.coverage * 100).toFixed(2)}%`, String(region.area), ], })); renderRows(rows); } function showInstanceTable(result) { setHeaders(['Object', 'Class', 'Confidence', 'Coverage']); const rows = result.regions.slice(0, MAX_ROWS).map((region, index) => ({ cells: [ `#${index + 1}`, region.label, region.score === null ? '—' : `${(region.score * 100).toFixed(1)}%`, `${(region.coverage * 100).toFixed(2)}%`, ], })); renderRows(rows); } function showPromptableTable(result) { setHeaders(['Candidate', 'Predicted IoU', 'Coverage']); const rows = result.candidates.map((candidate, index) => ({ cells: [ index === 0 ? `#${index + 1} · shown` : `#${index + 1}`, candidate.score.toFixed(3), `${(candidate.coverage * 100).toFixed(2)}%`, ], onClick: () => { state.samResult = { result, selected: index }; renderPromptable(result, index); updatePromptableSummary(result, index); showPromptableTable(result); }, })); renderRows(rows); } function updatePromptableSummary(result, selectedIndex) { const best = result.candidates[0]; summary.textContent = `Click at (${result.point.x}, ${result.point.y}) — ` + `best mask covers ${(best.coverage * 100).toFixed(1)}% of the frame ` + `at IoU ${best.score.toFixed(3)}. Showing candidate #${selectedIndex + 1}.`; } /* ------------------------------------------------------------------ * * Summaries * ------------------------------------------------------------------ */ function summarizeThreshold(result) { const named = thresholdMethod.options[thresholdMethod.selectedIndex].text; const blobs = result.components.length; // Only the largest MAX_ROWS blobs get a mask and a table row, so say so when // the count is bigger than that rather than quoting a number the view cannot // back up. const shown = blobs > MAX_ROWS ? ` (showing the ${MAX_ROWS} largest)` : ''; return ( `${named} — cutoff at grey level ${result.threshold}, ` + `foreground ${((result.foreground / (result.width * result.height)) * 100).toFixed(1)}%, ` + `${blobs} separate blob${blobs === 1 ? '' : 's'} found${shown}.` ); } function summarizeSemantic(result) { const named = result.regions.filter((region) => region.coverage >= MIN_COVERAGE); const covered = result.regions.reduce((total, region) => total + region.coverage, 0); const top = named .slice(0, 4) .map((region) => region.label) .join(', '); return ( `SegFormer labelled ${named.length} scene classes, covering ` + `${(covered * 100).toFixed(1)}% of the frame. Largest: ${top || '—'}.` ); } function summarizeInstance(result) { const counts = new Map(); for (const region of result.regions) { counts.set(region.label, (counts.get(region.label) || 0) + 1); } const pieces = [...counts.entries()] .sort((a, b) => b[1] - a[1]) .slice(0, 6) .map(([label, count]) => `${label} ×${count}`); return `MaskFormer found ${result.regions.length} separate objects — ${pieces.join(', ') || 'none'}.`; } /* ------------------------------------------------------------------ * * Comparison strip * ------------------------------------------------------------------ */ function thumbnailFromCanvas() { const width = 360; const scale = Math.min(1, width / canvas.width); const scratch = document.createElement('canvas'); scratch.width = Math.max(1, Math.round(canvas.width * scale)); scratch.height = Math.max(1, Math.round(canvas.height * scale)); scratch.getContext('2d').drawImage(canvas, 0, 0, scratch.width, scratch.height); return scratch.toDataURL('image/jpeg', 0.72); } function recordCompare(key, headline) { const experiment = getExperiment(key); compareEntries.set(key, { key, label: experiment.label, family: experiment.family, headline, thumb: thumbnailFromCanvas(), }); renderCompare(); } function renderCompare() { compareGrid.innerHTML = ''; if (!compareEntries.size) { const empty = document.createElement('p'); empty.className = 'compare-empty'; empty.textContent = 'Run a method and its result will appear here.'; compareGrid.appendChild(empty); return; } // Keep the panel order stable rather than the order the user happened to run things in. const ordered = EXPERIMENTS.map((experiment) => compareEntries.get(experiment.key)).filter(Boolean); for (const entry of ordered) { const card = document.createElement('article'); card.className = 'compare-card'; const image = document.createElement('img'); image.src = entry.thumb; image.alt = `${entry.label} segmentation result`; image.loading = 'lazy'; const kicker = document.createElement('p'); kicker.className = 'compare-kicker'; kicker.textContent = entry.family; const title = document.createElement('h3'); title.textContent = entry.label; const text = document.createElement('p'); text.className = 'compare-headline'; text.textContent = entry.headline; card.append(image, kicker, title, text); compareGrid.appendChild(card); } } /* ------------------------------------------------------------------ * * Selection * ------------------------------------------------------------------ */ function resetResult(message = 'No result yet.') { summary.textContent = message; resultKicker.textContent = 'Result'; resultTitle.textContent = 'Run a method to see its segments'; setHeaders(['Segment', 'Detail']); renderRows([], 'Run a method to see its segments.'); state.samResult = null; lastDraw = null; viewSwitch.hidden = true; samHint.hidden = true; canvas.classList.remove('clickable'); } function setSelectedImage(dataUrl, readyMessage) { const image = new Image(); image.onload = () => { state.image = image; state.working = makeWorkingCopy(image); state.samHandle = null; drawBase(); computeHistogram(); runButton.disabled = false; resetResult('Image ready. Pick a method and run it.'); statusEl.textContent = readyMessage; setBadge('Image ready'); // Segments from a different photo are not comparable, so start clean. if (compareEntries.size) { compareEntries.clear(); renderCompare(); statusEl.textContent = `${readyMessage} Comparison cleared — it belonged to the previous image.`; } }; image.onerror = () => { statusEl.textContent = 'Could not read that image.'; setBadge('Image error', 'error'); }; image.src = dataUrl; } async function loadExample(example, button) { try { statusEl.textContent = `Loading example: ${example.label}…`; setBadge('Loading sample', 'running'); const response = await fetch(example.src); if (!response.ok) throw new Error(`Could not load ${example.src}`); const dataUrl = await blobToDataUrl(await response.blob()); imageInput.value = ''; document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected')); button.classList.add('selected'); setSelectedImage(dataUrl, `Example ready: ${example.label}.`); } catch (error) { console.error(error); statusEl.textContent = 'Could not load that example. Try another one.'; setBadge('Sample error', 'error'); } } function renderExampleChoices() { sampleGrid.innerHTML = ''; for (const example of chooseRandom(EXAMPLES, 4)) { const button = document.createElement('button'); button.type = 'button'; button.className = 'sample-card'; button.title = `Use example: ${example.label}`; const image = document.createElement('img'); image.src = example.src; image.alt = example.label; image.loading = 'lazy'; const label = document.createElement('span'); label.textContent = example.label; const source = document.createElement('small'); const cocoId = example.src.match(/(\d{12})\.jpg$/)?.[1] || ''; source.textContent = cocoId ? `COCO val2017 · ${cocoId}` : 'COCO val2017'; button.append(image, label, source); button.addEventListener('click', () => loadExample(example, button)); sampleGrid.appendChild(button); } } function selectExperiment(key, button) { state.experiment = key; const experiment = getExperiment(key); document.querySelectorAll('.experiment-card').forEach((card) => { const active = card.dataset.key === key; card.classList.toggle('selected', active); card.setAttribute('aria-checked', String(active)); }); experimentBlurb.textContent = experiment.blurb; // Model-substitution disclosure. Kept on the page, not just in the source, so // nobody reads "SegFormer" as a stand-in for "DeepLabV3" without being told. experimentNote.textContent = experiment.note || ''; experimentNote.hidden = !experiment.note; for (const [panelKey, panel] of Object.entries(panels)) { panel.hidden = panelKey !== key; } samHint.hidden = true; canvas.classList.remove('clickable'); setBadge(`Method: ${experiment.label}`); if (state.working) { statusEl.textContent = `${experiment.label} selected. Run it when you are ready.`; resetResult(`Image ready. Run ${experiment.label}.`); } computeHistogram(); } function renderExperimentChoices() { for (const experiment of EXPERIMENTS) { const button = document.createElement('button'); button.type = 'button'; button.className = 'experiment-card'; button.dataset.key = experiment.key; button.setAttribute('role', 'radio'); button.setAttribute('aria-checked', String(experiment.key === state.experiment)); const family = document.createElement('span'); family.className = 'experiment-family'; family.textContent = experiment.family; const title = document.createElement('strong'); title.textContent = experiment.label; const tagline = document.createElement('em'); tagline.textContent = experiment.tagline; button.append(family, title, tagline); button.addEventListener('click', () => selectExperiment(experiment.key, button)); experimentGrid.appendChild(button); } } /* ------------------------------------------------------------------ * * Running * ------------------------------------------------------------------ */ function currentThresholdOptions() { return { method: thresholdMethod.value, threshold: Number(cutoff.value), blockSize: Number(blockSize.value), constant: Number(adaptiveC.value), invert: invert.checked, denoise: denoise.checked, }; } async function runOnce() { if (!state.working || state.busy) return; const experiment = getExperiment(state.experiment); state.busy = true; runButton.disabled = true; progressWrap.hidden = false; progressBar.style.width = '5%'; setBadge(`Running ${experiment.label}`, 'running'); const started = performance.now(); try { if (experiment.kind === 'threshold') { const imageData = state.working.canvas .getContext('2d', { willReadFrequently: true }) .getImageData(0, 0, state.working.width, state.working.height); statusEl.textContent = 'Thresholding pixels…'; const result = runThreshold(imageData, currentThresholdOptions()); result.width = state.working.width; result.height = state.working.height; renderThreshold(result); showThresholdTable(result); const headline = summarizeThreshold(result); summary.textContent = headline; resultKicker.textContent = experiment.family; resultTitle.textContent = `Threshold — ${result.components.length} blobs`; recordCompare(experiment.key, headline); setBadge(`${result.components.length} blobs`, 'ready'); } if (experiment.kind === 'semantic') { statusEl.textContent = 'Preparing SegFormer. The first run downloads model files.'; const result = await runSemantic(state.working.dataUrl, { progressCallback: setProgress }); renderRegions(result.regions); showSemanticTable(result); const headline = summarizeSemantic(result); summary.textContent = headline; resultKicker.textContent = experiment.family; resultTitle.textContent = 'SegFormer — classes per pixel'; recordCompare(experiment.key, headline); setBadge(`${result.regions.length} classes`, 'ready'); } if (experiment.kind === 'instance') { statusEl.textContent = 'Preparing MaskFormer. The first run downloads model files.'; const result = await runInstance(state.working.dataUrl, { threshold: Number(confidence.value), progressCallback: setProgress, }); renderRegions(result.regions); showInstanceTable(result); const headline = summarizeInstance(result); summary.textContent = headline; resultKicker.textContent = experiment.family; resultTitle.textContent = `MaskFormer — ${result.regions.length} objects`; recordCompare(experiment.key, headline); setBadge(`${result.regions.length} objects`, 'ready'); } if (experiment.kind === 'promptable') { statusEl.textContent = 'Computing the SlimSAM image embedding. The first run downloads model files.'; state.samHandle = await prepareSam(state.working.dataUrl, { progressCallback: setProgress }); state.samResult = null; drawBase(); resetResult('SlimSAM is ready. Click the image to segment an object.'); resultKicker.textContent = experiment.family; resultTitle.textContent = 'SlimSAM — click to segment'; samHint.hidden = false; canvas.classList.add('clickable'); setBadge('SlimSAM ready', 'ready'); statusEl.textContent = 'Click anywhere on the image. Each click is a new prompt.'; } const seconds = ((performance.now() - started) / 1000).toFixed(1); if (experiment.kind !== 'promptable') { statusEl.textContent = `Done in ${seconds}s with ${experiment.label}.`; } } catch (error) { console.error(error); statusEl.textContent = `${experiment.label} failed to run. Check your connection, or try another method.`; setBadge('Error', 'error'); } finally { progressWrap.hidden = true; progressBar.style.width = '0%'; state.busy = false; runButton.disabled = !state.working; } } async function handleCanvasClick(event) { // state.experiment holds a key ("sam"), so compare the kind, not the key. if (getExperiment(state.experiment).kind !== 'promptable' || !state.samHandle || state.busy) return; const rect = canvas.getBoundingClientRect(); const x = (event.clientX - rect.left) * (canvas.width / rect.width); const y = (event.clientY - rect.top) * (canvas.height / rect.height); state.busy = true; setBadge('Segmenting', 'running'); statusEl.textContent = `Segmenting around (${Math.round(x)}, ${Math.round(y)})…`; try { const started = performance.now(); const result = await segmentWithPoint(state.samHandle, x, y); const seconds = ((performance.now() - started) / 1000).toFixed(2); state.samResult = { result, selected: 0 }; renderPromptable(result, 0); showPromptableTable(result); updatePromptableSummary(result, 0); resultKicker.textContent = 'Promptable'; resultTitle.textContent = 'SlimSAM — 3 candidate masks'; recordCompare('sam', `Clicked (${result.point.x}, ${result.point.y}) — best IoU ${result.candidates[0].score.toFixed(3)}.`); setBadge(`${seconds}s`, 'ready'); statusEl.textContent = `SlimSAM answered in ${seconds}s. Click again for a different object.`; } catch (error) { console.error(error); statusEl.textContent = 'SlimSAM failed on that point. Try another spot.'; setBadge('Error', 'error'); } finally { state.busy = false; } } /* ------------------------------------------------------------------ * * Wiring * ------------------------------------------------------------------ */ runButton.addEventListener('click', runOnce); canvas.addEventListener('click', handleCanvasClick); for (const option of viewSwitch.querySelectorAll('.view-option')) { option.addEventListener('click', () => { state.view = option.dataset.view; for (const other of viewSwitch.querySelectorAll('.view-option')) { const active = other === option; other.classList.toggle('selected', active); other.setAttribute('aria-checked', String(active)); } redraw(); }); } thresholdMethod.addEventListener('change', () => { const method = thresholdMethod.value; thresholdManual.hidden = method !== 'binary'; thresholdAdaptive.hidden = method !== 'adaptive'; drawHistogram(); }); cutoff.addEventListener('input', () => { cutoffValue.value = String(cutoff.value); drawHistogram(); }); blockSize.addEventListener('input', () => { blockSizeValue.value = String(blockSize.value); }); adaptiveC.addEventListener('input', () => { adaptiveCValue.value = String(adaptiveC.value); }); confidence.addEventListener('input', () => { confidenceValue.value = Number(confidence.value).toFixed(2); }); imageInput.addEventListener('change', () => { const file = imageInput.files?.[0]; if (!file) return; if (!file.type.startsWith('image/')) { statusEl.textContent = 'Please choose an image file.'; setBadge('Invalid file', 'error'); runButton.disabled = true; return; } document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected')); state.samHandle = null; const reader = new FileReader(); reader.onload = () => setSelectedImage(reader.result, 'Your image is ready.'); reader.onerror = () => { statusEl.textContent = 'Could not read that image.'; setBadge('Image error', 'error'); }; reader.readAsDataURL(file); }); shuffleButton.addEventListener('click', () => { renderExampleChoices(); statusEl.textContent = state.working ? 'New examples shown. Your current image is still selected.' : 'Choose an example, or upload your own image.'; }); clearCompareButton.addEventListener('click', () => { compareEntries.clear(); renderCompare(); statusEl.textContent = 'Comparison cleared.'; }); /* ------------------------------------------------------------------ * * Boot * ------------------------------------------------------------------ */ renderExperimentChoices(); renderExampleChoices(); selectExperiment(state.experiment); resetResult('Choose an image, then run a method.');
import {
EXPERIMENTS,
getExperiment,
colorForIndex,
runSemantic,
runInstance,
prepareSam,
segmentWithPoint,
} from './segmenter.js';
import { runThreshold, toGrayscale, buildHistogram, otsuThreshold } from './classic.js';
/* ------------------------------------------------------------------ *
* DOM
* ------------------------------------------------------------------ */
const imageInput = document.querySelector('#image-input');
const experimentGrid = document.querySelector('#experiment-grid');
const experimentBlurb = document.querySelector('#experiment-blurb');
const experimentNote = document.querySelector('#experiment-note');
const runButton = document.querySelector('#run-button');
const statusEl = document.querySelector('#status');
const progressWrap = document.querySelector('#progress-wrap');
const progressBar = document.querySelector('#progress-bar');
const canvasWrap = document.querySelector('#canvas-wrap');
const canvas = document.querySelector('#result-canvas');
const viewSwitch = document.querySelector('#view-switch');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const samHint = document.querySelector('#sam-hint');
const summary = document.querySelector('#summary');
const tableHead = document.querySelector('#table-head');
const tbody = document.querySelector('#detections-body');
const runtimeBadge = document.querySelector('#runtime-badge');
const resultKicker = document.querySelector('#result-kicker');
const resultTitle = document.querySelector('#result-title');
const sampleGrid = document.querySelector('#sample-grid');
const shuffleButton = document.querySelector('#shuffle-examples');
const compareGrid = document.querySelector('#compare-grid');
const clearCompareButton = document.querySelector('#clear-compare');
const panels = {
threshold: document.querySelector('#panel-threshold'),
segformer: document.querySelector('#panel-segformer'),
maskformer: document.querySelector('#panel-maskformer'),
sam: document.querySelector('#panel-sam'),
};
const thresholdMethod = document.querySelector('#threshold-method');
const thresholdManual = document.querySelector('#threshold-manual');
const thresholdAdaptive = document.querySelector('#threshold-adaptive');
const cutoff = document.querySelector('#cutoff');
const cutoffValue = document.querySelector('#cutoff-value');
const blockSize = document.querySelector('#block-size');
const blockSizeValue = document.querySelector('#block-size-value');
const adaptiveC = document.querySelector('#adaptive-c');
const adaptiveCValue = document.querySelector('#adaptive-c-value');
const invert = document.querySelector('#invert');
const denoise = document.querySelector('#denoise');
const histogramCanvas = document.querySelector('#histogram');
const confidence = document.querySelector('#confidence');
const confidenceValue = document.querySelector('#confidence-value');
/* ------------------------------------------------------------------ *
* Examples
* ------------------------------------------------------------------ */
const EXAMPLES = [
{ src: './examples/000000039769.jpg', label: 'Two cats on a couch' },
{ src: './examples/000000189806.jpg', label: 'Cat and dog indoors' },
{ src: './examples/000000010092.jpg', label: 'Bedroom interior' },
{ src: './examples/000000037777.jpg', label: 'Kitchen counter' },
{ src: './examples/000000210520.jpg', label: 'Dining table' },
{ src: './examples/000000397133.jpg', label: 'Busy kitchen' },
{ src: './examples/000000167898.jpg', label: 'Bathroom fixtures' },
{ src: './examples/000000376310.jpg', label: 'Bathroom objects' },
{ src: './examples/000000252219.jpg', label: 'Street scene' },
{ src: './examples/000000174482.jpg', label: 'Bicycle in traffic' },
{ src: './examples/000000482978.jpg', label: 'Passenger train' },
{ src: './examples/000000090208.jpg', label: 'Double-decker buses' },
{ src: './examples/000000517523.jpg', label: 'Airplane on approach' },
{ src: './examples/000000570448.jpg', label: 'Boat at the shore' },
{ src: './examples/000000431876.jpg', label: 'Horses and riders' },
{ src: './examples/000000199442.jpg', label: 'Surfer on a wave' },
{ src: './examples/000000097278.jpg', label: 'Snowboarder' },
{ src: './examples/000000500270.jpg', label: 'Skateboarder mid-trick' },
{ src: './examples/000000286458.jpg', label: 'Packed suitcase' },
{ src: './examples/000000429281.jpg', label: 'Bananas at a market' },
{ src: './examples/000000365886.jpg', label: 'Person with a phone' },
{ src: './examples/000000181666.jpg', label: 'Herd in a field' },
{ src: './examples/000000087038.jpg', label: 'Skate park' },
{ src: './examples/000000063965.jpg', label: 'Cake and person' },
];
/* ------------------------------------------------------------------ *
* State
* ------------------------------------------------------------------ */
/** Longest side of the working copy. Keeps every method responsive. */
const WORKING_MAX_SIDE = 768;
/** Regions below this share of the frame are noise, not segments. */