CoolFace
Apppublic

Thback/CSI

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py112 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 SegformerFeatureExtractor, TFSegformerForSemanticSegmentation9 10feature_extractor = SegformerFeatureExtractor.from_pretrained(11    "nvidia/segformer-b3-finetuned-cityscapes-1024-1024"12)13model = TFSegformerForSemanticSegmentation.from_pretrained(14    "nvidia/segformer-b3-finetuned-cityscapes-1024-1024"15)16 17def ade_palette():18    """ADE20K palette that maps each class to RGB values."""19    return [20        [234, 234, 234],21        [0, 0, 0],22        [255, 0, 0],23        [255, 255, 0],24        [255, 255, 255],25        [0, 255, 255],26        [0, 0, 255],27        [255, 0, 255],28        [243, 97, 220],29        [155, 0, 67],30        [50, 130, 255],31        [255, 130, 50],32        [53, 53, 53],33        [177, 177, 177],34        [95, 0, 255],35        [29, 255, 22],36        [255, 0, 95],37        [100, 100, 100],38        [92, 209, 229],39    ]40 41labels_list = []42 43with open(r'labels.txt', 'r') as fp:44    for line in fp:45        labels_list.append(line[:-1])46 47colormap = np.asarray(ade_palette())48 49def label_to_color_image(label):50    if label.ndim != 2:51        raise ValueError("Expect 2-D input label")52 53    if np.max(label) >= len(colormap):54        raise ValueError("label value too large.")55    return colormap[label]56 57def draw_plot(pred_img, seg):58    fig = plt.figure(figsize=(20, 15))59 60    grid_spec = gridspec.GridSpec(1, 2, width_ratios=[6, 1])61 62    plt.subplot(grid_spec[0])63    plt.imshow(pred_img)64    plt.axis('off')65    LABEL_NAMES = np.asarray(labels_list)66    FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)67    FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)68 69    unique_labels = np.unique(seg.numpy().astype("uint8"))70    ax = plt.subplot(grid_spec[1])71    plt.imshow(FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation="nearest")72    ax.yaxis.tick_right()73    plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])74    plt.xticks([], [])75    ax.tick_params(width=0.0, labelsize=25)76    return fig77 78def sepia(input_img):79    input_img = Image.fromarray(input_img)80 81    inputs = feature_extractor(images=input_img, return_tensors="tf")82    outputs = model(**inputs)83    logits = outputs.logits84 85    logits = tf.transpose(logits, [0, 2, 3, 1])86    logits = tf.image.resize(87        logits, input_img.size[::-1]88    )  # We reverse the shape of `image` because `image.size` returns width and height.89    seg = tf.math.argmax(logits, axis=-1)[0]90 91    color_seg = np.zeros(92        (seg.shape[0], seg.shape[1], 3), dtype=np.uint893    )  # height, width, 394    for label, color in enumerate(colormap):95        color_seg[seg.numpy() == label, :] = color96 97    # Show image + mask98    pred_img = np.array(input_img) * 0.5 + color_seg * 0.599    pred_img = pred_img.astype(np.uint8)100 101    fig = draw_plot(pred_img, seg)102    return fig103 104demo = gr.Interface(fn=sepia,105                    inputs=gr.Image(shape=(400, 600)),106                    outputs=['plot'],107                    examples=["cityscapes-1.jpg", "cityscapes-2.jpg", "cityscapes-3.jpg", "cityscapes-4.jpg", "cityscapes-5.jpg", "cityscapes-6.jpg"],108                    allow_flagging='never')109 110 111demo.launch()112