Spaces:
Running
Running
File size: 36,796 Bytes
5d2240d 15daaf3 5d2240d 15daaf3 5d2240d 15daaf3 5d2240d 15daaf3 5d2240d 15daaf3 5d2240d 15daaf3 5d2240d 15daaf3 5d2240d 15daaf3 5d2240d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 | 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.');
|