ryujiho commited on
Commit
0a32a44
·
verified ·
1 Parent(s): 9089a0a
Files changed (1) hide show
  1. app.py +81 -58
app.py CHANGED
@@ -1,31 +1,36 @@
1
  import gradio as gr
2
- from matplotlib import gridspec
3
  import matplotlib.pyplot as plt
4
  import numpy as np
5
  from PIL import Image
6
  import torch
7
  from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
8
-
 
9
  MODEL_ID = "nvidia/segformer-b4-finetuned-cityscapes-1024-1024"
10
  processor = AutoImageProcessor.from_pretrained(MODEL_ID)
11
  model = AutoModelForSemanticSegmentation.from_pretrained(MODEL_ID)
12
-
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
14
  model.to(device)
15
 
16
-
17
  def ade_palette():
 
18
  return [
19
  [204, 87, 92],[112, 185, 212],[45, 189, 106],[234, 123, 67],[78, 56, 123],[210, 32, 89],
20
  [90, 180, 56],[155, 102, 200],[33, 147, 176],[255, 183, 76],[67, 123, 89],[190, 60, 45],
21
  [134, 112, 200],[56, 45, 189],[200, 56, 123],[87, 92, 204],[120, 56, 123],[45, 78, 123],
22
- [112,117,119]
23
  ]
24
 
25
- labels_list = []
26
- with open("labels.txt", "r", encoding="utf-8") as fp:
27
- for line in fp:
28
- labels_list.append(line.rstrip("\n"))
 
 
 
 
 
29
 
30
  colormap = np.asarray(ade_palette(), dtype=np.uint8)
31
 
@@ -36,7 +41,7 @@ def label_to_color_image(label):
36
  raise ValueError("label value too large.")
37
  return colormap[label]
38
 
39
-
40
  def draw_legend(seg_np):
41
  """
42
  세그멘테이션 결과(seg_np)에서 등장한 클래스만 골라
@@ -48,104 +53,123 @@ def draw_legend(seg_np):
48
 
49
  unique_labels = np.unique(seg_np.astype("uint8"))
50
 
51
- fig, ax = plt.subplots(figsize=(4, 8))
 
52
  ax.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")
53
  ax.yaxis.tick_right()
54
  ax.set_yticks(range(len(unique_labels)))
55
- ax.set_yticklabels(LABEL_NAMES[unique_labels])
56
  ax.set_xticks([])
57
- ax.tick_params(width=0.0, labelsize=10)
 
 
 
 
58
  plt.tight_layout()
59
  return fig
60
 
61
-
62
  def run_inference(input_img):
63
- """
64
- Gradio에서 이미지를 받아:
65
- - 세그멘테이션 수행
66
- - 오버레이 이미지(np.array)
67
- - 범례 플롯(matplotlib Figure)
68
- 두 개를 반환.
69
- """
70
  if input_img is None:
71
  return None, None
72
 
73
-
74
  img = Image.fromarray(input_img.astype(np.uint8)) if isinstance(input_img, np.ndarray) else input_img
75
  if img.mode != "RGB":
76
  img = img.convert("RGB")
77
 
78
  inputs = processor(images=img, return_tensors="pt").to(device)
79
 
80
-
81
  with torch.no_grad():
82
  outputs = model(**inputs)
83
- logits = outputs.logits
84
 
85
  upsampled = torch.nn.functional.interpolate(
86
  logits, size=img.size[::-1], mode="bilinear", align_corners=False
87
  )
88
- seg = upsampled.argmax(dim=1)[0].cpu().numpy().astype(np.uint8)
89
 
90
-
91
- color_seg = colormap[seg]
92
  pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8)
93
 
94
  legend_fig = draw_legend(seg)
95
 
96
  return pred_img, legend_fig
97
 
98
-
99
- with gr.Blocks(title="Semantic Segmentation Demo") as demo:
 
 
 
100
  # 상단 제목/설명
101
  gr.Markdown(
102
  """
