0jung commited on
Commit
cc3a22a
·
1 Parent(s): c988822
Files changed (1) hide show
  1. app.py +12 -49
app.py CHANGED
@@ -1,23 +1,15 @@
1
  import gradio as gr
2
-
3
- from matplotlib import gridspec
4
- import matplotlib.pyplot as plt
5
  import numpy as np
6
  from PIL import Image
7
- import tensorflow as tf
8
  from transformers import MaskFormerImageProcessor, MaskFormerForInstanceSegmentation
9
- import requests
10
 
11
- feature_extractor = MaskFormerImageProcessor.from_pretrained(
12
- "nvidia/segformer-b0-finetuned-cityscapes-1024-1024"
13
- )
14
  model = MaskFormerForInstanceSegmentation.from_pretrained(
15
  "nvidia/segformer-b0-finetuned-cityscapes-1024-1024"
16
  )
17
 
18
-
19
  def ade_palette():
20
- """ADE20K palette that maps each class to RGB values."""
21
  return [
22
  [204, 87, 92],
23
  [112, 185, 212],
@@ -170,16 +162,14 @@ def ade_palette():
170
  [28, 210, 99],
171
  ]
172
 
173
-
174
  labels_list = []
175
 
176
- with open(r'labels.txt', 'r') as fp:
177
  for line in fp:
178
  labels_list.append(line[:-1])
179
 
180
  colormap = np.asarray(ade_palette())
181
 
182
-
183
  def label_to_color_image(label):
184
  if label.ndim != 2:
185
  raise ValueError("Expect 2-D input label")
@@ -188,59 +178,32 @@ def label_to_color_image(label):
188
  raise ValueError("label value too large.")
189
  return colormap[label]
190
 
191
-
192
- def draw_plot(pred_img, seg):
193
- fig = plt.figure(figsize=(20, 15))
194
-
195
- grid_spec = gridspec.GridSpec(1, 2, width_ratios=[6, 1])
196
-
197
- plt.subplot(grid_spec[0])
198
- plt.imshow(pred_img)
199
- plt.axis('off')
200
- LABEL_NAMES = np.asarray(labels_list)
201
- FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
202
- FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)
203
-
204
- unique_labels = np.unique(seg.numpy().astype("uint8"))
205
- ax = plt.subplot(grid_spec[1])
206
- plt.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")
207
- ax.yaxis.tick_right()
208
- plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])
209
- plt.xticks([], [])
210
- ax.tick_params(width=0.0, labelsize=25)
211
- return fig
212
-
213
-
214
  def sepia(input_img):
215
  input_img = Image.fromarray(input_img)
 
 
 
216
 
217
- inputs = feature_extractor(images=input_img, return_tensors="tf")
218
  outputs = model(**inputs)
219
  logits = outputs.logits
220
 
221
- logits = tf.transpose(logits, [0, 2, 3, 1])
222
- logits = tf.image.resize(
223
- logits, input_img.size[::-1]
224
- ) # We reverse the shape of `image` because `image.size` returns width and height.
225
- seg = tf.math.argmax(logits, axis=-1)[0]
226
 
227
  color_seg = np.zeros(
228
  (seg.shape[0], seg.shape[1], 3), dtype=np.uint8
229
- ) # height, width, 3
230
  for label, color in enumerate(colormap):
231
- color_seg[seg.numpy() == label, :] = color
232
 
233
- # Show image + mask
234
  pred_img = np.array(input_img) * 0.5 + color_seg * 0.5
235
  pred_img = pred_img.astype(np.uint8)
236
 
237
- fig = draw_plot(pred_img, seg)
238
- return fig
239
-
240
 
241
  demo = gr.Interface(fn=sepia,
242
  inputs=gr.Image(shape=(400, 600)),
243
- outputs=['plot'],
244
  examples=["image-1.jpg", "image-2.jpg", "image-3.jpg", "image-4.jpeg", "image-5.jpg"],
245
  allow_flagging='never')
246
 
 
1
  import gradio as gr
 
 
 
2
  import numpy as np
3
  from PIL import Image
 
4
  from transformers import MaskFormerImageProcessor, MaskFormerForInstanceSegmentation
 
5
 
6
+ # Load the model using TensorFlow
 
 
7
  model = MaskFormerForInstanceSegmentation.from_pretrained(
8
  "nvidia/segformer-b0-finetuned-cityscapes-1024-1024"
9
  )
10
 
 
11
  def ade_palette():
12
+ # ADE20K palette that maps each class to RGB values
13
  return [
14
  [204, 87, 92],
15
  [112, 185, 212],
 
162
  [28, 210, 99],
163
  ]
164
 
 
165
  labels_list = []
166
 
167
+ with open('labels.txt', 'r') as fp:
168
  for line in fp:
169
  labels_list.append(line[:-1])
170
 
171
  colormap = np.asarray(ade_palette())
172
 
 
173
  def label_to_color_image(label):
174
  if label.ndim != 2:
175
  raise ValueError("Expect 2-D input label")
 
178
  raise ValueError("label value too large.")
179
  return colormap[label]
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  def sepia(input_img):
182
  input_img = Image.fromarray(input_img)
183
+ feature_extractor = MaskFormerImageProcessor.from_pretrained(
184
+ "nvidia/segformer-b0-finetuned-cityscapes-1024-1024"
185
+ )
186
 
187
+ inputs = feature_extractor(images=input_img)
188
  outputs = model(**inputs)
189
  logits = outputs.logits
190
 
191
+ seg = np.argmax(logits, axis=-1)
 
 
 
 
192
 
193
  color_seg = np.zeros(
194
  (seg.shape[0], seg.shape[1], 3), dtype=np.uint8
195
+ )
196
  for label, color in enumerate(colormap):
197
+ color_seg[seg == label, :] = color
198
 
 
199
  pred_img = np.array(input_img) * 0.5 + color_seg * 0.5
200
  pred_img = pred_img.astype(np.uint8)
201
 
202
+ return pred_img
 
 
203
 
204
  demo = gr.Interface(fn=sepia,
205
  inputs=gr.Image(shape=(400, 600)),
206
+ outputs=gr.Image(),
207
  examples=["image-1.jpg", "image-2.jpg", "image-3.jpg", "image-4.jpeg", "image-5.jpg"],
208
  allow_flagging='never')
209