File size: 6,958 Bytes
9089a0a
 
26a3918
9089a0a
 
 
 
1d51f27
 
0a32a44
1d51f27
9089a0a
 
 
1d51f27
9089a0a
 
 
1d51f27
 
0a32a44
1d51f27
 
 
9089a0a
1d51f27
 
 
 
 
 
 
9089a0a
 
1d51f27
26a3918
0a32a44
 
 
 
 
 
1d51f27
9089a0a
1d51f27
 
 
 
26a3918
1d51f27
 
9089a0a
1d51f27
 
9089a0a
 
 
1d51f27
 
 
9089a0a
 
1d51f27
 
26a3918
1d51f27
26a3918
9089a0a
26a3918
 
 
9089a0a
1d51f27
 
 
9089a0a
 
 
26a3918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d51f27
26a3918
1d51f27
9089a0a
 
 
1d51f27
 
26a3918
1d51f27
9089a0a
 
26a3918
9089a0a
26a3918
1d51f27
 
 
 
 
9089a0a
 
 
 
 
 
 
1d51f27
9089a0a
1d51f27
9089a0a
 
 
0a32a44
9089a0a
1d51f27
0a32a44
9089a0a
 
26a3918
 
 
9089a0a
1d51f27
 
26a3918
1d51f27
0a32a44
 
26a3918
0a32a44
9089a0a
 
0a32a44
1d51f27
 
9089a0a
 
1d51f27
9089a0a
1d51f27
0a32a44
 
9089a0a
 
 
1d51f27
 
9089a0a
 
 
0a32a44
 
9089a0a
0a32a44
9089a0a
 
1d51f27
 
 
 
 
9089a0a
 
1d51f27
9089a0a
 
0a32a44
26a3918
 
 
 
9089a0a
 
 
26a3918
9089a0a
 
 
26a3918
 
 
 
 
 
9089a0a
26a3918
9089a0a
 
1d51f27
 
9089a0a
1d51f27
9089a0a
1d51f27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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()