103
- # SegFormer Cityscapes Semantic Segmentation
104
- 업로드한 이미지를 대상으로 **시맨틱 세그멘테이션**을 수행합니다.
105
- 왼쪽에 이미지를 업로드한 뒤, `세그멘테이션 실행` 버튼을 눌러 결과를 확인해보세요.
106
  """
107
  )
 
108
 
109
- with gr.Row():
110
- # 왼쪽: 입력 / 버튼 / 예시
111
- with gr.Column(scale=1):
112
- gr.Markdown(" 입력 이미지")
113
  input_image = gr.Image(
114
  type="numpy",
115
  label="입력 이미지 (도로/도시 장면 권장)",
 
 
116
  )
117
 
118
  with gr.Row():
119
- run_btn = gr.Button("세그멘테이션 실행")
120
- clear_btn = gr.Button(" 초기화")
 
121
 
122
- gr.Markdown("예시 이미지")
123
  gr.Examples(
124
  examples=[
125
- "city1.jpg",
126
- "city2.jpg",
127
- "city3.jpg",
128
- "city4.jpeg",
129
- "city5.jpg",
130
  ],
131
  inputs=input_image,
 
 
132
  )
133
 
134
- # 오른쪽: 결과 탭 (오버레이 / 범례)
135
- with gr.Column(scale=2):
136
- gr.Markdown("세그멘테이션 결과")
137
-
138
- with gr.Tab("오버레이 결과"):
139
- overlay_out = gr.Image(label="원본 + 세그멘테이션 오버레이")
140
-
141
- with gr.Tab("라벨 범례"):
142
- legend_out = gr.Plot(label="클래스별 색상 및 이름")
143
-
144
- # 버튼 동작 연결
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  run_btn.click(
146
  fn=run_inference,
147
  inputs=input_image,
148
  outputs=[overlay_out, legend_out],
 
 
149
  )
150
 
151
  # 초기화 버튼: 입력/출력 모두 리셋
@@ -153,10 +177,9 @@ with gr.Blocks(title="Semantic Segmentation Demo") as demo:
153
  fn=lambda: (None, None, None),
154
  inputs=None,
155
  outputs=[input_image, overlay_out, legend_out],
 
156
  )
157
 
158
- # -----------------------------
159
  # 6. 실행
160
- # -----------------------------
161
  if __name__ == "__main__":
162
- demo.launch()
 
1
  import gradio as gr
 
2
  import matplotlib.pyplot as plt
3
  import numpy as np
4
  from PIL import Image
5
  import torch
6
  from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
7
+ # (기존에 정의된 함수들은 그대로 사용)
8
+ # 1. 모델 및 프로세서 로드
9
  MODEL_ID = "nvidia/segformer-b4-finetuned-cityscapes-1024-1024"
10
  processor = AutoImageProcessor.from_pretrained(MODEL_ID)
11
  model = AutoModelForSemanticSegmentation.from_pretrained(MODEL_ID)
 
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
13
  model.to(device)
14
 
15
+ # 2. 팔레트 & 라벨 로딩
16
  def ade_palette():
17
+ """테스트용 18개 클래스 팔레트 (라벨 개수 18개와 맞춤)."""
18
  return [
19
  [204, 87, 92],[112, 185, 212],[45, 189, 106],[234, 123, 67],[78, 56, 123],[210, 32, 89],
20
  [90, 180, 56],[155, 102, 200],[33, 147, 176],[255, 183, 76],[67, 123, 89],[190, 60, 45],
21
  [134, 112, 200],[56, 45, 189],[200, 56, 123],[87, 92, 204],[120, 56, 123],[45, 78, 123],
22
+ [112,117,119] # 19th color (cityscapes has 19 classes)
23
  ]
24
 
25
+ # !!! 'labels.txt' 파일이 현재 환경에 있다고 가정합니다.
26
+ try:
27
+ labels_list = []
28
+ with open("labels.txt", "r", encoding="utf-8") as fp:
29
+ for line in fp:
30
+ labels_list.append(line.rstrip("\n"))
31
+ except FileNotFoundError:
32
+ # labels.txt 파일이 없을 경우 임시 라벨 사용 (실제 라벨은 Cityscapes 기준 19개)
33
+ labels_list = [f"Class {i+1}" for i in range(19)]
34
 
35
  colormap = np.asarray(ade_palette(), dtype=np.uint8)
36
 
 
41
  raise ValueError("label value too large.")
42
  return colormap[label]
43
 
44
+ # 3. 범례용 플롯 생성 함수
45
  def draw_legend(seg_np):
46
  """
47
  세그멘테이션 결과(seg_np)에서 등장한 클래스만 골라
 
53
 
54
  unique_labels = np.unique(seg_np.astype("uint8"))
55
 
56
+ # Matplotlib 스타일링 개선
57
+ fig, ax = plt.subplots(figsize=(4, 8), facecolor='#F9FAFB') # 배경색 설정
58
  ax.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")
59
  ax.yaxis.tick_right()
60
  ax.set_yticks(range(len(unique_labels)))
61
+ ax.set_yticklabels(LABEL_NAMES[unique_labels], fontsize=10)
62
  ax.set_xticks([])
63
+ ax.tick_params(width=0.0, length=0.0) # 틱 표시 없앰
64
+ ax.spines['right'].set_visible(False) # 축 경계선 제거
65
+ ax.spines['left'].set_visible(False)
66
+ ax.spines['top'].set_visible(False)
67
+ ax.spines['bottom'].set_visible(False)
68
  plt.tight_layout()
69
  return fig
70
 
71
+ # 4. 추론 함수 (기존과 동일)
72
  def run_inference(input_img):
 
 
 
 
 
 
 
73
  if input_img is None:
74
  return None, None
75
 
 
76
  img = Image.fromarray(input_img.astype(np.uint8)) if isinstance(input_img, np.ndarray) else input_img
