Spaces:
Sleeping
Sleeping
Add app.py
Browse files- app.py +53 -0
- requirements.txt +3 -0
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
from PIL import Image
|
5 |
+
from transformers import SamModel, SamProcessor
|
6 |
+
|
7 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
8 |
+
processor = SamProcessor.from_pretrained('facebook/sam-vit-base')
|
9 |
+
model = SamModel.from_pretrained('hmdliu/sidewalks-seg-base')
|
10 |
+
model.to(device)
|
11 |
+
|
12 |
+
def segment_image(image, threshold):
|
13 |
+
# init data
|
14 |
+
width, height = image.size
|
15 |
+
prompt = [0, 0, width, height]
|
16 |
+
inputs = processor(image, input_boxes=[[prompt]], return_tensors='pt')
|
17 |
+
# make prediction
|
18 |
+
outputs = model(pixel_values=inputs['pixel_values'].to(device),
|
19 |
+
input_boxes=inputs['input_boxes'].to(device),
|
20 |
+
multimask_output=False)
|
21 |
+
prob_map = torch.sigmoid(outputs.pred_masks.squeeze()).cpu().detach()
|
22 |
+
prediction = (prob_map > threshold).float()
|
23 |
+
prob_map, prediction = prob_map.numpy(), prediction.numpy()
|
24 |
+
# visualize results
|
25 |
+
plt.figure(figsize=(8, 8))
|
26 |
+
plt.imshow(prediction, cmap='gray', interpolation='nearest')
|
27 |
+
plt.axis('off')
|
28 |
+
plt.tight_layout()
|
29 |
+
plt.savefig('mask.png', bbox_inches='tight', pad_inches=0)
|
30 |
+
plt.figure(figsize=(8, 8))
|
31 |
+
plt.imshow(prob_map, cmap='jet', interpolation='nearest')
|
32 |
+
plt.axis('off')
|
33 |
+
plt.tight_layout()
|
34 |
+
plt.savefig('heatmap.png', bbox_inches='tight', pad_inches=0)
|
35 |
+
plt.close()
|
36 |
+
return Image.open('mask.png'), Image.open('heatmap.png')
|
37 |
+
|
38 |
+
with gr.Blocks() as demo:
|
39 |
+
with gr.Row():
|
40 |
+
with gr.Column():
|
41 |
+
image_input = gr.Image(type='pil', label='TIFF Image')
|
42 |
+
threshold_slider = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.5, label='Prediction Threshold')
|
43 |
+
segment_button = gr.Button('Segment')
|
44 |
+
with gr.Column():
|
45 |
+
prediction = gr.Image(type='pil', label='Segmentation Result')
|
46 |
+
with gr.Column():
|
47 |
+
prob_map = gr.Image(type='pil', label='Probability Map')
|
48 |
+
segment_button.click(
|
49 |
+
segment_image,
|
50 |
+
inputs=[image_input, threshold_slider],
|
51 |
+
outputs=[prediction, prob_map]
|
52 |
+
)
|
53 |
+
demo.launch(debug=True, show_error=True)
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
matplotlib
|
3 |
+
transformers
|