Download app.py from ryujiho/task3: direct link, hf CLI and curl.
- Browser
- Download file 6.96 kB
-
https://huggingface.co/spaces/ryujiho/task3/resolve/main/app.py
- Command line
-
hf download hf://spaces/ryujiho/task3/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ryujiho/task3/resolve/main/app.py
6.96 kB
| import gradio as gr | |
| import matplotlib.pyplot as plt | |
| from matplotlib import gridspec | |
| import numpy as np | |
| from PIL import Image | |
| import torch | |
| from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation | |
| # ----------------------------- | |
| # 1. ๋ชจ๋ธ ๋ฐ ํ๋ก์ธ์ ๋ก๋ | |
| # ----------------------------- | |
| MODEL_ID = "nvidia/segformer-b4-finetuned-cityscapes-1024-1024" | |
| processor = AutoImageProcessor.from_pretrained(MODEL_ID) | |
| model = AutoModelForSemanticSegmentation.from_pretrained(MODEL_ID) | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| model.to(device) | |
| # ----------------------------- | |
| # 2. ํ๋ ํธ & ๋ผ๋ฒจ ๋ก๋ฉ | |
| # ----------------------------- | |
| def cityscapes_palette(): | |
| """Cityscapes 19๊ฐ ํด๋์ค์ฉ ํ๋ ํธ.""" | |
| return [ | |
| [204, 87, 92], [112, 185, 212], [45, 189, 106], | |
| [234, 123, 67], [78, 56, 123], [210, 32, 89], | |
| [90, 180, 56], [155, 102, 200], [33, 147, 176], | |
| [255, 183, 76], [67, 123, 89], [190, 60, 45], | |
| [134, 112, 200],[56, 45, 189], [200, 56, 123], | |
| [87, 92, 204], [120, 56, 123], [45, 78, 123], | |
| [112, 117, 119], # 19th color | |
| ] | |
| # labels.txt: Cityscapes ์์๋๋ก 19์ค (road ~ bicycle) ์๋ค๊ณ ๊ฐ์ | |
| try: | |
| labels_list = [] | |
| with open("labels.txt", "r", encoding="utf-8") as fp: | |
| for line in fp: | |
| labels_list.append(line.rstrip("\n")) | |
| except FileNotFoundError: | |
| labels_list = [f"Class {i}" for i in range(19)] | |
| base_cmap = np.asarray(cityscapes_palette(), dtype=np.uint8) | |
| if len(labels_list) <= len(base_cmap): | |
| colormap = base_cmap[: len(labels_list)] | |
| else: | |
| # ๋ผ๋ฒจ์ด ๋ ๋ง์๋ ์ ํฐ์ง๊ฒ ์ ๋ฐ๋ณต | |
| repeat = int(np.ceil(len(labels_list) / len(base_cmap))) | |
| colormap = np.tile(base_cmap, (repeat, 1))[: len(labels_list)] | |
| def label_to_color_image(label: np.ndarray) -> np.ndarray: | |
| if label.ndim != 2: | |
| raise ValueError("Expect 2-D input label") | |
| if np.max(label) >= len(colormap): | |
| raise ValueError( | |
| f"label value too large. max={np.max(label)}, palette_size={len(colormap)}" | |
| ) | |
| return colormap[label] | |
| # ----------------------------- | |
| # 3. ์ค๋ฒ๋ ์ด + ๋ฒ๋ก ํ ์ฅ์ ๊ทธ๋ฆฌ๋ ํจ์ | |
| # ----------------------------- | |
| def draw_overlay_with_legend(pred_img: np.ndarray, seg_np: np.ndarray): | |
| """ | |
| ์ผ์ชฝ: ์ธ๊ทธ๋ฉํ ์ด์ ์ค๋ฒ๋ ์ด | |
| ์ค๋ฅธ์ชฝ: ์ด ์ฅ๋ฉด์ ๋ฑ์ฅํ ํด๋์ค๋ค์ ์์ ํจ์น + ๋ผ๋ฒจ ์ด๋ฆ | |
| ์ ํ Figure ์์ ๊ทธ๋ ค์ ๋ฐํ. | |
| """ | |
| label_names = np.asarray(labels_list) | |
| full_label_map = np.arange(len(label_names)).reshape(len(label_names), 1) | |
| full_color_map = label_to_color_image(full_label_map) | |
| unique_labels = np.unique(seg_np.astype("uint8")) | |
| # ์ ์ฒด Figure: ์ผ์ชฝ(ํฐ) + ์ค๋ฅธ์ชฝ(์ข์ ๋ฒ๋ก) | |
| fig = plt.figure(figsize=(10, 6)) | |
| gs = gridspec.GridSpec(1, 2, width_ratios=[4, 1]) | |
| # --- ์ผ์ชฝ: ์ค๋ฒ๋ ์ด --- | |
| ax0 = plt.subplot(gs[0]) | |
| ax0.imshow(pred_img) | |
| ax0.axis("off") | |
| ax0.set_title("Overlay", fontsize=12) | |
| # --- ์ค๋ฅธ์ชฝ: ๋ฒ๋ก --- | |
| ax1 = plt.subplot(gs[1]) | |
| ax1.imshow(full_color_map[unique_labels].astype(np.uint8), interpolation="nearest") | |
| ax1.yaxis.tick_right() | |
| ax1.set_yticks(range(len(unique_labels))) | |
| ax1.set_yticklabels(label_names[unique_labels], fontsize=10) | |
| ax1.set_xticks([]) | |
| # ํ ๋๋ฆฌ/ํฑ ์ ๋ฆฌ | |
| ax1.tick_params(width=0.0, length=0.0) | |
| for spine in ["right", "left", "top", "bottom"]: | |
| ax1.spines[spine].set_visible(False) | |
| plt.tight_layout() | |
| return fig | |
| # ----------------------------- | |
| # 4. ์ถ๋ก ํจ์: Figure ํ๋๋ง ๋ฐํ | |
| # ----------------------------- | |
| def run_inference(input_img): | |
| if input_img is None: | |
| return None | |
| # numpy -> PIL | |
| img = ( | |
| Image.fromarray(input_img.astype(np.uint8)) | |
| if isinstance(input_img, np.ndarray) | |
| else input_img | |
| ) | |
| if img.mode != "RGB": | |
| img = img.convert("RGB") | |
| inputs = processor(images=img, return_tensors="pt").to(device) | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| logits = outputs.logits # (1, C, h/4, w/4) | |
| # ์๋ณธ ํฌ๊ธฐ๋ก ์ ์ํ | |
| upsampled = torch.nn.functional.interpolate( | |
| logits, size=img.size[::-1], mode="bilinear", align_corners=False | |
| ) | |
| seg = upsampled.argmax(dim=1)[0].cpu().numpy().astype(np.uint8) | |
| # ์ ์ค๋ฒ๋ ์ด | |
| color_seg = colormap[seg] | |
| pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8) | |
| # ๐ ์ฌ๊ธฐ์ ๋ฐ๋ก "์ค๋ฒ๋ ์ด + ๋ฒ๋ก ํ ์ฅ" Figure ์์ฑ | |
| fig = draw_overlay_with_legend(pred_img, seg) | |
| return fig | |
| # ----------------------------- | |
| # 5. Gradio UI (์ฌํํ Blocks + Plot ํ๋) | |
| # ----------------------------- | |
| with gr.Blocks( | |
| title="Semantic Segmentation Demo", | |
| theme=gr.themes.Soft(), | |
| ) as demo: | |
| gr.Markdown( | |
| """ | |
| # ๐ง SegFormer Cityscapes Semantic Segmentation | |
| ์ ๋ก๋ํ ์ด๋ฏธ์ง๋ฅผ ๋์์ผ๋ก **์๋งจํฑ ์ธ๊ทธ๋ฉํ ์ด์ **์ ์ํํฉ๋๋ค. | |
| (Model: SegFormer-B4, Dataset: Cityscapes) | |
| """ | |
| ) | |
| gr.HTML("<hr>") | |
| with gr.Row(variant="panel"): | |
| with gr.Column(scale=1, min_width=300): | |
| gr.Markdown("### 1๏ธโฃ ์ ๋ ฅ ์ด๋ฏธ์ง") | |
| input_image = gr.Image( | |
| type="numpy", | |
| label="์ ๋ ฅ ์ด๋ฏธ์ง (๋๋ก/๋์ ์ฅ๋ฉด ๊ถ์ฅ)", | |
| height=350, | |
| interactive=True, | |
| ) | |
| with gr.Row(): | |
| run_btn = gr.Button("๐ ์ธ๊ทธ๋ฉํ ์ด์ ์คํ", variant="primary") | |
| clear_btn = gr.Button("๐งน ์ด๊ธฐํ") | |
| gr.Markdown("### ๐ ์์ ์ด๋ฏธ์ง") | |
| gr.Examples( | |
| examples=[ | |
| "city1.jpg", | |
| "city2.jpg", | |
| "city3.jpg", | |
| "city4.jpeg", | |
| "city5.jpg", | |
| ], | |
| inputs=input_image, | |
| label="ํด๋ฆญํ์ฌ ๋ถ๋ฌ์ค๊ธฐ", | |
| ) | |
| with gr.Column(scale=2, min_width=450): | |
| gr.Markdown("### 2๏ธโฃ ์ธ๊ทธ๋ฉํ ์ด์ ๊ฒฐ๊ณผ (์ค๋ฒ๋ ์ด + ๋ผ๋ฒจ ๋ฒ๋ก)") | |
| result_plot = gr.Plot(label="Overlay + Legend") # โฌ ๏ธ ํ๋์ Plot๋ง | |
| # ๋ฒํผ ์ด๋ฒคํธ | |
| run_btn.click( | |
| fn=run_inference, | |
| inputs=input_image, | |
| outputs=result_plot, | |
| ) | |
| clear_btn.click( | |
| fn=lambda: None, | |
| inputs=None, | |
| outputs=result_plot, | |
| ) | |
| clear_btn.click( | |
| fn=lambda: None, | |
| inputs=None, | |
| outputs=input_image, | |
| ) | |
| # ----------------------------- | |
| # 6. ์คํ | |
| # ----------------------------- | |
| if __name__ == "__main__": | |
| demo.launch() | |