77
  if img.mode != "RGB":
78
  img = img.convert("RGB")
79
 
80
  inputs = processor(images=img, return_tensors="pt").to(device)
81
 
 
82
  with torch.no_grad():
83
  outputs = model(**inputs)
84
+ logits = outputs.logits
85
 
86
  upsampled = torch.nn.functional.interpolate(
87
  logits, size=img.size[::-1], mode="bilinear", align_corners=False
88
  )
89
+ seg = upsampled.argmax(dim=1)[0].cpu().numpy().astype(np.uint8)
90
 
91
+ color_seg = colormap[seg]
 
92
  pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8)
93
 
94
  legend_fig = draw_legend(seg)
95
 
96
  return pred_img, legend_fig
97
 
98
+ # 5. Gradio UI (Blocks로 보너스 노리기) - **개선된 부분**
99
+ with gr.Blocks(
100
+ title="Semantic Segmentation Demo",
101
+ theme=gr.themes.Monochrome() # 테마를 Monochrome으로 변경하여 깔끔하고 모던한 느낌을 줍니다.
102
+ ) as demo:
103
  # 상단 제목/설명
104
  gr.Markdown(
105
  """
106
+ # 🧠 SegFormer Cityscapes Semantic Segmentation
107
+ 업로드한 이미지를 대상으로 **시맨틱 세그멘테이��**을 수행합니다. (Model: SegFormer-B4, Dataset: Cityscapes)
 
108
  """
109
  )
110
+ gr.HTML("<hr>") # 구분선 추가
111
 
112
+ with gr.Row(variant="panel"): # 섹션을 패널로 묶어 시각적 경계 명확화
113
+ # ⬅️ 왼쪽: 입력 및 컨트롤
114
+ with gr.Column(scale=1, min_width=300):
115
+ gr.Markdown("### 1️⃣ 입력 이미지")
116
  input_image = gr.Image(
117
  type="numpy",
118
  label="입력 이미지 (도로/도시 장면 권장)",
119
+ height=350, # 높이 고정
120
+ interactive=True, # 이미지 드래그앤드롭/클릭으로 업로드 가능
121
  )
122
 
123
  with gr.Row():
124
+ # 버튼 강조
125
+ run_btn = gr.Button("🚀 세그멘테이션 실행", variant="primary")
126
+ clear_btn = gr.Button("🧹 초기화")
127
 
128
+ gr.Markdown("### 🔍 예시 이미지")
129
  gr.Examples(
130
  examples=[
131
+ "city1.jpg", "city2.jpg", "city3.jpg", "city4.jpeg", "city5.jpg"
 
 
 
 
132
  ],
133
  inputs=input_image,
134
+ label="클릭하여 로드하세요",
135
+ # examples_per_page=5 # 모든 예시를 한 줄에 표시
136
  )
137
 
138
+ # ➡️ 오른쪽: 결과 탭 (오버레이 / 범례)
139
+ with gr.Column(scale=2, min_width=450):
140
+ gr.Markdown("### 2️⃣ 세그멘테이션 결과")
141
+
142
+ # 탭 컴포넌트 사용
143
+ with gr.Tabs(selected=0):
144
+ with gr.TabItem("🖼️ 오버레이 결과"):
145
+ overlay_out = gr.Image(
146
+ label="원본 + 세그멘테이션 오버레이 (50% 투명도)",
147
+ height=400, # 높이 고정
148
+ interactive=False # 결과 이미지는 상호작용 불가
149
+ )
150
+
151
+ with gr.TabItem("📋 라벨 범례"):
152
+ # 결과 이미지와 범례를 수평으로 배치하기 위해 Row 사용 (선택 사항)
153
+ with gr.Row():
154
+ legend_out = gr.Plot(label="클래스별 색상 및 이름", height=400)
155
+ # 범례에 대한 간단한 설명 추가
156
+ gr.Markdown(
157
+ """
158
+ <div style="padding: 10px; background-color: #f0f0f0; border-radius: 5px;">
159
+ **💡 참고:** 이 범례에는 이미지 분석 결과에 실제로 등장한 클래스만 표시됩니다.
160
+ </div>
161
+ """,
162
+ scale=0
163
+ )
164
+
165
+
166
+ # 버튼 동작 연결 (기존과 동일)
167
  run_btn.click(
168
  fn=run_inference,
169
  inputs=input_image,
170
  outputs=[overlay_out, legend_out],
171
+ # API 호출 중 로딩 표시
172
+ queue=False
173
  )
174
 
175
  # 초기화 버튼: 입력/출력 모두 리셋
 
177
  fn=lambda: (None, None, None),
178
  inputs=None,
179
  outputs=[input_image, overlay_out, legend_out],
180
+ queue=False
181
  )
182
 
 
183
  # 6. 실행
 
184
  if __name__ == "__main__":
185
+ demo.launch()