Khunanya commited on
Commit
13fb353
·
verified ·
1 Parent(s): d9a798a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -16
app.py CHANGED
@@ -1,25 +1,44 @@
1
  import gradio as gr
2
- from transformers import pipeline
3
  from PIL import Image
 
 
4
 
5
- # โหลด pipeline สำหรับ semantic segmentation
6
- segmenter = pipeline("image-segmentation", model="nvidia/segformer-b0-finetuned-ade-512-512")
 
7
 
8
- def segment_image(image):
9
- segments = segmenter(image)
10
- # สร้างภาพรวมของ segmentation mask ด้วยสีที่ต่างกัน
11
- mask = Image.new("RGBA", image.size)
12
- for segment in segments:
13
- mask_part = Image.new("RGBA", image.size, segment["color"])
14
- mask_part.putalpha(int(255 * segment["score"]))
15
- mask = Image.alpha_composite(mask, mask_part)
16
- return mask
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  # Gradio UI
19
  gr.Interface(
20
- fn=segment_image,
21
- inputs=gr.Image(type="pil", label="Upload Image"),
22
- outputs="image",
23
  title="Semantic Segmentation with SegFormer",
24
- description="ใช้โมเดล nvidia/segformer-b0-finetuned-ade-512-512 ตรวจจับพื้นที่ของวัตถุต่าง ในภาพ"
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()