Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor
|
3 |
+
from PIL import Image
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
# Load pretrained model
|
8 |
+
processor = SegformerImageProcessor(do_reduce_labels=False)
|
9 |
+
model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
|
10 |
+
model.eval()
|
11 |
+
|
12 |
+
# Prediction function
|
13 |
+
def segment_image(input_image):
|
14 |
+
inputs = processor(images=input_image, return_tensors="pt")
|
15 |
+
|
16 |
+
with torch.no_grad():
|
17 |
+
outputs = model(**inputs)
|
18 |
+
logits = outputs.logits
|
19 |
+
|
20 |
+
pred_mask = torch.argmax(logits, dim=1)[0].cpu().numpy()
|
21 |
+
normalized_mask = (pred_mask * (255 // logits.shape[1])).astype(np.uint8)
|
22 |
+
output_image = Image.fromarray(normalized_mask)
|
23 |
+
|
24 |
+
# Bigger mask (3x)
|
25 |
+
scale_factor = 3
|
26 |
+
new_size = (output_image.width * scale_factor, output_image.height * scale_factor)
|
27 |
+
bigger_output = output_image.resize(new_size, resample=Image.NEAREST)
|
28 |
+
|
29 |
+
return bigger_output
|
30 |
+
|
31 |
+
# Gradio Interface
|
32 |
+
demo = gr.Interface(
|
33 |
+
fn=segment_image,
|
34 |
+
inputs=gr.Image(type="pil", label="Upload Blood Smear Image"),
|
35 |
+
outputs=gr.Image(type="pil", label="Predicted Grayscale Mask"),
|
36 |
+
title="Malaria Blood Smear Segmentation (SegFormer - Pretrained)",
|
37 |
+
description="Upload a blood smear image to segment it using a pretrained SegFormer model (ADE20K 150 classes).",
|
38 |
+
examples=["examples/sample1.jpg", "examples/sample2.jpg"] # Example images
|
39 |
+
)
|
40 |
+
|
41 |
+
if __name__ == "__main__":
|
42 |
+
demo.launch()
|