Thiago Hersan commited on
Commit
f254011
1 Parent(s): 4fba7a2

maskformer-swin-tiny-ade

Browse files
Files changed (1) hide show
  1. app.py +37 -4
app.py CHANGED
@@ -1,7 +1,40 @@
1
  import gradio as gr
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ import random
4
+ import numpy as np
5
+ from transformers import MaskFormerFeatureExtractor, MaskFormerForInstanceSegmentation
6
 
 
 
7
 
8
+ preprocessor = MaskFormerFeatureExtractor.from_pretrained("facebook/maskformer-swin-tiny-ade")
9
+ model = MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-tiny-ade")
10
+
11
+ def visualize_instance_seg_mask(mask):
12
+ image = np.zeros((mask.shape[0], mask.shape[1], 3))
13
+ labels = np.unique(mask)
14
+ label2color = {label: (random.randint(0, 1), random.randint(0, 255), random.randint(0, 255)) for label in labels}
15
+ for i in range(image.shape[0]):
16
+ for j in range(image.shape[1]):
17
+ image[i, j, :] = label2color[mask[i, j]]
18
+ image = image / 255
19
+ return image
20
+
21
+ def query_image(img):
22
+ target_size = (img.shape[0], img.shape[1])
23
+ inputs = preprocessor(images=img, return_tensors="pt")
24
+ outputs = model(**inputs)
25
+ results = preprocessor.post_process_segmentation(outputs=outputs, target_size=target_size)[0]
26
+ results = torch.argmax(results, dim=0).numpy()
27
+ results = visualize_instance_seg_mask(results)
28
+ return results
29
+
30
+
31
+ demo = gr.Interface(
32
+ query_image,
33
+ inputs=[gr.Image()],
34
+ outputs="image",
35
+ title="maskformer-swin-tiny-ade results",
36
+ allow_flagging="never",
37
+ analytics_enabled=None
38
+ )
39
+
40
+ demo.launch(show_api=False)