수정4
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import matplotlib.pyplot as plt
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
| 5 |
import torch
|
|
@@ -32,22 +33,20 @@ def cityscapes_palette():
|
|
| 32 |
]
|
| 33 |
|
| 34 |
|
| 35 |
-
# labels.txt: Cityscapes 순서대로 19줄 (road
|
| 36 |
try:
|
| 37 |
labels_list = []
|
| 38 |
with open("labels.txt", "r", encoding="utf-8") as fp:
|
| 39 |
for line in fp:
|
| 40 |
labels_list.append(line.rstrip("\n"))
|
| 41 |
except FileNotFoundError:
|
| 42 |
-
# 예비용 라벨 (labels.txt 없을 때)
|
| 43 |
labels_list = [f"Class {i}" for i in range(19)]
|
| 44 |
|
| 45 |
-
# 팔레트와 라벨 개수 맞추기 (예: 라벨 개수 변경 시 대비)
|
| 46 |
base_cmap = np.asarray(cityscapes_palette(), dtype=np.uint8)
|
| 47 |
if len(labels_list) <= len(base_cmap):
|
| 48 |
colormap = base_cmap[: len(labels_list)]
|
| 49 |
else:
|
| 50 |
-
# 라벨이 더 많
|
| 51 |
repeat = int(np.ceil(len(labels_list) / len(base_cmap)))
|
| 52 |
colormap = np.tile(base_cmap, (repeat, 1))[: len(labels_list)]
|
| 53 |
|
|
@@ -63,12 +62,13 @@ def label_to_color_image(label: np.ndarray) -> np.ndarray:
|
|
| 63 |
|
| 64 |
|
| 65 |
# -----------------------------
|
| 66 |
-
# 3. 범례
|
| 67 |
# -----------------------------
|
| 68 |
-
def
|
| 69 |
"""
|
| 70 |
-
세그멘테이션
|
| 71 |
-
색상 패치 + 라벨 이름
|
|
|
|
| 72 |
"""
|
| 73 |
label_names = np.asarray(labels_list)
|
| 74 |
full_label_map = np.arange(len(label_names)).reshape(len(label_names), 1)
|
|
@@ -76,30 +76,41 @@ def draw_legend(seg_np: np.ndarray):
|
|
| 76 |
|
| 77 |
unique_labels = np.unique(seg_np.astype("uint8"))
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
for spine in ["right", "left", "top", "bottom"]:
|
| 89 |
-
|
| 90 |
|
| 91 |
plt.tight_layout()
|
| 92 |
return fig
|
| 93 |
|
| 94 |
|
| 95 |
# -----------------------------
|
| 96 |
-
# 4. 추론 함수
|
| 97 |
# -----------------------------
|
| 98 |
def run_inference(input_img):
|
| 99 |
if input_img is None:
|
| 100 |
-
return None
|
| 101 |
|
| 102 |
-
#
|
| 103 |
img = (
|
| 104 |
Image.fromarray(input_img.astype(np.uint8))
|
| 105 |
if isinstance(input_img, np.ndarray)
|
|
@@ -124,18 +135,18 @@ def run_inference(input_img):
|
|
| 124 |
color_seg = colormap[seg]
|
| 125 |
pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8)
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
|
|
|
| 129 |
|
| 130 |
|
| 131 |
# -----------------------------
|
| 132 |
-
# 5. Gradio UI (Blocks)
|
| 133 |
# -----------------------------
|
| 134 |
with gr.Blocks(
|
| 135 |
title="Semantic Segmentation Demo",
|
| 136 |
-
theme=gr.themes.Soft(),
|
| 137 |
) as demo:
|
| 138 |
-
# 상단 제목/설명
|
| 139 |
gr.Markdown(
|
| 140 |
"""
|
| 141 |
# 🧠 SegFormer Cityscapes Semantic Segmentation
|
|
@@ -146,7 +157,6 @@ with gr.Blocks(
|
|
| 146 |
gr.HTML("<hr>")
|
| 147 |
|
| 148 |
with gr.Row(variant="panel"):
|
| 149 |
-
# ⬅️ 왼쪽: 입력 및 컨트롤
|
| 150 |
with gr.Column(scale=1, min_width=300):
|
| 151 |
gr.Markdown("### 1️⃣ 입력 이미지")
|
| 152 |
input_image = gr.Image(
|
|
@@ -173,41 +183,26 @@ with gr.Blocks(
|
|
| 173 |
label="클릭하여 불러오기",
|
| 174 |
)
|
| 175 |
|
| 176 |
-
# ➡️ 오른쪽: 결과 탭 (오버레이 / 범례)
|
| 177 |
with gr.Column(scale=2, min_width=450):
|
| 178 |
-
gr.Markdown("### 2️⃣ 세그멘테이션 결과")
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
overlay_out = gr.Image(
|
| 183 |
-
label="원본 + 세그멘테이션 오버레이 (50% 투명도)",
|
| 184 |
-
height=400,
|
| 185 |
-
interactive=False,
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
with gr.Tab("📋 라벨 범례"):
|
| 189 |
-
with gr.Row():
|
| 190 |
-
legend_out = gr.Plot(label="클래스별 색상 및 이름") # height 제거!
|
| 191 |
-
gr.Markdown(
|
| 192 |
-
"""
|
| 193 |
-
<div style="padding: 10px; background-color: #f0f0f0; border-radius: 5px;">
|
| 194 |
-
<b>💡 참고:</b> 이 범례에는 이미지 분석 결과에 <u>실제로 등장한 클래스만</u> 표시됩니다.
|
| 195 |
-
</div>
|
| 196 |
-
""",
|
| 197 |
-
)
|
| 198 |
-
|
| 199 |
-
# 버튼 동작 연결
|
| 200 |
run_btn.click(
|
| 201 |
fn=run_inference,
|
| 202 |
inputs=input_image,
|
| 203 |
-
outputs=
|
| 204 |
)
|
| 205 |
|
| 206 |
-
# 초기화 버튼: 입력/출력 리셋
|
| 207 |
clear_btn.click(
|
| 208 |
-
fn=lambda:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
inputs=None,
|
| 210 |
-
outputs=
|
| 211 |
)
|
| 212 |
|
| 213 |
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import matplotlib.pyplot as plt
|
| 3 |
+
from matplotlib import gridspec
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image
|
| 6 |
import torch
|
|
|
|
| 33 |
]
|
| 34 |
|
| 35 |
|
| 36 |
+
# labels.txt: Cityscapes 순서대로 19줄 (road ~ bicycle) 있다고 가정
|
| 37 |
try:
|
| 38 |
labels_list = []
|
| 39 |
with open("labels.txt", "r", encoding="utf-8") as fp:
|
| 40 |
for line in fp:
|
| 41 |
labels_list.append(line.rstrip("\n"))
|
| 42 |
except FileNotFoundError:
|
|
|
|
| 43 |
labels_list = [f"Class {i}" for i in range(19)]
|
| 44 |
|
|
|
|
| 45 |
base_cmap = np.asarray(cityscapes_palette(), dtype=np.uint8)
|
| 46 |
if len(labels_list) <= len(base_cmap):
|
| 47 |
colormap = base_cmap[: len(labels_list)]
|
| 48 |
else:
|
| 49 |
+
# 라벨이 더 많아도 안 터지게 색 반복
|
| 50 |
repeat = int(np.ceil(len(labels_list) / len(base_cmap)))
|
| 51 |
colormap = np.tile(base_cmap, (repeat, 1))[: len(labels_list)]
|
| 52 |
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
# -----------------------------
|
| 65 |
+
# 3. 오버레이 + 범례 한 장에 그리는 함수
|
| 66 |
# -----------------------------
|
| 67 |
+
def draw_overlay_with_legend(pred_img: np.ndarray, seg_np: np.ndarray):
|
| 68 |
"""
|
| 69 |
+
왼쪽: 세그멘테이션 오버레이
|
| 70 |
+
오른쪽: 이 장면에 등장한 클래스들의 색상 패치 + 라벨 이름
|
| 71 |
+
을 한 Figure 안에 그려서 반환.
|
| 72 |
"""
|
| 73 |
label_names = np.asarray(labels_list)
|
| 74 |
full_label_map = np.arange(len(label_names)).reshape(len(label_names), 1)
|
|
|
|
| 76 |
|
| 77 |
unique_labels = np.unique(seg_np.astype("uint8"))
|
| 78 |
|
| 79 |
+
# 전체 Figure: 왼쪽(큰) + 오른쪽(좁은 범례)
|
| 80 |
+
fig = plt.figure(figsize=(10, 6))
|
| 81 |
+
gs = gridspec.GridSpec(1, 2, width_ratios=[4, 1])
|
| 82 |
+
|
| 83 |
+
# --- 왼쪽: 오버레이 ---
|
| 84 |
+
ax0 = plt.subplot(gs[0])
|
| 85 |
+
ax0.imshow(pred_img)
|
| 86 |
+
ax0.axis("off")
|
| 87 |
+
ax0.set_title("Overlay", fontsize=12)
|
| 88 |
+
|
| 89 |
+
# --- 오른쪽: 범례 ---
|
| 90 |
+
ax1 = plt.subplot(gs[1])
|
| 91 |
+
ax1.imshow(full_color_map[unique_labels].astype(np.uint8), interpolation="nearest")
|
| 92 |
+
ax1.yaxis.tick_right()
|
| 93 |
+
ax1.set_yticks(range(len(unique_labels)))
|
| 94 |
+
ax1.set_yticklabels(label_names[unique_labels], fontsize=10)
|
| 95 |
+
ax1.set_xticks([])
|
| 96 |
+
|
| 97 |
+
# 테두리/틱 정리
|
| 98 |
+
ax1.tick_params(width=0.0, length=0.0)
|
| 99 |
for spine in ["right", "left", "top", "bottom"]:
|
| 100 |
+
ax1.spines[spine].set_visible(False)
|
| 101 |
|
| 102 |
plt.tight_layout()
|
| 103 |
return fig
|
| 104 |
|
| 105 |
|
| 106 |
# -----------------------------
|
| 107 |
+
# 4. 추론 함수: Figure 하나만 반환
|
| 108 |
# -----------------------------
|
| 109 |
def run_inference(input_img):
|
| 110 |
if input_img is None:
|
| 111 |
+
return None
|
| 112 |
|
| 113 |
+
# numpy -> PIL
|
| 114 |
img = (
|
| 115 |
Image.fromarray(input_img.astype(np.uint8))
|
| 116 |
if isinstance(input_img, np.ndarray)
|
|
|
|
| 135 |
color_seg = colormap[seg]
|
| 136 |
pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8)
|
| 137 |
|
| 138 |
+
# 👉 여기서 바로 "오버레이 + 범례 한 장" Figure 생성
|
| 139 |
+
fig = draw_overlay_with_legend(pred_img, seg)
|
| 140 |
+
return fig
|
| 141 |
|
| 142 |
|
| 143 |
# -----------------------------
|
| 144 |
+
# 5. Gradio UI (심플한 Blocks + Plot 하나)
|
| 145 |
# -----------------------------
|
| 146 |
with gr.Blocks(
|
| 147 |
title="Semantic Segmentation Demo",
|
| 148 |
+
theme=gr.themes.Soft(),
|
| 149 |
) as demo:
|
|
|
|
| 150 |
gr.Markdown(
|
| 151 |
"""
|
| 152 |
# 🧠 SegFormer Cityscapes Semantic Segmentation
|
|
|
|
| 157 |
gr.HTML("<hr>")
|
| 158 |
|
| 159 |
with gr.Row(variant="panel"):
|
|
|
|
| 160 |
with gr.Column(scale=1, min_width=300):
|
| 161 |
gr.Markdown("### 1️⃣ 입력 이미지")
|
| 162 |
input_image = gr.Image(
|
|
|
|
| 183 |
label="클릭하여 불러오기",
|
| 184 |
)
|
| 185 |
|
|
|
|
| 186 |
with gr.Column(scale=2, min_width=450):
|
| 187 |
+
gr.Markdown("### 2️⃣ 세그멘테이션 결과 (오버레이 + 라벨 범례)")
|
| 188 |
+
result_plot = gr.Plot(label="Overlay + Legend") # ⬅️ 하나의 Plot만
|
| 189 |
+
|
| 190 |
+
# 버튼 이벤트
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
run_btn.click(
|
| 192 |
fn=run_inference,
|
| 193 |
inputs=input_image,
|
| 194 |
+
outputs=result_plot,
|
| 195 |
)
|
| 196 |
|
|
|
|
| 197 |
clear_btn.click(
|
| 198 |
+
fn=lambda: None,
|
| 199 |
+
inputs=None,
|
| 200 |
+
outputs=result_plot,
|
| 201 |
+
)
|
| 202 |
+
clear_btn.click(
|
| 203 |
+
fn=lambda: None,
|
| 204 |
inputs=None,
|
| 205 |
+
outputs=input_image,
|
| 206 |
)
|
| 207 |
|
| 208 |
|