CoolFace
Apppublic

aupfe08/SegFormer_ADE_Segmentation

sourceHugging Faceupdated 1y agoView on Hugging Face
1likes
app.py247 linesDownload Raw Back to root
1import gradio as gr2 3from matplotlib import gridspec4import matplotlib.pyplot as plt5import numpy as np6from PIL import Image7import tensorflow as tf8from transformers import SegformerImageProcessor, SegformerForSemanticSegmentation9 10feature_extractor = SegformerImageProcessor.from_pretrained(11    "nvidia/segformer-b5-finetuned-ade-640-640"12)13model = SegformerForSemanticSegmentation.from_pretrained(14    "nvidia/segformer-b5-finetuned-ade-640-640"15)16 17def ade_palette():18    """ADE20K palette that maps each class to RGB values."""19    return [20        [120, 120, 120],21        [180, 120, 120],22        [6, 230, 230],23        [80, 50, 50],24        [4, 200, 3],25        [120, 120, 80],26        [140, 140, 140],27        [204, 5, 255],28        [230, 230, 230],29        [4, 250, 7],30        [224, 5, 255],31        [235, 255, 7],32        [150, 5, 61],33        [120, 120, 70],34        [8, 255, 51],35        [255, 6, 82],36        [143, 255, 140],37        [204, 255, 4],38        [255, 51, 7],39        [204, 70, 3],40        [0, 102, 200],41        [61, 230, 250],42        [255, 6, 51],43        [11, 102, 255],44        [255, 7, 71],45        [255, 9, 224],46        [9, 7, 230],47        [220, 220, 220],48        [255, 9, 92],49        [112, 9, 255],50        [8, 255, 214],51        [7, 255, 224],52        [255, 184, 6],53        [10, 255, 71],54        [255, 41, 10],55        [7, 255, 255],56        [224, 255, 8],57        [102, 8, 255],58        [255, 61, 6],59        [255, 194, 7],60        [255, 122, 8],61        [0, 255, 20],62        [255, 8, 41],63        [255, 5, 153],64        [6, 51, 255],65        [235, 12, 255],66        [160, 150, 20],67        [0, 163, 255],68        [140, 140, 140],69        [250, 10, 15],70        [20, 255, 0],71        [31, 255, 0],72        [255, 31, 0],73        [255, 224, 0],74        [153, 255, 0],75        [0, 0, 255],76        [255, 71, 0],77        [0, 235, 255],78        [0, 173, 255],79        [31, 0, 255],80        [11, 200, 200],81        [255, 82, 0],82        [0, 255, 245],83        [0, 61, 255],84        [0, 255, 112],85        [0, 255, 133],86        [255, 0, 0],87        [255, 163, 0],88        [255, 102, 0],89        [194, 255, 0],90        [0, 143, 255],91        [51, 255, 0],92        [0, 82, 255],93        [0, 255, 41],94        [0, 255, 173],95        [10, 0, 255],96        [173, 255, 0],97        [0, 255, 153],98        [255, 92, 0],99        [255, 0, 255],100        [255, 0, 245],101        [255, 0, 102],102        [255, 173, 0],103        [255, 0, 20],104        [255, 184, 184],105        [0, 31, 255],106        [0, 255, 61],107        [0, 71, 255],108        [255, 0, 204],109        [0, 255, 194],110        [0, 255, 82],111        [0, 10, 255],112        [0, 112, 255],113        [51, 0, 255],114        [0, 194, 255],115        [0, 122, 255],116        [0, 255, 163],117        [255, 153, 0],118        [0, 255, 10],119        [255, 112, 0],120        [143, 255, 0],121        [82, 0, 255],122        [163, 255, 0],123        [255, 235, 0],124        [8, 184, 170],125        [133, 0, 255],126        [0, 255, 92],127        [184, 0, 255],128        [255, 0, 31],129        [0, 184, 255],130        [0, 214, 255],131        [255, 0, 112],132        [92, 255, 0],133        [0, 224, 255],134        [112, 224, 255],135        [70, 184, 160],136        [163, 0, 255],137        [153, 0, 255],138        [71, 255, 0],139        [255, 0, 163],140        [255, 204, 0],141        [255, 0, 143],142        [0, 255, 235],143        [133, 255, 0],144        [255, 0, 235],145        [245, 0, 255],146        [255, 0, 122],147        [255, 245, 0],148        [10, 190, 212],149        [214, 255, 0],150        [0, 204, 255],151        [20, 0, 255],152        [255, 255, 0],153        [0, 153, 255],154        [0, 41, 255],155        [0, 255, 204],156        [41, 0, 255],157        [41, 255, 0],158        [173, 0, 255],159        [0, 245, 255],160        [71, 0, 255],161        [122, 0, 255],162        [0, 255, 184],163        [0, 92, 255],164        [184, 255, 0],165        [0, 133, 255],166        [255, 214, 0],167        [25, 194, 194],168        [102, 255, 0],169        [92, 0, 255],170    ]171 172labels_list = []173 174with open(r'labels.txt', 'r') as fp:175    for line in fp:176        labels_list.append(line[:-1])177 178colormap = np.asarray(ade_palette())179 180def label_to_color_image(label):181    if label.ndim != 2:182        raise ValueError("Expect 2-D input label")183 184    if np.max(label) >= len(colormap):185        raise ValueError("label value too large.")186 187    return colormap[label]188 189def draw_plot(pred_img, seg):190    fig = plt.figure(figsize=(20, 15))191 192    grid_spec = gridspec.GridSpec(1, 2, width_ratios=[6, 1])193 194    plt.subplot(grid_spec[0])195    plt.imshow(pred_img)196    plt.axis('off')197 198    LABEL_NAMES = np.asarray(labels_list)199    FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)200    FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)201 202    unique_labels = np.unique(seg.numpy().astype("uint8"))203    ax = plt.subplot(grid_spec[1])204    plt.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")205    ax.yaxis.tick_right()206    plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])207    plt.xticks([], [])208    ax.tick_params(width=0.0, labelsize=25)209    return fig210 211def sepia(input_img):212    input_img = Image.fromarray(input_img)213 214    inputs = feature_extractor(images=input_img, return_tensors="tf")215    outputs = model(**inputs)216    logits = outputs.logits217 218    logits = tf.transpose(logits, [0, 2, 3, 1])219    logits = tf.image.resize(220        logits, input_img.size[::-1]221    )  # We reverse the shape of `image` because `image.size` returns width and height.222    seg = tf.math.argmax(logits, axis=-1)[0]223 224    color_seg = np.zeros(225        (seg.shape[0], seg.shape[1], 3), dtype=np.uint8226    )  # height, width, 3227 228    for label, color in enumerate(colormap):229        color_seg[seg == label, :] = color230 231    # Convert to BGR232    color_seg = color_seg[..., ::-1]233 234    # Show image + mask235    pred_img = np.array(input_img) * 0.5 + color_seg * 0.5236    pred_img = pred_img.astype(np.uint8)    237 238    fig = draw_plot(pred_img, seg)239    return fig240 241demo = gr.Interface(sepia, 242                    gr.Image(shape=(200, 200)), 243                    outputs=['plot'], 244                    examples=["ADE_val_00000001.jpg", "ADE_val_00001159.jpg", "ADE_val_00001248.jpg", "ADE_val_00001472.jpg"],245                    allow_flagging='never')246 247demo.launch()