task3 / app.py
ryujiho's picture
์ˆ˜์ •4
26a3918 verified
Raw History Blame Contribute Delete
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()