Topic3APIS / README.md
learnANDlive's picture
Upload folder using huggingface_hub
15daaf3 verified
|
Raw History Blame Contribute Delete
13.2 kB
---
title: AI-Powered Image Segmentation
emoji: 🌖
colorFrom: purple
colorTo: green
sdk: static
app_file: index.html
pinned: false
---
# Image Segmentation Mini-Lab
## 中文说明
这是一个面向 Creative Technology / 入门 AI 课程的图像分割教学实验。
目标检测回答的是"这个物体在哪里",图像分割要回答一个更难的问题:**哪些像素属于这个物体**。这个项目让同一张图片依次经过四种分割思路,从一条手写的阈值规则开始,一步步交给三个预训练模型,让学生直接看到"规则"和"学习"的差别在哪里。
### 学习路径
1. 从 24 张 COCO 2017 validation 示例中选一张,或者上传自己的图片。
2. 选择四种方法之一,点击 Run。
3. 用结果上方的三个视图切换看同一份结果,**不用重新跑模型**:
- **Photo + mask**:原图叠加半透明 mask(默认)
- **Mask only**:只显示 mask 本身,深色底 + 纯色区域。这是分割模型真正的输出,也是"分割"和"检测/分类"最直观的区别
- **Photo only**:不带任何标注的原图,用来对比
4. 查看分割结果表格和每个区域的覆盖率。
5. 保持图片不变,切换方法,结果会保留在下方的对比栏里,可以并排比较。
6. 对 SlimSAM:先 Run 一次计算图像编码,然后在图上**任意点击**,它会分割光标下的物体。
### 四个实验
| # | 方法 | 类别 | 输出的是什么 |
|---|------|------|--------------|
| 1 | Threshold(传统阈值) | Classic CV | 一条手写规则切出的前景像素,按连通域分组 |
| 2 | SegFormer | Semantic | 每个像素一个场景类别,不区分同类个体 |
| 3 | MaskFormer | Instance | 每个物体一张独立 mask,带类别和置信度 |
| 4 | SlimSAM | Promptable | 没有固定类别表,给一个点就切出那个物体 |
第 1 个实验包含三种阈值规则:手动阈值、Otsu 自动阈值(最大化类间方差)、自适应局部均值阈值(应对不均匀光照),外加形态学开闭运算去噪和二遍连通域标记。这部分不依赖任何模型,**断网也能跑**。
### 关于模型替换(请注意)
原始需求里的 DeepLabV3 和 Mask R-CNN **在浏览器里都跑不了**,所以页面用了同一任务位置上的替代模型:
- **SegFormer 替代 DeepLabV3。** Transformers.js 已经移除了 MobileViTForSemanticSegmentation,而 MobileNetV2 版的 DeepLabV3 没有发布 ONNX 权重。SegFormer 填的是同一个"语义分割"位置:一样是每像素一个类别。
- **MaskFormer 替代 Mask R-CNN。** 唯一的 ONNX 导出是一个 185 MB 的计算图,需要自己手写 RPN / NMS 后处理。MaskFormer 填的是同一个"实例分割"位置:一样是每个物体一张 mask。
页面文案和本文档都按实际运行的模型标注,没有把 SegFormer 写成 DeepLabV3,也没有把 MaskFormer 写成 Mask R-CNN。这是刻意的:做 AI 应用时,说清楚"实际跑的是什么"比对齐需求文档上的名字更重要。
### 模型与数据
- 语义分割:`Xenova/segformer-b0-finetuned-ade-512-512`(ADE20k,150 类场景)
- 实例分割:`onnx-community/maskformer-swin-tiny-coco`(COCO)
- 可提示分割:`Xenova/slimsam-77-uniform`(SlimSAM,即精简版 SAM,ONNX 权重)
- 示例库:24 张从 COCO 2017 validation 中选出的图片
三个模型都已训练完成,这个 Demo 只做 inference,不需要训练,也不需要 GPU 服务器。
内置的 COCO 示例用于给课堂提供可靠的起始输入。COCO 不拥有这些底层图片,每张图片仍保留其原始许可信息。
### 一个项目,一个 Demo
- `index.html` — 页面结构与教学流程
- `style.css` — 页面视觉样式
- `app.js` — 交互、画布绘制与结果表格
- `classic.js` — 传统阈值分割(纯像素统计,无模型)
- `segmenter.js` — 三个预训练模型的调用
- `examples/` — 24 张 COCO validation 示例图片
### Runtime
这是一个 Static Space,通过 Transformers.js(v4.3.0,从 jsDelivr CDN 加载)在浏览器内运行模型。Transformers.js 是**用到时才动态加载**的,所以页面秒开,而且第一个实验在完全离线的情况下依然可用。
每个模型第一次运行需要下载权重(SegFormer 最小,MaskFormer 最大),之后复用浏览器缓存。跑过一次 SlimSAM 的图像编码后,后续每次点击几乎是即时的——因为编码器只跑一次,点击只是拿缓存的 embedding 做一次很轻的解码。这一点本身就是 SlimSAM 的设计要点。
打开浏览器控制台时,第一次加载每个模型都会看到一条 `tokenizer_config.json` 的 404。这是正常的:Transformers.js 会探测这个可选文件,而这两个分割模型是纯视觉的,仓库里没有这个文件,库会跳过它继续用 `preprocessor_config.json`。它不影响任何结果。
### 部署注意事项
`examples/` 里的 24 张图片总共约 3.7 MB,作为普通 git 对象提交即可,**不需要 Git LFS**。
如果你从 `test/` 复制了 `.gitattributes`,请把它删掉。里面没有 `*.jpg` 这样的通配规则,而是把每张图片按**完整路径逐条**声明为 LFS(例如 `examples/000000039769.jpg filter=lfs diff=lfs merge=lfs -text`)。只要这些路径匹配到本项目的 `examples/`,提交时每张 JPEG 都会被换成约 131 字节的 LFS 指针文件;如果本机没有安装 git-lfs,Space 部署后会加载不出任何图片。参考项目 `test/` 的本地副本目前就处于这个状态(本机 `git lfs` 未安装)。
用 `git lfs install && git lfs pull` 可以修复已有的 LFS 仓库,但对这个新项目来说最简单的做法是:不要引入 LFS 规则,或者直接用网页上传 / `hf upload` 推送。
### 课堂使用前检查
- 至少一张 COCO 示例可以正常分割;
- **四个方法跑完后都能看到彩色 mask**(Mask only 视图里应该是纯色区域,不是一片空底);
- 三个视图按钮能来回切换,且切换时不会重新跑模型;
- Shuffle 会从 24 张示例中重新随机显示 4 张;
- 四张方法卡片都能选中,右侧面板会跟着切换;
- 第一次未缓存运行时能显示进度条,而不是看起来卡住;
- 四种方法的结果都能出现在下方对比栏里;
- SlimSAM 点击图片后能返回 3 个候选 mask;
- 窄屏 / 手机宽度(390 px)下页面没有横向溢出。
---
## English
This is a small teaching mini-lab on image segmentation for a Creative Technology / introductory AI course.
Object detection answers "where is this thing". Segmentation asks a harder question: **which pixels belong to it**. This project sends one image through four different ideas about what a segment is, starting with a hand-written threshold rule and then handing the job to three pretrained models, so students can see directly where a rule ends and learning begins.
### Learning path
1. Choose one of 24 COCO 2017 validation examples, or upload your own image.
2. Pick one of four methods and press Run.
3. Use the three view buttons above the result to see the same result three ways, without re-running the model:
- **Photo + mask** — the photo with translucent masks on top (default)
- **Mask only** — the masks alone on a flat backdrop. This is literally what a segmentation model returns, and it is the clearest difference between segmentation and detection or classification
- **Photo only** — the untouched photo, for comparison
4. Inspect the result table and each region's coverage.
5. Keep the image fixed, switch methods, and compare them side by side in the strip below.
6. For SlimSAM: run once to compute the image embedding, then **click anywhere** on the picture to segment the object under the cursor.
### The four experiments
| # | Method | Family | What it returns |
|---|--------|--------|-----------------|
| 1 | Threshold | Classic CV | Foreground pixels from one hand-written rule, grouped into connected blobs |
| 2 | SegFormer | Semantic | One scene class per pixel, with no notion of separate objects |
| 3 | MaskFormer | Instance | A separate mask per object, with class and confidence |
| 4 | SlimSAM | Promptable | No fixed class list — give it a point, it cuts out that object |
Experiment 1 offers three threshold rules: a manual cutoff, Otsu's automatic cutoff (maximising between-class variance), and an adaptive local-mean threshold for uneven lighting, plus morphological opening/closing cleanup and two-pass connected-component labelling. None of it touches a model, so **it works with no network at all**.
### About the substituted models (please read)
DeepLabV3 and Mask R-CNN, as originally specified, **cannot run in a browser**, so the page uses the closest model for the same task:
- **SegFormer stands in for DeepLabV3.** Transformers.js dropped MobileViTForSemanticSegmentation, and the MobileNetV2 DeepLabV3 checkpoint ships no ONNX weights. SegFormer fills the same semantic-segmentation slot: one class per pixel.
- **MaskFormer stands in for Mask R-CNN.** The only ONNX export is a 185 MB graph needing hand-written RPN/NMS post-processing. MaskFormer fills the same instance-segmentation slot: one mask per object.
The page copy and this document name the models that actually run. SegFormer is not labelled DeepLabV3, and MaskFormer is not labelled Mask R-CNN. That is deliberate: in an AI application, being clear about what is actually running matters more than matching a name in the requirements.
### Model and data
- Semantic: `Xenova/segformer-b0-finetuned-ade-512-512` (ADE20k, 150 scene classes)
- Instance: `onnx-community/maskformer-swin-tiny-coco` (COCO)
- Promptable: `Xenova/slimsam-77-uniform` (SlimSAM — a slimmed-down SAM, ONNX weights)
- Example bank: 24 selected images from COCO 2017 validation
All three models are already trained. This demo performs inference only; no training or GPU server is required.
The bundled COCO examples give the classroom reliable starting inputs. COCO does not own the underlying images; each image retains its original license.
### One project, one demo
- `index.html` — page structure and teaching flow
- `style.css` — presentation
- `app.js` — interaction, canvas rendering, and result tables
- `classic.js` — traditional threshold segmentation (pixel statistics only, no model)
- `segmenter.js` — the three pretrained model calls
- `examples/` — 24 COCO validation examples
### Runtime
This is a Static Space. It runs models in the browser with Transformers.js (v4.3.0, loaded from the jsDelivr CDN). Transformers.js is imported **lazily, on first use**, so the page paints immediately and the first experiment keeps working completely offline.
The first run of each model downloads its weights — SegFormer is the smallest, MaskFormer the largest — and later runs reuse the browser cache. Once SlimSAM's image encoder has run for an image, every following click is nearly instant, because the encoder runs once and a click is only a cheap decode against the cached embedding. That is the design point of SlimSAM, and the caching here is what makes it visible.
If you open the browser console, the first load of each model logs a 404 for `tokenizer_config.json`. That is expected: Transformers.js probes for that optional file, and both segmentation checkpoints are vision-only, so the repo does not ship one and the library falls through to `preprocessor_config.json`. It does not affect any result.
### Deployment note
The 24 images in `examples/` total about 3.7 MB and should be committed as ordinary git objects. **Git LFS is not needed.**
If you copied `.gitattributes` over from `test/`, delete it. It has no `*.jpg` wildcard; instead it declares each image as LFS by **full path, one line per file** (for example `examples/000000039769.jpg filter=lfs diff=lfs merge=lfs -text`). Any of those paths that match this project's `examples/` will rewrite the JPEG into a ~131-byte LFS pointer on commit, and without git-lfs installed locally the deployed Space then fails to load any image. The local `test/` copy is currently in exactly that state (this machine has no `git lfs`).
`git lfs install && git lfs pull` repairs an existing LFS repo, but for this project the simplest path is not to introduce an LFS rule at all, or to push with the web uploader / `hf upload`.
### Classroom check before use
- at least one COCO example segments correctly;
- **all four methods actually paint a coloured mask** (the Mask only view should show solid regions, never an empty backdrop);
- the three view buttons switch back and forth without re-running the model;
- Shuffle redraws four images from the 24-image sample bank;
- all four method cards select, and the right-hand panel follows;
- the first uncached run shows a progress bar instead of appearing frozen;
- all four methods appear in the comparison strip;
- clicking the image under SlimSAM returns 3 candidate masks;
- the page still works at a narrow/mobile width (390 px) with no horizontal overflow.