kacorn commited on
Commit
6453410
·
verified ·
1 Parent(s): acb03df

Upload 6 files

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. app.py +105 -0
  3. city-1.jpg +3 -0
  4. city-2.jpg +3 -0
  5. city-3.jpeg +3 -0
  6. city-4.jpg +3 -0
  7. city-5.jpg +3 -0
.gitattributes CHANGED
@@ -38,3 +38,4 @@ city-2.jpg filter=lfs diff=lfs merge=lfs -text
38
  city-3.jpg filter=lfs diff=lfs merge=lfs -text
39
  city-4.jpg filter=lfs diff=lfs merge=lfs -text
40
  city-5.jpg filter=lfs diff=lfs merge=lfs -text
 
 
38
  city-3.jpg filter=lfs diff=lfs merge=lfs -text
39
  city-4.jpg filter=lfs diff=lfs merge=lfs -text
40
  city-5.jpg filter=lfs diff=lfs merge=lfs -text
41
+ city-3.jpeg filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-b0-finetuned-cityscapes-512-1024"
10
+ processor = AutoImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-cityscapes-512-1024")
11
+ model = AutoModelForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-cityscapes-512-1024")
12
+
13
+ def ade_palette():
14
+ """ADE20K palette that maps each class to RGB values."""
15
+ return [
16
+ [204, 87, 92],[112, 185, 212],[45, 189, 106],[234, 123, 67],[78, 56, 123],[210, 32, 89],
17
+ [90, 180, 56],[155, 102, 200],[33, 147, 176],[255, 183, 76],[67, 123, 89],[190, 60, 45],
18
+ [134, 112, 200],[56, 45, 189],[200, 56, 123],[87, 92, 204],[120, 56, 123],[45, 78, 123],
19
+ ]
20
+
21
+ labels_list = []
22
+ with open("labels.txt", "r", encoding="utf-8") as fp:
23
+ for line in fp:
24
+ labels_list.append(line.rstrip("\n"))
25
+
26
+ colormap = np.asarray(ade_palette(), dtype=np.uint8)
27
+
28
+ def label_to_color_image(label):
29
+ if label.ndim != 2:
30
+ raise ValueError("Expect 2-D input label")
31
+ if np.max(label) >= len(colormap):
32
+ raise ValueError("label value too large.")
33
+ return colormap[label]
34
+
35
+ def draw_plot(pred_img, seg_np):
36
+ fig = plt.figure(figsize=(20, 15))
37
+ grid_spec = gridspec.GridSpec(1, 2, width_ratios=[6, 1])
38
+
39
+ plt.subplot(grid_spec[0])
40
+ plt.imshow(pred_img)
41
+ plt.axis('off')
42
+
43
+ LABEL_NAMES = np.asarray(labels_list)
44
+ FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
45
+ FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)
46
+
47
+ unique_labels = np.unique(seg_np.astype("uint8"))
48
+ ax = plt.subplot(grid_spec[1])
49
+ plt.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")
50
+ ax.yaxis.tick_right()
51
+ plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])
52
+ plt.xticks([], [])
53
+ ax.tick_params(width=0.0, labelsize=25)
54
+ return fig
55
+
56
+ def run_inference(input_img):
57
+ # input: numpy array from gradio -> PIL
58
+ img = Image.fromarray(input_img.astype(np.uint8)) if isinstance(input_img, np.ndarray) else input_img
59
+ if img.mode != "RGB":
60
+ img = img.convert("RGB")
61
+
62
+ inputs = processor(images=img, return_tensors="pt")
63
+ with torch.no_grad():
64
+ outputs = model(**inputs)
65
+ logits = outputs.logits # (1, C, h/4, w/4)
66
+
67
+ # resize to original
68
+ upsampled = torch.nn.functional.interpolate(
69
+ logits, size=img.size[::-1], mode="bilinear", align_corners=False
70
+ )
71
+ seg = upsampled.argmax(dim=1)[0].cpu().numpy().astype(np.uint8) # (H,W)
72
+
73
+ # colorize & overlay
74
+ color_seg = colormap[seg] # (H,W,3)
75
+ pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8)
76
+
77
+ fig = draw_plot(pred_img, seg)
78
+ return fig
79
+
80
+ with gr.Blocks(title="City Segmentation Demo") as demo:
81
+ gr.Markdown("# 🏙️ 도시 이미지 시맨틱 세그멘테이션")
82
+ gr.Markdown("이미지를 업로드하면 SegFormer가 도로, 건물, 하늘 등을 색상으로 구분합니다.")
83
+
84
+ with gr.Row():
85
+ with gr.Column(scale=1):
86
+ input_image = gr.Image(type="numpy", label="입력 이미지")
87
+ run_button = gr.Button("🔍 분석 실행")
88
+ gr.Examples(
89
+ examples=[
90
+ ["city-1.jpg"],
91
+ ["city-2.jpg"],
92
+ ["city-3.jpeg"],
93
+ ["city-4.jpg"],
94
+ ["city-5.jpg"],
95
+ ],
96
+ inputs=input_image
97
+ )
98
+
99
+ with gr.Column(scale=2):
100
+ output_plot = gr.Plot(label="결과 (Segmentation Overlay + Legend)")
101
+
102
+ run_button.click(fn=run_inference, inputs=input_image, outputs=output_plot)
103
+
104
+ if __name__ == "__main__":
105
+ demo.launch()
city-1.jpg ADDED

Git LFS Details

  • SHA256: a1ad943af90adc83ece5bfefd0ac779eec1f7e163cb1916e91aa2c44f6a07e9f
  • Pointer size: 131 Bytes
  • Size of remote file: 269 kB
city-2.jpg ADDED

Git LFS Details

  • SHA256: 9e3bb67a3f2fc2d44a3e330a2144de152d181f57f7f223ef139fe3300e2c97b3
  • Pointer size: 131 Bytes
  • Size of remote file: 366 kB
city-3.jpeg ADDED

Git LFS Details

  • SHA256: cfaeef10a76621feee92225c6f1cb2a96bff952fff5ef1f34e6cabc4771804e4
  • Pointer size: 131 Bytes
  • Size of remote file: 138 kB
city-4.jpg ADDED

Git LFS Details

  • SHA256: 3b7da6fe0cdeaac0452b7e74f5475927186541dcfca18ff731087d681179f28e
  • Pointer size: 131 Bytes
  • Size of remote file: 230 kB
city-5.jpg ADDED

Git LFS Details

  • SHA256: 889227732e1120f4bccde2e697e2158b8fe76848e467dabb4326319339bac0ca
  • Pointer size: 132 Bytes
  • Size of remote file: 1.48 MB