Spaces:
Running
Running
Download segmenter.js from Mollysc/Topic3APIS: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/Mollysc/Topic3APIS/resolve/main/segmenter.js
- Command line
-
hf download hf://spaces/Mollysc/Topic3APIS/segmenter.js
-
curl -L -o segmenter.js https://huggingface.co/spaces/Mollysc/Topic3APIS/resolve/main/segmenter.js
10.3 kB
| /** | |
| * 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" | |
| * | |
| * The traditional thresholding baseline lives in classic.js and needs no model. | |
| * | |
| * 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. | |
| * | |
| * Two reasons: the page paints immediately instead of waiting on a ~1 MB | |
| * library, and the classic threshold experiment in classic.js keeps working | |
| * with no network at all, which matters when a classroom connection is flaky. | |
| */ | |
| 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'; | |
| export const EXPERIMENTS = [ | |
| { | |
| key: 'threshold', | |
| label: 'Threshold', | |
| family: 'Classic CV', | |
| tagline: 'Hand-written rule', | |
| blurb: | |
| 'No model. Pick a grey level, call everything brighter than it "object". Otsu chooses the level from the histogram automatically.', | |
| note: 'Pure pixel statistics — fast, explainable, and blind to what the objects actually are.', | |
| kind: 'threshold', | |
| }, | |
| { | |
| key: 'segformer', | |
| label: 'SegFormer', | |
| family: 'Semantic', | |
| tagline: 'Every pixel gets a class', | |
| blurb: | |
| 'A learned semantic segmenter trained on ADE20k. It labels each pixel with one of 150 scene categories: sky, wall, road, person.', | |
| note: | |
| 'Stands in for DeepLabV3, which has no working browser build. Same task and output shape — one class per pixel, no separate objects.', | |
| kind: 'semantic', | |
| }, | |
| { | |
| key: 'maskformer', | |
| label: 'MaskFormer', | |
| family: 'Instance', | |
| tagline: 'Each object gets its own mask', | |
| blurb: | |
| 'A learned instance segmenter trained on COCO. It predicts a separate mask, class and confidence for every individual object.', | |
| note: | |
| 'Stands in for Mask R-CNN, which has no working browser build. Same task — per-object masks rather than per-pixel classes.', | |
| kind: 'instance', | |
| }, | |
| { | |
| key: 'sam', | |
| label: 'SlimSAM', | |
| family: 'Promptable', | |
| tagline: 'Tell it where, it cuts it out', | |
| blurb: | |
| 'A slimmed-down Segment Anything. It has no fixed list of classes: you click a point, and it returns the object under that point.', | |
| note: 'After Run, click anywhere on the image. Each click is a fresh prompt.', | |
| kind: 'promptable', | |
| }, | |
| ]; | |
| export function getExperiment(key) { | |
| return EXPERIMENTS.find((experiment) => experiment.key === key) || EXPERIMENTS[0]; | |
| } | |
| /* ------------------------------------------------------------------ * | |
| * 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, | |
| }; | |
| } | |