kaushikroy1984 commited on
Commit
035a34d
·
verified ·
1 Parent(s): 70e15df

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -0
app.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import gradio as gr
3
+ import numpy as np
4
+ from os import environ
5
+ from PIL import Image
6
+ from torchvision import transforms as T
7
+ from transformers import MaskFormerForInstanceSegmentation, MaskFormerImageProcessor
8
+
9
+
10
+ example_images = sorted(glob.glob('sample_images/*.jpg'))
11
+
12
+ ade_mean=[0.485, 0.456, 0.406]
13
+ ade_std=[0.229, 0.224, 0.225]
14
+
15
+ test_transform = T.Compose([
16
+ T.ToTensor(),
17
+ T.Normalize(mean=ade_mean, std=ade_std)
18
+ ])
19
+
20
+ palette = [
21
+ [120, 120, 120], [4, 200, 4], [4, 4, 250], [6, 230, 230],
22
+ [80, 50, 50], [120, 120, 80], [140, 140, 140], [204, 5, 255]
23
+ ]
24
+
25
+ model_id = f"https://huggingface.co/thiagohersan/maskformer-satellite-trees"
26
+ vegetation_labels = ["vegetation"]
27
+
28
+ # preprocessor = MaskFormerImageProcessor.from_pretrained(model_id)
29
+ preprocessor = MaskFormerImageProcessor(
30
+ do_resize=False,
31
+ do_normalize=False,
32
+ do_rescale=False,
33
+ ignore_index=255,
34
+ reduce_labels=False
35
+ )
36
+
37
+
38
+ hf_token = environ.get('HFTOKEN')
39
+ model = MaskFormerForInstanceSegmentation.from_pretrained(model_id, use_auth_token=hf_token)
40
+
41
+
42
+ def visualize_instance_seg_mask(img_in, mask, id2label, included_labels):
43
+ img_out = np.zeros((mask.shape[0], mask.shape[1], 3))
44
+ image_total_pixels = mask.shape[0] * mask.shape[1]
45
+ label_ids = np.unique(mask)
46
+
47
+ id2color = {id: palette[id] for id in label_ids}
48
+ id2count = {id: 0 for id in label_ids}
49
+
50
+ for i in range(img_out.shape[0]):
51
+ for j in range(img_out.shape[1]):
52
+ img_out[i, j, :] = id2color[mask[i, j]]
53
+ id2count[mask[i, j]] = id2count[mask[i, j]] + 1
54
+
55
+ image_res = (0.5 * img_in + 0.5 * img_out).astype(np.uint8)
56
+
57
+ dataframe = [[
58
+ f"{id2label[id]}",
59
+ f"{(100 * id2count[id] / image_total_pixels):.2f} %",
60
+ f"{np.sqrt(id2count[id] / image_total_pixels):.2f} m"
61
+ ] for id in label_ids if id2label[id] in included_labels]
62
+
63
+ if len(dataframe) < 1:
64
+ dataframe = [[
65
+ f"",
66
+ f"{(0):.2f} %",
67
+ f"{(0):.2f} m"
68
+ ]]
69
+
70
+ return image_res, dataframe
71
+
72
+
73
+ def query_image(image_path):
74
+ img = np.array(Image.open(image_path))
75
+ img_size = (img.shape[0], img.shape[1])
76
+ inputs = preprocessor(images=test_transform(img), return_tensors="pt")
77
+ outputs = model(**inputs)
78
+ results = preprocessor.post_process_semantic_segmentation(outputs=outputs, target_sizes=[img_size])[0]
79
+ mask_img, dataframe = visualize_instance_seg_mask(img, results.numpy(), model.config.id2label, vegetation_labels)
80
+ return mask_img, dataframe
81
+
82
+
83
+ demo = gr.Interface(
84
+ title="Maskformer Satellite+Trees",
85
+ description="Using a finetuned version of the [facebook/maskformer-swin-base-ade](https://huggingface.co/facebook/maskformer-swin-base-ade) model (created specifically to work with satellite images) to calculate percentage of pixels in an image that belong to vegetation.",
86
+
87
+ fn=query_image,
88
+ inputs=[gr.Image(type="filepath", label="Input Image")],
89
+ outputs=[
90
+ gr.Image(label="Vegetation"),
91
+ gr.DataFrame(label="Info", headers=["Object Label", "Pixel Percent", "Square Length"])
92
+ ],
93
+
94
+ examples=example_images,
95
+ cache_examples=True,
96
+
97
+ allow_flagging="never",
98
+ analytics_enabled=None
99
+ )
100
+
101
+ demo.launch(show_api=False)