Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,25 +1,44 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import
|
| 3 |
from PIL import Image
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
# โหลด
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
def
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Gradio UI
|
| 19 |
gr.Interface(
|
| 20 |
-
fn=
|
| 21 |
-
inputs=gr.Image(type="pil", label="Upload
|
| 22 |
-
outputs="
|
| 23 |
title="Semantic Segmentation with SegFormer",
|
| 24 |
-
description="ใช้โมเดล
|
| 25 |
).launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
|
| 3 |
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
|
| 7 |
+
# โหลดโมเดล SegFormer
|
| 8 |
+
processor = AutoImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
|
| 9 |
+
model = AutoModelForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
|
| 10 |
|
| 11 |
+
def segment(image):
|
| 12 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 13 |
+
with torch.no_grad():
|
| 14 |
+
outputs = model(**inputs)
|
| 15 |
+
logits = outputs.logits # (1, num_labels, H, W)
|
| 16 |
+
|
| 17 |
+
upsampled_logits = torch.nn.functional.interpolate(
|
| 18 |
+
logits,
|
| 19 |
+
size=image.size[::-1], # (H, W)
|
| 20 |
+
mode="bilinear",
|
| 21 |
+
align_corners=False,
|
| 22 |
+
)[0]
|
| 23 |
+
|
| 24 |
+
predicted = upsampled_logits.argmax(0).numpy()
|
| 25 |
+
|
| 26 |
+
# สร้างภาพ segmentation mask
|
| 27 |
+
colored_mask = Image.fromarray(segmentation_to_color(predicted))
|
| 28 |
+
|
| 29 |
+
return colored_mask
|
| 30 |
+
|
| 31 |
+
# แปลง mask เป็นสี (แบบง่าย)
|
| 32 |
+
def segmentation_to_color(segmentation):
|
| 33 |
+
num_classes = np.max(segmentation) + 1
|
| 34 |
+
colors = np.random.randint(0, 255, size=(num_classes, 3), dtype=np.uint8)
|
| 35 |
+
return colors[segmentation]
|
| 36 |
|
| 37 |
# Gradio UI
|
| 38 |
gr.Interface(
|
| 39 |
+
fn=segment,
|
| 40 |
+
inputs=gr.Image(type="pil", label="Upload an image"),
|
| 41 |
+
outputs=gr.Image(type="pil", label="Segmentation Mask"),
|
| 42 |
title="Semantic Segmentation with SegFormer",
|
| 43 |
+
description="ใช้โมเดล NVIDIA SegFormer สำหรับ Semantic Segmentation"
|
| 44 |
).launch()
|