"second commit"
Browse files- app.py +43 -43
- 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
|
| 8 |
-
from transformers import
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 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
|
| 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,
|
| 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(
|
| 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
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
logits = outputs.logits
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
seg = tf.math.argmax(logits, axis=-1)[0]
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
|
| 96 |
-
#
|
| 97 |
-
|
| 98 |
-
pred_img =
|
| 99 |
|
| 100 |
fig = draw_plot(pred_img, seg)
|
| 101 |
return fig
|
| 102 |
|
| 103 |
-
demo = gr.Interface(
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
-
|
|
|
|
|
|
| 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 |
-
|
|
|
|
| 4 |
numpy
|
| 5 |
-
Image
|
| 6 |
matplotlib
|
|
|
|
| 1 |
torch
|
| 2 |
+
transformers>=4.41.0
|
| 3 |
+
gradio>=4.0.0
|
| 4 |
+
Pillow
|
| 5 |
numpy
|
|
|
|
| 6 |
matplotlib
|