File size: 4,433 Bytes
418578d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#######################################################################################
#
# MIT License
#
# Copyright (c) [2025] [leonelhs@gmail.com]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#######################################################################################
#
# This project is one of several repositories exploring image segmentation techniques.
# All related projects and interactive demos can be found at:
# https://huggingface.co/spaces/leonelhs/removators
# huggingface: https://huggingface.co/spaces/leonelhs/segformer-tf-transformers
#

import csv
import os
import sys
from itertools import islice

import cv2
import numpy as np
import onnxruntime as ort
import gradio as gr
from PIL import Image
from huggingface_hub import hf_hub_download

ade_palette = []
labels_list = []

csv.field_size_limit(sys.maxsize)

with open(r"labels.txt", "r") as fp:
    for line in fp:
        labels_list.append(line[:-1])

with open(r"ade_palette.txt", "r") as fp:
    for line in fp:
        tmp_list = list(map(int, line[:-1].strip("][").split(", ")))
        ade_palette.append(tmp_list)

    colormap = np.asarray(ade_palette)


REPO_ID = "leonelhs/segmentators"
model_path = hf_hub_download(repo_id=REPO_ID, filename="segformer/segformer-b5-finetuned-ade-640-640.onnx")


sess_options = ort.SessionOptions()
sess_options.intra_op_num_threads = os.cpu_count()
sess = ort.InferenceSession(model_path, sess_options, providers=["CPUExecutionProvider"])


def label_to_color_image(label):
    if label.ndim != 2:
        raise ValueError("Expect 2-D input label")

    if np.max(label) >= len(colormap):
        raise ValueError("label value too large.")

    return colormap[label]

def predict(input_img):

    img = cv2.imread(input_img)
    img = cv2.resize(img, (640, 640)).astype(np.float32)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_batch = np.expand_dims(img, axis=0)
    img_batch = np.transpose(img_batch, (0, 3, 1, 2))

    logits = sess.run(None, {"pixel_values": img_batch})[0]

    logits = np.transpose(logits, (0, 2, 3, 1))
    segmented_mask = np.argmax(logits, axis=-1)[0].astype("float32")
    segmented_mask = cv2.resize(segmented_mask, (640, 640)).astype("uint8")


    parts = []
    unique_labels = np.unique(segmented_mask)
    label_names = np.asarray(labels_list)

    for label in unique_labels:
        part = np.where(segmented_mask == label)
        color_seg = np.full((640, 640, 3), 0, dtype=np.uint8)
        color_seg[part[0], part[1], :] = colormap[label]
        color_seg = cv2.cvtColor(color_seg, cv2.COLOR_BGR2GRAY)
        parts.append((color_seg, label_names[label]))

    return Image.fromarray(img.astype("uint8")), parts

with gr.Blocks(title="SegFormer") as app:
    navbar = gr.Navbar(visible=True, main_page_name="Workspace")
    gr.Markdown("## SegFormer(ADE20k) ONNX")
    with gr.Row():
        with gr.Column(scale=1):
            inp = gr.Image(type="filepath", label="Upload Image")
            btn_predict = gr.Button("Parse")
        with gr.Column(scale=2):
            out = gr.AnnotatedImage(label="Image parsed annotated")

    btn_predict.click(predict, inputs=[inp], outputs=[out])


with app.route("About this", "/about"):
    with open("README.md") as f:
        for line in islice(f, 12, None):
            gr.Markdown(line.strip())

app.launch(share=False, debug=True, show_error=True, mcp_server=True, pwa=True)
app.queue()