xgenatiik commited on
Commit
95fcb89
1 Parent(s): 36d9e79

initial commit

Browse files
Files changed (1) hide show
  1. ex6.py +57 -0
ex6.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import MobileViTFeatureExtractor, MobileViTForSemanticSegmentation
3
+ from PIL import Image
4
+ import numpy as np
5
+
6
+ feature_extractor = MobileViTFeatureExtractor.from_pretrained("apple/deeplabv3-mobilevit-small")
7
+ model = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-small")
8
+
9
+ #(21 classes)
10
+ COLORS = np.array([
11
+ [0, 0, 0],
12
+ [128, 0, 0],
13
+ [0, 128, 0],
14
+ [128, 128, 0],
15
+ [0, 0, 128],
16
+ [128, 0, 128],
17
+ [0, 128, 128],
18
+ [128, 128, 128],
19
+ [64, 0, 0],
20
+ [192, 0, 0],
21
+ [64, 128, 0],
22
+ [192, 128, 0],
23
+ [64, 0, 128],
24
+ [192, 0, 128],
25
+ [64, 128, 128],
26
+ [192, 128, 128],
27
+ [0, 64, 0],
28
+ [128, 64, 0],
29
+ [0, 192, 0],
30
+ [128, 192, 0],
31
+ [0, 64, 128],
32
+ [128, 64, 128]
33
+ ], dtype=np.uint8) # Ensure the data type is uint8 for image processing
34
+
35
+ def segment_image(image):
36
+ inputs = feature_extractor(images=image, return_tensors="pt")
37
+
38
+ outputs = model(**inputs)
39
+ logits = outputs.logits
40
+ predicted_mask = logits.argmax(1).squeeze(0).numpy()
41
+
42
+ colored_mask = COLORS[predicted_mask]
43
+ colored_mask_image = Image.fromarray(colored_mask)
44
+ colored_mask_resized = colored_mask_image.resize(image.size, Image.NEAREST)
45
+
46
+ return colored_mask_resized
47
+
48
+ interface = gr.Interface(
49
+ fn=segment_image,
50
+ inputs=gr.Image(type="pil"),
51
+ outputs="image",
52
+ title="Image Segmentation with MobileViT",
53
+ description="Upload an image to see the semantic segmentation result. The segmentation mask uses different colors to indicate different classes.",
54
+ )
55
+
56
+ interface.launch(share=True)
57
+