File size: 8,271 Bytes
5d2240d
 
 
 
 
 
15daaf3
5d2240d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4988f9
 
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
/**
 * The learned half of the mini-lab.
 *
 * Three pretrained models, one per rung of the segmentation ladder:
 *   semantic   - SegFormer: "every pixel gets a class", no notion of instances
 *   instance   - MaskFormer: "each object gets its own mask"
 *   promptable - SlimSAM: "tell me where, and I will cut out that thing"
 *
 * Model-choice notes (please keep these honest when editing the page copy):
 *   - DeepLabV3 has no working browser build. Transformers.js dropped
 *     MobileViTForSemanticSegmentation, and the MobileNetV2 DeepLabV3 checkpoint
 *     ships no ONNX weights. SegFormer fills the same semantic-segmentation slot.
 *   - Mask R-CNN has no working browser build either: the only ONNX export is a
 *     185 MB graph needing hand-written RPN/NMS post-processing. MaskFormer
 *     fills the same instance-segmentation slot.
 */

const TRANSFORMERS_URL = 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.0';

let transformersPromise = null;

/**
 * Load the Transformers.js bundle on first use rather than at page load, so
 * the page paints immediately instead of waiting on a ~1 MB library.
 */
function loadTransformers() {
  transformersPromise ??= import(TRANSFORMERS_URL);
  return transformersPromise;
}

export const SEGFORMER_ID = 'Xenova/segformer-b0-finetuned-ade-512-512';
export const MASKFORMER_ID = 'onnx-community/maskformer-swin-tiny-coco';
export const SAM_ID = 'Xenova/slimsam-77-uniform';

/* ------------------------------------------------------------------ *
 * Colour
 * ------------------------------------------------------------------ */

