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("