Mingze commited on
Commit
d8927ef
·
1 Parent(s): ae93c58

Enrich demo with examples and documentation

Browse files
Files changed (3) hide show
  1. LICENSE +21 -0
  2. README.md +183 -24
  3. app.py +69 -5
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mingze Chen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -12,42 +12,201 @@ license: mit
12
  short_description: Street image segmentation with SegFormer.
13
  ---
14
 
15
- # Street Scene Segmentation
16
 
17
- A small Hugging Face Space for uploading street-view imagery and generating:
18
 
19
- - a semantic-segmentation overlay;
20
- - a Cityscapes color mask;
21
- - per-class pixel coverage;
22
- - downloadable overlay, mask, raw class-ID PNG, and CSV files.
23
 
24
- The app uses
25
- [`nvidia/segformer-b0-finetuned-cityscapes-1024-1024`](https://huggingface.co/nvidia/segformer-b0-finetuned-cityscapes-1024-1024).
26
- It is intentionally small enough to run on a free CPU Space, while automatically
27
- using CUDA when a GPU is available. The inference function is also decorated for
28
- Hugging Face ZeroGPU, allowing eligible free personal accounts to host the app
29
- without creating a paid CPU Space.
30
 
31
- ## Deploy
32
 
33
- Create a new **Gradio Space**. If your account offers **ZeroGPU**, select it in
34
- the hardware picker. Then push these files to the Space repository:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  ```bash
37
  git remote add space https://huggingface.co/spaces/<USERNAME>/<SPACE_NAME>
38
- git push space main
39
  ```
40
 
41
- No API key or Space secret is required because the model is public.
 
 
42
 
43
- ## API
44
 
45
- After deployment, the Gradio endpoint is exposed as `segment`. The Space's
46
- **Use via API** panel provides a generated Python and JavaScript example.
 
 
 
 
 
47
 
48
- ## Notes
49
 
50
- - The model predicts the 19 Cityscapes street-scene classes.
51
- - Images larger than 2048 pixels on their longest side are resized before output.
 
 
 
 
 
 
52
  - Model-license and dataset terms remain governed by the linked model card and
53
- Cityscapes terms.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  short_description: Street image segmentation with SegFormer.
13
  ---
14
 
15
+ <div align="center">
16
 
17
+ # 🚦 Street Scene Semantic Segmentation
18
 
19
+ ### Pixel-level urban scene understanding with SegFormer and Cityscapes
 
 
 
20
 
21
+ [![Hugging Face Space](https://img.shields.io/badge/🤗_Hugging_Face-Live_Demo-FFD21E)](https://huggingface.co/spaces/Mingze/StreetSceneSegmentation)
22
+ [![Model](https://img.shields.io/badge/Model-SegFormer--B0-6366F1)](https://huggingface.co/nvidia/segformer-b0-finetuned-cityscapes-1024-1024)
23
+ [![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB)](https://www.python.org/)
24
+ [![Gradio](https://img.shields.io/badge/UI-Gradio-FF7C00)](https://www.gradio.app/)
25
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
 
26
 
27
+ **Upload a street image and turn every pixel into an interpretable map of the urban environment.**
28
 
29
+ [**🚀 Launch the live app**](https://huggingface.co/spaces/Mingze/StreetSceneSegmentation) ·
30
+ [**🧠 View the model**](https://huggingface.co/nvidia/segformer-b0-finetuned-cityscapes-1024-1024) ·
31
+ [**💻 Source code**](https://github.com/LabMingzeChen/StreetSceneSegmentation)
32
+
33
+ </div>
34
+
35
+ ---
36
+
37
+ ## Live demo
38
+
39
+ The public [Hugging Face Space](https://huggingface.co/spaces/Mingze/StreetSceneSegmentation)
40
+ runs entirely in the browser interface. Students can upload an image, choose a
41
+ built-in example, inspect the results, and download the outputs without installing
42
+ Python or providing an API key.
43
+
44
+ | Sample street image | Example segmentation result |
45
+ |---|---|
46
+ | ![Sample street scene](https://raw.githubusercontent.com/LabMingzeChen/HNIVision/main/space/examples/140546.jpg) | ![Example semantic segmentation](https://raw.githubusercontent.com/LabMingzeChen/HNIVision/main/space/examples/140546_segmentation.png) |
47
+
48
+ ## What the project does
49
+
50
+ The application uses
51
+ [`nvidia/segformer-b0-finetuned-cityscapes-1024-1024`](https://huggingface.co/nvidia/segformer-b0-finetuned-cityscapes-1024-1024)
52
+ to perform semantic segmentation. Unlike object detection, which draws one box
53
+ around an object, semantic segmentation assigns a class to **every image pixel**.
54
+
55
+ For each image, the app produces:
56
+
57
+ | Output | Purpose |
58
+ |---|---|
59
+ | Segmentation overlay | Keeps the original scene visible beneath the predicted classes |
60
+ | Cityscapes color mask | Shows a clean, standardized categorical map |
61
+ | Class coverage table | Reports class ID, pixel count, area share, and color |
62
+ | Raw class-ID PNG | Preserves the numeric prediction for later analysis |
63
+ | CSV summary | Supports statistics, plotting, and classroom exercises |
64
+
65
+ ## The 19 Cityscapes classes
66
+
67
+ | Group | Classes | Example questions |
68
+ |---|---|---|
69
+ | Travel surfaces | `road`, `sidewalk` | How much of the view supports vehicle or pedestrian movement? |
70
+ | Built environment | `building`, `wall`, `fence`, `pole`, `traffic light`, `traffic sign` | Which fixed urban elements dominate the scene? |
71
+ | Nature and sky | `vegetation`, `terrain`, `sky` | How visually green or open is the street? |
72
+ | People | `person`, `rider` | Where are active street users visible? |
73
+ | Transport | `car`, `truck`, `bus`, `train`, `motorcycle`, `bicycle` | Which transport modes appear in the image? |
74
+
75
+ The reported area share is the percentage of **image pixels** assigned to a
76
+ class. It is a measure of visual coverage, not physical land area.
77
+
78
+ ## How it works
79
+
80
+ ```text
81
+ Street image
82
+ ↓ resize and normalize
83
+ SegFormer-B0 image processor
84
+ ↓ transformer-based semantic segmentation
85
+ 19-class pixel map
86
+ ├── original-image overlay
87
+ ├── Cityscapes color mask
88
+ ├── raw class-ID image
89
+ └── per-class CSV summary
90
+ ```
91
+
92
+ The model is downloaded from Hugging Face on the first request and then reused
93
+ from the container cache. CUDA is selected when available; local execution also
94
+ works on CPU. Images larger than 2048 pixels on their longest side are resized
95
+ to limit memory use while preserving aspect ratio.
96
+
97
+ ## Classroom and research examples
98
+
99
+ - **Urban greenery:** compare the visible share of vegetation across streets.
100
+ - **Street design:** examine how roads, sidewalks, buildings, and terrain divide the view.
101
+ - **Mobility:** compare the presence of cars, bicycles, buses, riders, and pedestrians.
102
+ - **Model literacy:** inspect boundary errors and discuss why predictions differ from human interpretation.
103
+ - **Change over time:** process repeat photographs of a location and compare their CSV summaries.
104
+
105
+ Four sample street scenes are loaded from the
106
+ [HNIVision example collection](https://github.com/LabMingzeChen/HNIVision/tree/main/space/examples)
107
+ and appear directly beneath the upload panel in the live app. Hosting samples
108
+ through GitHub Raw follows the same lightweight pattern as HNI-VLM and avoids
109
+ duplicating binary assets in the Space repository.
110
+
111
+ ## Run locally
112
+
113
+ ```bash
114
+ git clone https://github.com/LabMingzeChen/StreetSceneSegmentation.git
115
+ cd StreetSceneSegmentation
116
+ python -m venv .venv
117
+ source .venv/bin/activate
118
+ pip install -r requirements.txt
119
+ python app.py
120
+ ```
121
+
122
+ Open the local URL printed by Gradio. The first prediction downloads the public
123
+ model weights; no application secret is required.
124
+
125
+ ## Use the API
126
+
127
+ Every deployed Gradio Space also exposes an endpoint named `segment`:
128
+
129
+ ```python
130
+ from gradio_client import Client, handle_file
131
+
132
+ client = Client("Mingze/StreetSceneSegmentation")
133
+ result = client.predict(
134
+ handle_file("street.jpg"),
135
+ 0.55, # overlay opacity
136
+ 0.10, # minimum table share (%)
137
+ api_name="/segment",
138
+ )
139
+ ```
140
+
141
+ The Space's **Use via API** panel generates additional Python, JavaScript, and
142
+ command-line examples for the current deployment.
143
+
144
+ ## Deploy your own Hugging Face Space
145
+
146
+ 1. Create a new **Gradio Space**.
147
+ 2. Select ZeroGPU when it is available for your account, or choose another supported hardware tier.
148
+ 3. Clone this repository and add the Space as a second remote.
149
+ 4. Push the same `main` branch to Hugging Face.
150
 
151
  ```bash
152
  git remote add space https://huggingface.co/spaces/<USERNAME>/<SPACE_NAME>
153
+ git push -u space main
154
  ```
155
 
156
+ The YAML block at the top of this README is the Space configuration. Keep
157
+ `app_file: app.py` and the declared Gradio version aligned with
158
+ [`requirements.txt`](requirements.txt).
159
 
160
+ ## Project structure
161
 
162
+ ```text
163
+ StreetSceneSegmentation/
164
+ ├── app.py Gradio interface and model inference
165
+ ├── segmentation_utils.py Palette, rendering, resizing, and CSV helpers
166
+ ├── tests/ Lightweight image-processing tests
167
+ └── requirements.txt Reproducible runtime dependencies
168
+ ```
169
 
170
+ ## Limitations and responsible use
171
 
172
+ - The model was trained for road-driving scenes and may perform poorly on unusual
173
+ viewpoints, night images, severe weather, indoor scenes, or locations unlike
174
+ the training data.
175
+ - Thin structures and object boundaries are common sources of pixel-level error.
176
+ - Results are estimates, not ground truth. Do not use them for navigation,
177
+ safety-critical decisions, legal judgments, or identifying individuals.
178
+ - Uploaded images are processed by the selected Hugging Face Space runtime.
179
+ Avoid submitting private or sensitive imagery to a public service.
180
  - Model-license and dataset terms remain governed by the linked model card and
181
+ [Cityscapes](https://www.cityscapes-dataset.com/) terms.
182
+
183
+ ## References
184
+
185
+ - Enze Xie et al., [“SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers”](https://arxiv.org/abs/2105.15203), NeurIPS 2021.
186
+ - Marius Cordts et al., [“The Cityscapes Dataset for Semantic Urban Scene Understanding”](https://arxiv.org/abs/1604.01685), CVPR 2016.
187
+ - NVIDIA, [SegFormer-B0 Cityscapes model card](https://huggingface.co/nvidia/segformer-b0-finetuned-cityscapes-1024-1024).
188
+
189
+ ## Citation
190
+
191
+ If this software supports your teaching or research, cite the repository:
192
+
193
+ ```bibtex
194
+ @software{chen2026streetscenesegmentation,
195
+ author = {Chen, Mingze},
196
+ title = {Street Scene Semantic Segmentation},
197
+ year = {2026},
198
+ url = {https://github.com/LabMingzeChen/StreetSceneSegmentation}
199
+ }
200
+ ```
201
+
202
+ ## License
203
+
204
+ Released under the [MIT License](LICENSE).
205
+
206
+ ---
207
+
208
+ <div align="center">
209
+
210
+ **If this project is useful, please star the GitHub repository and share the live Space with your students.**
211
+
212
+ </div>
app.py CHANGED
@@ -37,6 +37,14 @@ from segmentation_utils import (
37
 
38
  MODEL_ID = "nvidia/segformer-b0-finetuned-cityscapes-1024-1024"
39
  OUTPUT_ROOT = Path("/tmp/street-scene-segmentation")
 
 
 
 
 
 
 
 
40
 
41
 
42
  @lru_cache(maxsize=1)
@@ -128,6 +136,18 @@ CSS = """
128
  .hero {text-align: center; margin: 0 auto 1rem;}
129
  .hero h1 {font-size: 2.1rem; margin-bottom: .3rem;}
130
  .muted {color: #64748b;}
 
 
 
 
 
 
 
 
 
 
 
 
131
  """
132
 
133
 
@@ -136,8 +156,13 @@ with gr.Blocks(title="Street Scene Segmentation", theme=gr.themes.Soft(), css=CS
136
  """
137
  <div class="hero">
138
  <h1>🚦 Street Scene Semantic Segmentation</h1>
139
- <p>Upload a road or urban street image to identify Cityscapes classes such as roads, sidewalks, buildings, vegetation, vehicles, and people.</p>
140
- <p class="muted">SegFormer-B0 · 19 street-scene classes · CPU/GPU adaptive</p>
 
 
 
 
 
141
  </div>
142
  """
143
  )
@@ -150,6 +175,13 @@ with gr.Blocks(title="Street Scene Segmentation", theme=gr.themes.Soft(), css=CS
150
  height=470,
151
  sources=["upload", "clipboard", "webcam"],
152
  )
 
 
 
 
 
 
 
153
  with gr.Accordion("Display settings", open=False):
154
  opacity_input = gr.Slider(
155
  0.15,
@@ -191,9 +223,41 @@ with gr.Blocks(title="Street Scene Segmentation", theme=gr.themes.Soft(), css=CS
191
 
192
  gr.Markdown(
193
  """
194
- > The model is downloaded from Hugging Face on the first run and then reused from the container cache.
195
- > Images are resized to a maximum side length of 2048 px to prevent memory issues.
196
- > This Cityscapes model is intended for street scenes, not medical, remote-sensing, or indoor imagery.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  """
198
  )
199
 
 
37
 
38
  MODEL_ID = "nvidia/segformer-b0-finetuned-cityscapes-1024-1024"
39
  OUTPUT_ROOT = Path("/tmp/street-scene-segmentation")
40
+ SAMPLE_ROOT = (
41
+ "https://raw.githubusercontent.com/"
42
+ "LabMingzeChen/HNIVision/main/space/examples"
43
+ )
44
+ SAMPLE_IMAGES = [
45
+ f"{SAMPLE_ROOT}/{filename}"
46
+ for filename in ("140546.jpg", "145541.jpg", "148831.jpg", "160710.jpg")
47
+ ]
48
 
49
 
50
  @lru_cache(maxsize=1)
 
136
  .hero {text-align: center; margin: 0 auto 1rem;}
137
  .hero h1 {font-size: 2.1rem; margin-bottom: .3rem;}
138
  .muted {color: #64748b;}
139
+ .project-links {display: flex; justify-content: center; gap: .55rem; flex-wrap: wrap; margin-top: .75rem;}
140
+ .project-link {
141
+ display: inline-block; padding: .42rem .78rem; border: 1px solid #d7deea;
142
+ border-radius: 999px; color: inherit !important; text-decoration: none !important;
143
+ background: white; font-size: .92rem; font-weight: 600;
144
+ }
145
+ .project-link:hover {border-color: #6366f1; box-shadow: 0 2px 8px rgba(99, 102, 241, .12);}
146
+ .guide-grid {display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .8rem; margin: .8rem 0;}
147
+ .guide-card {border: 1px solid #e2e8f0; border-radius: 12px; padding: .85rem 1rem; background: rgba(255,255,255,.55);}
148
+ .guide-card h3 {margin: 0 0 .35rem; font-size: 1rem;}
149
+ .guide-card p {margin: 0; color: #475569; font-size: .93rem; line-height: 1.45;}
150
+ @media (max-width: 760px) {.guide-grid {grid-template-columns: 1fr;}}
151
  """
152
 
153
 
 
156
  """
157
  <div class="hero">
158
  <h1>🚦 Street Scene Semantic Segmentation</h1>
159
+ <p>Turn a street image into a pixel-level map of roads, sidewalks, buildings, vegetation, vehicles, people, and more.</p>
160
+ <p class="muted">SegFormer-B0 · 19 Cityscapes classes · browser-based · no API key required</p>
161
+ <div class="project-links">
162
+ <a class="project-link" href="https://huggingface.co/spaces/Mingze/StreetSceneSegmentation" target="_blank">🤗 Hugging Face Space</a>
163
+ <a class="project-link" href="https://huggingface.co/nvidia/segformer-b0-finetuned-cityscapes-1024-1024" target="_blank">🧠 Model card</a>
164
+ <a class="project-link" href="https://github.com/LabMingzeChen/StreetSceneSegmentation" target="_blank">⭐ GitHub source</a>
165
+ </div>
166
  </div>
167
  """
168
  )
 
175
  height=470,
176
  sources=["upload", "clipboard", "webcam"],
177
  )
178
+ if SAMPLE_IMAGES:
179
+ gr.Examples(
180
+ examples=SAMPLE_IMAGES,
181
+ inputs=image_input,
182
+ label="Or try a sample street scene",
183
+ examples_per_page=4,
184
+ )
185
  with gr.Accordion("Display settings", open=False):
186
  opacity_input = gr.Slider(
187
  0.15,
 
223
 
224
  gr.Markdown(
225
  """
226
+ ## How to use the app
227
+
228
+ <div class="guide-grid">
229
+ <div class="guide-card"><h3>1 · Choose an image</h3><p>Upload, paste, use a webcam, or select one of the sample street scenes above.</p></div>
230
+ <div class="guide-card"><h3>2 · Run segmentation</h3><p>The model assigns one Cityscapes class to every pixel. The first run may take longer while the model loads.</p></div>
231
+ <div class="guide-card"><h3>3 · Explore and download</h3><p>Compare the overlay and mask, review area shares, and download reusable PNG and CSV outputs.</p></div>
232
+ </div>
233
+
234
+ ## What the results mean
235
+
236
+ - **Overlay** blends the prediction with the original photograph. White lines mark boundaries between predicted classes.
237
+ - **Color mask** shows only the standard Cityscapes colors, making classes easier to compare across images.
238
+ - **Area share** is the percentage of image pixels assigned to each class. It describes visual coverage, not physical land area.
239
+ - **Class-ID PNG** stores the numeric class at each pixel; the CSV summarizes visible classes and their colors.
240
+
241
+ | Scene layer | Classes |
242
+ |---|---|
243
+ | Travel surfaces | road, sidewalk |
244
+ | Built environment | building, wall, fence, pole, traffic light, traffic sign |
245
+ | Nature and sky | vegetation, terrain, sky |
246
+ | People | person, rider |
247
+ | Transport | car, truck, bus, train, motorcycle, bicycle |
248
+
249
+ ## Classroom and research ideas
250
+
251
+ - Compare vegetation and built-environment shares across several streets.
252
+ - Discuss why a pixel classifier can confuse terrain, sidewalk, wall, or fence at object boundaries.
253
+ - Export the CSV files and create a class-coverage chart for an urban-design exercise.
254
+ - Compare the same location across seasons, weather conditions, or camera viewpoints.
255
+
256
+ > **Important:** predictions are model estimates, not ground truth. The model was trained for road-driving imagery and can be less reliable for unusual viewpoints, severe weather, night scenes, indoor images, or places unlike the training data. Do not use it for safety-critical decisions or to identify individuals.
257
+
258
+ [Read the SegFormer paper](https://arxiv.org/abs/2105.15203) ·
259
+ [Explore the Cityscapes dataset](https://www.cityscapes-dataset.com/) ·
260
+ [View the source on GitHub](https://github.com/LabMingzeChen/StreetSceneSegmentation)
261
  """
262
  )
263