function hslToRgb(h, s, l) {
  const k = (n) => (n + h * 12) % 12;
  const a = s * Math.min(l, 1 - l);
  const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  return [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
}

/**
 * Golden-angle hues keep consecutive region indices far apart on the colour
 * wheel, which matters when a semantic model returns a dozen classes at once.
 */
export function colorForIndex(index) {
  return hslToRgb(((index * 137.508) % 360) / 360, 0.62, 0.55);
}

/* ------------------------------------------------------------------ *
 * Mask bookkeeping
 * ------------------------------------------------------------------ */

/** Area, coverage, bounding box and centroid of a binary mask in one pass. */
export function summarizeMask(mask, width, height) {
  let area = 0;
  let sumX = 0;
  let sumY = 0;
  let xmin = width;
  let ymin = height;
  let xmax = -1;
  let ymax = -1;

  for (let y = 0; y < height; y++) {
    const row = y * width;
    for (let x = 0; x < width; x++) {
      if (!mask[row + x]) continue;
      area++;
      sumX += x;
      sumY += y;
      if (x < xmin) xmin = x;
      if (y < ymin) ymin = y;
      if (x > xmax) xmax = x;
      if (y > ymax) ymax = y;
    }
  }

  if (area === 0) {
    return { area: 0, coverage: 0, xmin: 0, ymin: 0, xmax: 0, ymax: 0, cx: 0, cy: 0 };
  }
  return {
    area,
    coverage: area / (width * height),
    xmin,
    ymin,
    xmax,
    ymax,
    cx: Math.round(sumX / area),
    cy: Math.round(sumY / area),
  };
}

/** Normalise a pipeline `RawImage` mask into the shape app.js renders. */
function regionFromRawImage(label, score, rawImage, index) {
  const { data, width, height } = rawImage;
  const summary = summarizeMask(data, width, height);
  return {
    label,
    score,
    color: colorForIndex(index),
    mask: data,
    width,
    height,
    ...summary,
  };
}

/* ------------------------------------------------------------------ *
 * Semantic + instance pipelines
 * ------------------------------------------------------------------ */

const pipelineCache = new Map();

async function loadSegmentationPipeline(modelId, progressCallback) {
  if (pipelineCache.has(modelId)) return pipelineCache.get(modelId);

  const { pipeline } = await loadTransformers();
  const segmenter = await pipeline('image-segmentation', modelId, {
    dtype: 'q8',
    progress_callback: progressCallback,
  });

  pipelineCache.set(modelId, segmenter);
  return segmenter;
}

/**
 * SegFormer. The pipeline resolves the `semantic` subtask, so we get one binary
 * mask per class actually present in the image (not all 150).
 */
export async function runSemantic(dataUrl, options = {}) {
  const segmenter = await loadSegmentationPipeline(SEGFORMER_ID, options.progressCallback);
  const output = await segmenter(dataUrl);

  const regions = output
    .map((item, index) => regionFromRawImage(item.label, item.score, item.mask, index))
    .filter((region) => region.area > 0)
    .sort((a, b) => b.area - a.area);

  return { kind: 'semantic', regions };
}

/**
 * MaskFormer. The pipeline resolves the `instance` subtask, so each entry is one
 * object with its own label and confidence.
 */
export async function runInstance(dataUrl, options = {}) {
  const segmenter = await loadSegmentationPipeline(MASKFORMER_ID, options.progressCallback);
  const threshold = Number.isFinite(options.threshold) ? options.threshold : 0.5;
  const output = await segmenter(dataUrl, { threshold });

  const regions = output
    .map((item, index) => regionFromRawImage(item.label, item.score, item.mask, index))
    .filter((region) => region.area > 0)
    .sort((a, b) => (b.score ?? 0) - (a.score ?? 0));

  return { kind: 'instance', regions };
}

/* ------------------------------------------------------------------ *
 * SlimSAM (promptable)
 * ------------------------------------------------------------------ */

let samBundle = null;

async function loadSam(progressCallback) {
  if (samBundle) return samBundle;

  const { SamModel, AutoProcessor } = await loadTransformers();
  const model = await SamModel.from_pretrained(SAM_ID, {
    dtype: 'q8',
    progress_callback: progressCallback,
  });
  const processor = await AutoProcessor.from_pretrained(SAM_ID, {
    progress_callback: progressCallback,
  });

  samBundle = { model, processor };
  return samBundle;
}

/**
 * Run SlimSAM's vision encoder once per image and keep the embeddings.
 *
 * The encoder is the expensive half (1024x1024 through a ViT). Caching its
 * output is what makes clicking around the image feel instant, and it is also a
 * neat illustration of how SlimSAM is actually built: one image embedding, many
 * cheap prompt decodes.
 */
export async function prepareSam(dataUrl, options = {}) {
  const { model, processor } = await loadSam(options.progressCallback);
  const { RawImage } = await loadTransformers();

  const rawImage = await RawImage.read(dataUrl);
  const inputs = await processor(rawImage);
  const embeddings = await model.get_image_embeddings({ pixel_values: inputs.pixel_values });

  return { rawImage, inputs, embeddings };
}

/**
 * One point prompt -> three candidate masks, ordered by predicted IoU.
 *
 * SlimSAM is trained to return several plausible readings of an ambiguous click
 * (the whole crowd, or just the one person). Surfacing all three is the most
 * honest way to show what "promptable" actually means.
 */
export async function segmentWithPoint(handle, x, y) {
  const { rawImage, embeddings } = handle;
  const { model, processor } = samBundle;

  const prompted = await processor(rawImage, { input_points: [[[[x, y]]]] });
  const output = await model({ ...prompted, ...embeddings });

  const masks = await processor.post_process_masks(
    output.pred_masks,
    prompted.original_sizes,
    prompted.reshaped_input_sizes,
  );

  const scores = Array.from(output.iou_scores.data);
  const tensor = masks[0];
  const [, count, height, width] = tensor.dims;
  const plane = height * width;

  const candidates = [];
  for (let index = 0; index < count; index++) {
    const mask = tensor.data.subarray(index * plane, (index + 1) * plane);
    candidates.push({
      score: scores[index] ?? 0,
      color: colorForIndex(index),
      mask,
      width,
      height,
      ...summarizeMask(mask, width, height),
    });
  }

  // post_process_masks returns candidates in a fixed order, not sorted.
  candidates.sort((a, b) => b.score - a.score);

  return {
    kind: 'promptable',
    point: { x: Math.round(x), y: Math.round(y) },
    candidates,
    best: candidates[0] ?? null,
  };
}