practice3 / app.py
Karin0616
example radio
e5862fe
raw
history blame
No virus
2.9 kB
import gradio as gr
import random
from matplotlib import gridspec
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import tensorflow as tf
from transformers import SegformerFeatureExtractor, TFSegformerForSemanticSegmentation
feature_extractor = SegformerFeatureExtractor.from_pretrained(
"nvidia/segformer-b5-finetuned-cityscapes-1024-1024"
)
model = TFSegformerForSemanticSegmentation.from_pretrained(
"nvidia/segformer-b5-finetuned-cityscapes-1024-1024"
)
def palette():
return [
[204, 87, 92], # road (Reddish)
[112, 185, 212], # sidewalk (Blue)
[196, 160, 122], # building (Brown)
[106, 135, 242], # wall (Light Blue)
[91, 192, 222], # fence (Turquoise)
[255, 192, 203], # pole (Pink)
[176, 224, 230], # traffic light (Light Blue)
[222, 49, 99], # traffic sign (Red)
[139, 69, 19], # vegetation (Brown)
[255, 0, 0], # terrain (Red)
[0, 0, 255], # sky (Blue)
[255, 228, 181], # person (Peach)
[128, 0, 0], # rider (Maroon)
[0, 128, 0], # car (Green)
[255, 99, 71], # truck (Tomato)
[0, 255, 0], # bus (Lime)
[128, 0, 128], # train (Purple)
[255, 255, 0], # motorcycle (Yellow)
[128, 0, 128] # bicycle (Purple)
]
labels_list = []
with open(r'labels.txt', 'r') as fp:
for line in fp:
labels_list.append(line[:-1])
colormap = np.asarray(palette())
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]
# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ •์˜
iface = gr.Interface(
fn=lambda image: predict_segmentation(image, model),
inputs="image",
outputs="image",
examples=["city1.jpg","city2.jpg","city3.jpg"],
)
iface.launch()
# ์ด๋ฏธ์ง€ ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜ ํ•จ์ˆ˜ ์ •์˜
def predict_segmentation(image, model):
# ์ด๋ฏธ์ง€ ๋ณ€ํ™˜
image = Image.fromarray(image.astype('uint8'), 'RGB')
image = image.resize((1024, 1024)) # ๋ชจ๋ธ์˜ ์ž…๋ ฅ ํฌ๊ธฐ์— ๋งž๊ฒŒ ์กฐ์ ˆ
image_array = tf.keras.preprocessing.image.img_to_array(image)
image_array = tf.expand_dims(image_array, 0)
# ๋ชจ๋ธ ์ถ”๋ก 
predictions = model(image_array)["output_0"]
# ๋ ˆ์ด๋ธ”๋ณ„ ์ƒ‰์ƒ ๋งคํ•‘
segmented_image = tf.zeros_like(predictions)
for label, color in label_colors.items():
mask = tf.reduce_all(tf.equal(predictions, color), axis=-1, keepdims=True)
for i in range(3):
segmented_image += tf.cast(mask, tf.float32) * tf.constant(color[i], dtype=tf.float32)
# ์ด๋ฏธ์ง€ ๋ฆฌํ„ด
segmented_image = tf.cast(segmented_image, tf.uint8)
segmented_image = tf.image.resize(segmented_image, [image.height, image.width])
return segmented_image.numpy()