CoolFace
Apppublic

5Grains/Week_10_First

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py111 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    "mattmdjaga/segformer_b2_clothes"12)13model = TFSegformerForSemanticSegmentation.from_pretrained(14    "mattmdjaga/segformer_b2_clothes"15)16 17def ade_palette():18    """ADE20K palette that maps each class to RGB values."""19    return [20        [255, 0, 0],21        [255, 127, 127],22        [255, 127, 0],23        [255, 255, 0],24        [127, 255, 0],25        [0, 255, 0],26        [127, 255, 127],27        [0, 255, 127],28        [0, 255, 255],29        [0, 127, 255],30        [0, 0, 255],31        [127, 127, 255],32        [127, 0, 255],33        [255, 0, 255],34        [255, 0, 127],35        [0, 0, 0],36        [127, 127, 127],37        [255, 255, 255]38    ]39 40labels_list = []41 42with open(r'labels.txt', 'r') as fp:43    for line in fp:44        labels_list.append(line[:-1])45 46colormap = np.asarray(ade_palette())47 48def 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 56def 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()72    plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])73    plt.xticks([], [])74    ax.tick_params(width=0.0, labelsize=25)75    return fig76 77def 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.logits83 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.uint892    )  # height, width, 393    for label, color in enumerate(colormap):94        color_seg[seg.numpy() == label, :] = color95 96    # Show image + mask97    pred_img = np.array(input_img) * 0.5 + color_seg * 0.598    pred_img = pred_img.astype(np.uint8)99 100    fig = draw_plot(pred_img, seg)101    return fig102 103demo = 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 110demo.launch()111