Spaces:
Runtime error
Runtime error
import gradio as gr | |
from transformers import SegformerFeatureExtractor, SegformerForSemanticSegmentation | |
from PIL import Image | |
import numpy as np | |
# ๋ชจ๋ธ๊ณผ ํน์ง ์ถ์ถ๊ธฐ ๋ถ๋ฌ์ค๊ธฐ | |
feature_extractor = SegformerFeatureExtractor.from_pretrained("nvidia/segformer-b0-finetuned-cityscapes-512-1024") | |
model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-cityscapes-512-1024") | |
colors = np.array([ | |
[255, 0, 0], # ๋นจ๊ฐ | |
[255, 228, 0], # ๋ ธ๋ | |
[171, 242, 0], # ์ฐ๋ | |
[0, 216, 255], # ํ๋ | |
[0, 0, 255], # ํ๋ | |
[255, 0, 221], # ํํฌ | |
[116, 116, 116], # ํ์ | |
[95, 0, 255], # ๋ณด๋ผ | |
[255, 94, 0], # ์ฃผํฉ | |
[71, 200, 62], # ์ด๋ก | |
[153, 0, 76], # ๋ง์ ํ | |
[67, 116, 217], # ์ ๋งคํํ๋+ํ๋ | |
[153, 112, 0], # ๊ฒจ์ | |
[87, 129, 0], # ๋ น์ | |
[255, 169, 169], # ๋ถํ๋ถํ | |
[35, 30, 183], # ์ด๋์ด ํ๋ | |
[225, 186, 133], # ์ด์ | |
[206, 251, 201], # ์ฐํ์ด๋ก | |
[165, 102, 255] # ์ ๋งคํ๋ณด๋ผ | |
], dtype=np.uint8) | |
def segment_image(image): | |
# ์ด๋ฏธ์ง๋ฅผ ์ฒ๋ฆฌํ๊ณ ๋ชจ๋ธ์ ์ ๋ฌํ๊ธฐ | |
inputs = feature_extractor(images=image, return_tensors="pt") | |
outputs = model(**inputs) | |
logits = outputs.logits | |
# ๊ฒฐ๊ณผ ์ฒ๋ฆฌ ๋ฐ NumPy ๋ฐฐ์ด๋ก ๋ณํ | |
result = logits.argmax(dim=1)[0] | |
result = result.cpu().detach().numpy() | |
# ์์ ํ๋ ํธ ์ ์ฉ | |
result_color = colors[result] | |
# NumPy ๋ฐฐ์ด์ PIL ์ด๋ฏธ์ง๋ก ๋ณํ | |
result_image = Image.fromarray(result_color.astype(np.uint8)) | |
# ์๋ณธ ์ด๋ฏธ์ง์ ์ถ๋ก ๊ฒฐ๊ณผ ์ด๋ฏธ์ง์ ํฌ๊ธฐ ์ผ์น์ํค๊ธฐ | |
result_image = result_image.resize(image.size, Image.NEAREST) | |
# ์๋ณธ ์ด๋ฏธ์ง์ ์ถ๋ก ๊ฒฐ๊ณผ ์ด๋ฏธ์ง ๊ฒฐํฉ | |
combined_image = Image.blend(image.convert("RGBA"), result_image.convert("RGBA"), alpha=0.5) | |
return combined_image | |
# Gradio ์ธํฐํ์ด์ค ์ ์ | |
iface = gr.Interface( | |
fn=segment_image, | |
inputs=gr.inputs.Image(type='pil'), | |
examples = ['image1.jpg', 'image2.jpg', 'image3.jpg'], | |
outputs= 'image', | |
title="SegFormer Image Segmentation", | |
description="Upload an image to segment it using the SegFormer model trained on Cityscapes dataset." | |
) | |
# ์ธํฐํ์ด์ค ์คํ | |
iface.launch() | |