kacorn commited on
Commit
03799df
ยท
verified ยท
1 Parent(s): 1a53c5c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -105
app.py CHANGED
@@ -1,105 +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-b5-finetuned-ade-640-640"
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()
 
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-b5-finetuned-ade-640-640"
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],[255, 0, 0]
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()