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()