ockkjs commited on
Commit
c53ddb3
·
1 Parent(s): 72a9da8

"second commit"

Browse files
Files changed (2) hide show
  1. app.py +43 -43
  2. requirements.txt +3 -3
app.py CHANGED
@@ -1,18 +1,14 @@
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 SegformerFeatureExtractor, TFSegformerForSemanticSegmentation
9
 
10
- feature_extractor = SegformerFeatureExtractor.from_pretrained(
11
- "nvidia/segformer-b5-finetuned-ade-640-640"
12
- )
13
- model = TFSegformerForSemanticSegmentation.from_pretrained(
14
- "nvidia/segformer-b5-finetuned-ade-640-640"
15
- )
16
 
17
  def ade_palette():
18
  """ADE20K palette that maps each class to RGB values."""
@@ -38,34 +34,32 @@ def ade_palette():
38
  ]
39
 
40
  labels_list = []
41
-
42
- with open(r'labels.txt', 'r') as fp:
43
  for line in fp:
44
- labels_list.append(line[:-1])
45
 
46
- colormap = np.asarray(ade_palette())
47
 
48
  def label_to_color_image(label):
49
  if label.ndim != 2:
50
  raise ValueError("Expect 2-D input label")
51
-
52
  if np.max(label) >= len(colormap):
53
  raise ValueError("label value too large.")
54
  return colormap[label]
55
 
56
- def draw_plot(pred_img, seg):
57
  fig = plt.figure(figsize=(20, 15))
58
-
59
  grid_spec = gridspec.GridSpec(1, 2, width_ratios=[6, 1])
60
 
61
  plt.subplot(grid_spec[0])
62
  plt.imshow(pred_img)
63
  plt.axis('off')
 
64
  LABEL_NAMES = np.asarray(labels_list)
65
  FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
66
  FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)
67
 
68
- unique_labels = np.unique(seg.numpy().astype("uint8"))
69
  ax = plt.subplot(grid_spec[1])
70
  plt.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")
71
  ax.yaxis.tick_right()
@@ -74,37 +68,43 @@ def draw_plot(pred_img, seg):
74
  ax.tick_params(width=0.0, labelsize=25)
75
  return fig
76
 
77
- def sepia(input_img):
78
- input_img = Image.fromarray(input_img)
79
-
80
- inputs = feature_extractor(images=input_img, return_tensors="tf")
81
- outputs = model(**inputs)
82
- logits = outputs.logits
83
 
84
- logits = tf.transpose(logits, [0, 2, 3, 1])
85
- logits = tf.image.resize(
86
- logits, input_img.size[::-1]
87
- ) # We reverse the shape of `image` because `image.size` returns width and height.
88
- seg = tf.math.argmax(logits, axis=-1)[0]
89
 
90
- color_seg = np.zeros(
91
- (seg.shape[0], seg.shape[1], 3), dtype=np.uint8
92
- ) # height, width, 3
93
- for label, color in enumerate(colormap):
94
- color_seg[seg.numpy() == label, :] = color
95
 
96
- # Show image + mask
97
- pred_img = np.array(input_img) * 0.5 + color_seg * 0.5
98
- pred_img = pred_img.astype(np.uint8)
99
 
100
  fig = draw_plot(pred_img, seg)
101
  return fig
102
 
103
- demo = gr.Interface(fn=sepia,
104
- inputs=gr.Image(shape=(400, 600)),
105
- outputs=['plot'],
106
- examples=["person-1.jpg", "person-2.jpg", "person-3.jpg", "person-4.jpg", "person-5.jpg"],
107
- allow_flagging='never')
108
-
 
 
 
 
 
 
 
109
 
110
- 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(MODEL_ID)
11
+ model = AutoModelForSemanticSegmentation.from_pretrained(MODEL_ID)
 
 
 
12
 
13
  def ade_palette():
14
  """ADE20K palette that maps each class to RGB values."""
 
34
  ]
35
 
36
  labels_list = []
37
+ with open("labels.txt", "r", encoding="utf-8") as fp:
 
38
  for line in fp:
39
+ labels_list.append(line.rstrip("\n"))
40
 
41
+ colormap = np.asarray(ade_palette(), dtype=np.uint8)
42
 
43
  def label_to_color_image(label):
44
  if label.ndim != 2:
45
  raise ValueError("Expect 2-D input label")
 
46
  if np.max(label) >= len(colormap):
47
  raise ValueError("label value too large.")
48
  return colormap[label]
49
 
50
+ def draw_plot(pred_img, seg_np):
51
  fig = plt.figure(figsize=(20, 15))
 
52
  grid_spec = gridspec.GridSpec(1, 2, width_ratios=[6, 1])
53
 
54
  plt.subplot(grid_spec[0])
55
  plt.imshow(pred_img)
56
  plt.axis('off')
57
+
58
  LABEL_NAMES = np.asarray(labels_list)
59
  FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
60
  FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)
61
 
62
+ unique_labels = np.unique(seg_np.astype("uint8"))
63
  ax = plt.subplot(grid_spec[1])
64
  plt.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")
65
  ax.yaxis.tick_right()
 
68
  ax.tick_params(width=0.0, labelsize=25)
69
  return fig
70
 
71
+ def run_inference(input_img):
72
+ # input: numpy array from gradio -> PIL
73
+ img = Image.fromarray(input_img.astype(np.uint8)) if isinstance(input_img, np.ndarray) else input_img
74
+ if img.mode != "RGB":
75
+ img = img.convert("RGB")
 
76
 
77
+ inputs = processor(images=img, return_tensors="pt")
78
+ with torch.no_grad():
79
+ outputs = model(**inputs)
80
+ logits = outputs.logits # (1, C, h/4, w/4)
 
81
 
82
+ # resize to original
83
+ upsampled = torch.nn.functional.interpolate(
84
+ logits, size=img.size[::-1], mode="bilinear", align_corners=False
85
+ )
86
+ seg = upsampled.argmax(dim=1)[0].cpu().numpy().astype(np.uint8) # (H,W)
87
 
88
+ # colorize & overlay
89
+ color_seg = colormap[seg] # (H,W,3)
90
+ pred_img = (np.array(img) * 0.5 + color_seg * 0.5).astype(np.uint8)
91
 
92
  fig = draw_plot(pred_img, seg)
93
  return fig
94
 
95
+ demo = gr.Interface(
96
+ fn=run_inference,
97
+ inputs=gr.Image(type="numpy", label="Input Image"),
98
+ outputs=gr.Plot(label="Overlay + Legend"),
99
+ examples=[
100
+ "ADE_val_00000001.jpeg",
101
+ "ADE_val_00001159.jpg",
102
+ "ADE_val_00001248.jpg",
103
+ "ADE_val_00001472.jpg"
104
+ ],
105
+ flagging_mode="never",
106
+ cache_examples=False,
107
+ )
108
 
109
+ if __name__ == "__main__":
110
+ demo.launch()
requirements.txt CHANGED
@@ -1,6 +1,6 @@
1
  torch
2
- transformers
3
- tensorflow
 
4
  numpy
5
- Image
6
  matplotlib
 
1
  torch
2
+ transformers>=4.41.0
3
+ gradio>=4.0.0
4
+ Pillow
5
  numpy
 
6
  matplotlib