File size: 17,128 Bytes
7b1f0c9
 
 
 
 
 
 
 
 
eca2859
 
 
 
 
 
7b1f0c9
eca2859
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3d5f8e
eca2859
 
 
 
 
 
 
 
 
 
7b1f0c9
b3d5f8e
eca2859
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5626059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

Application for demo space

"""

import os
import sys
import torch
import requests
import numpy as np
import pandas as pd
import gradio as gr
from PIL import Image
from detectron2 import model_zoo
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
from detectron2.engine import DefaultPredictor
from detectron2.utils.visualizer import ColorMode, Visualizer
from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler


def get_article():
    """
    Get article

    :return:
    """

    if torch.cuda.is_available():
        article = """
            The space demonstrates the method introduced in the paper 'Improving 
            Computer Vision Interpretability: Transparent Two-level Classification for 
            Complex Scenes'.
            
            The segments from the COCO vocabulary are recognized with the 
            segmentation model by [Li et al. (2022)](https://arxiv.org/abs/2206.02777), 
            while they are recognized from the LVIS vocabulary with the model by 
            [Zhou et al (2022)](https://arxiv.org/abs/2201.02605).
        """
    else:
        article = """
            The space demonstrates the method introduced in the paper 'Improving 
            Computer Vision Interpretability: Transparent Two-level Classification for 
            Complex Scenes'.
            
            ⚠️ The segments from the COCO vocabulary as well as the LVIS v0.5 vocabulary 
            are recognized with the segmentation model by [Wu et al., 2017](https://github.com/facebookresearch/detectron2/tree/main).
            If you want to use the same segmentation models as in the paper, then you 
            have to duplicate this space in a space environment with GPU accelerator. 
        """

    return article


def get_models():
    """
    Get article

    :return:
    """

    if torch.cuda.is_available():
        # get coco model
        print("Get model for vocabulary COCO")

        # import modules only available with gpu
        sys.path.insert(0, "./modules/MaskDINO")

        from maskdino import add_maskformer2_config

        # download model weights
        model_path = "models/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth"
        model_url = "https://github.com/IDEA-Research/detrex-storage/releases/download/maskdino-v0.1.0/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth"

        if not os.path.exists(model_path):
            print("Download model weights for vocabulary COCO")
            r = requests.get(model_url)
            with open(model_path, "wb") as f:
                f.write(r.content)

        # config
        cfg_coco = get_cfg()
        # for poly lr schedule
        add_deeplab_config(cfg_coco)
        add_maskformer2_config(cfg_coco)
        cfg_coco.merge_from_file("modules/MaskDINO/configs/coco/instance-segmentation/swin/maskdino_R50_bs16_50ep_4s_dowsample1_2048.yaml")
        cfg_coco.MODEL.WEIGHTS = "models/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth"
        cfg_coco.MODEL.RETINANET.SCORE_THRESH_TEST = 0.0  # no effect
        cfg_coco.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.0  # no effect
        cfg_coco.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = 0.0  # no effect
        cfg_coco.freeze()

        # predictor
        predictor_coco = DefaultPredictor(cfg_coco)

        # get lvis model
        print("Get model for vocabulary LVIS")

        # import modules only available with gpu
        sys.path.insert(0, "./modules/Detic")
        sys.path.insert(0, "./modules/Detic/third_party/CenterNet2")

        from centernet.config import add_centernet_config
        from detic.config import add_detic_config
        from detic.modeling.utils import reset_cls_test
        from detic.modeling.text.text_encoder import build_text_encoder

        class LVISPredictor(DefaultPredictor):
            def __init__(self, cfg, vocab, custom_vocabulary=None, instance_mode=ColorMode.IMAGE):
                """
                Args:
                    cfg (CfgNode):
                    instance_mode (ColorMode):
                    parallel (bool): whether to run the model in different processes from visualization.
                        Useful since the visualization logic can be slow.
                """

                self.BUILDIN_CLASSIFIER = {
                    "lvis": "modules/Detic/datasets/metadata/lvis_v1_clip_a+cname.npy",
                    "objects365": "modules/Detic/datasets/metadata/o365_clip_a+cnamefix.npy",
                    "openimages": "modules/Detic/datasets/metadata/oid_clip_a+cname.npy",
                    "coco": "modules/Detic/datasets/metadata/coco_clip_a+cname.npy",
                }

                self.BUILDIN_METADATA_PATH = {
                    "lvis": "lvis_v1_val",
                    "objects365": "objects365_v2_val",
                    "openimages": "oid_val_expanded",
                    "coco": "coco_2017_val",
                }

                if vocab == "custom":
                    self.metadata = MetadataCatalog.get("__unused")
                    self.metadata.thing_classes = custom_vocabulary.split(',')
                    classifier = get_clip_embeddings(self.metadata.thing_classes)
                else:
                    self.metadata = MetadataCatalog.get(
                        self.BUILDIN_METADATA_PATH[vocab])
                    classifier = self.BUILDIN_CLASSIFIER[vocab]

                num_classes = len(self.metadata.thing_classes)
                self.cpu_device = torch.device("cpu")
                self.instance_mode = instance_mode

                self.predictor = DefaultPredictor(cfg)
                reset_cls_test(self.predictor.model, classifier, num_classes)

            def __call__(self, image):
                """
                Args:
                    image (np.ndarray): an image of shape (H, W, C) (in BGR order).
                        This is the format used by OpenCV.

                Returns:
                    predictions (dict): the output of the model.
                """

                predictions = self.predictor(image)

                return predictions


        def get_clip_embeddings(vocabulary, prompt='a '):
            text_encoder = build_text_encoder(pretrain=True)
            text_encoder.eval()
            texts = [prompt + x for x in vocabulary]
            emb = text_encoder(texts).detach().permute(1, 0).contiguous().cpu()
            return emb

        # download model weights
        model_path = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
        model_url = "https://dl.fbaipublicfiles.com/detic/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"

        if not os.path.exists(model_path):
            print("Download model weights")
            r = requests.get(model_url)
            with open(model_path, "wb") as f:
                f.write(r.content)

        # config
        cfg_lvis = get_cfg()  # weight-file
        add_centernet_config(cfg_lvis)
        add_detic_config(cfg_lvis)
        cfg_lvis.merge_from_file("modules/Detic/configs/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.yaml")
        cfg_lvis.MODEL.WEIGHTS = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
        cfg_lvis.MODEL.ROI_BOX_HEAD.CAT_FREQ_PATH = "modules/Detic/datasets/metadata/lvis_v1_train_cat_info.json"
        cfg_lvis.MODEL.ROI_BOX_HEAD.ZEROSHOT_WEIGHT_PATH = "rand"  # load later
        cfg_lvis.MODEL.ROI_HEADS.ONE_CLASS_PER_PROPOSAL = True
        cfg_lvis.freeze()
        # predictor
        predictor_lvis = LVISPredictor(cfg_lvis, vocab="lvis")

    else:
        # get coco model
        print("Get model for vocabulary COCO")

        # config
        cfg_coco = get_cfg()
        # device
        cfg_coco.MODEL.DEVICE = "cpu"
        # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
        cfg_coco.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml"))
        cfg_coco.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1  # set threshold for this model
        # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
        cfg_coco.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml")

        # predictor
        predictor_coco = DefaultPredictor(cfg_coco)

        # get coco model
        print("Get model for vocabulary LVIS")

        # config
        cfg_lvis = get_cfg()
        # device
        cfg_lvis.MODEL.DEVICE = "cpu"
        # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
        cfg_lvis.merge_from_file(model_zoo.get_config_file("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml"))
        cfg_lvis.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1  # set threshold for this model
        # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
        cfg_lvis.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml")

        # predictor
        predictor_lvis = DefaultPredictor(cfg_lvis)

    return predictor_coco, cfg_coco, predictor_lvis, cfg_lvis


def predict(image, vocabulary, feature_aggregation):
    """
    Predict segmented image and feature vector

    :param image:
    :param vocabulary:
    :param feature_aggregation:
    :return:
    """

    # convert image and resize if necessary
    image = image.convert('RGB')
    image.thumbnail((2000, 2000), Image.LANCZOS)
    image = np.array(image)

    # check vocabulary
    if vocabulary == "COCO":
        # get predictions
        predictions = predictor_coco(image)

        # visualize predictions
        visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION)
        image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu"))
        image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1])

        # get class names
        class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]).thing_classes)}

    elif vocabulary == "LVIS":
        # get predictions
        predictions = predictor_lvis(image)

        # visualize predictions
        visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION)
        image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu"))
        image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1])

        # get class names
        class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]).thing_classes)}

    else:
        raise Exception("Unknown vocabulary")

    # prepare segments in long format
    segments_long_df = pd.DataFrame([])

    for seg_num, seg_score, seg_mask in zip(predictions["instances"].pred_classes, predictions["instances"].scores, predictions["instances"].pred_masks):
        segments_long_df = pd.concat([segments_long_df, pd.Series({
            "id": "image_1",
            "seg_num": seg_num.item(),
            "seg_name": class_names[seg_num.item()],
            "seg_score": seg_score.item(),
            "seg_prop": (torch.sum(seg_mask == True) / torch.numel(seg_mask)).item()
        }).to_frame().T], ignore_index=True)

    # TODO: delete segments with less than 0.1
    #segments_long_df = segments_long_df.loc[(segments_long_df["seg_score"] >= 0.1)].reset_index(drop=True)

    if feature_aggregation == "bin":
        # get segments wide
        segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["any"]})
        cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
        cols_missing = [f'{vocabulary.lower()}_{category.lower()}_bin' for category in cols_missing]
        segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_bin' for var, agg, label in segments_wide_df.columns]
        segments_wide_df = segments_wide_df.reset_index()
        segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
        segments_wide_df = segments_wide_df.fillna(0)
        # get cols
        cols = [f'{vocabulary.lower()}_{cat.lower()}_bin' for cat in class_names.values()]
        # get vector
        feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records")

    elif feature_aggregation == "count":
        segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["count"]})
        cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
        cols_missing = [f'{vocabulary.lower()}_{category.lower()}_count' for category in cols_missing]
        segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_count' for var, agg, label in segments_wide_df.columns]
        segments_wide_df = segments_wide_df.reset_index()
        segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
        segments_wide_df = segments_wide_df.fillna(0)
        # get cols
        cols = [f'{vocabulary.lower()}_{cat.lower()}_count' for cat in class_names.values()]
        # get vector
        feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records")

    elif feature_aggregation == "area_max":
        segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["max"]})
        cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
        cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_max" for category in cols_missing]
        segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_max" for var, agg, label in segments_wide_df.columns]
        segments_wide_df = segments_wide_df.reset_index()
        segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
        segments_wide_df = segments_wide_df.fillna(0)
        # get cols
        cols = [f"{vocabulary.lower()}_{cat.lower()}_area_max" for cat in class_names.values()]
        # get vector
        feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records")

    elif feature_aggregation == "area_sum":
        segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["sum"]})
        cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
        cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_sum" for category in cols_missing]
        segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_sum" for var, agg, label in segments_wide_df.columns]
        segments_wide_df = segments_wide_df.reset_index()
        segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
        segments_wide_df = segments_wide_df.fillna(0)
        # get cols
        cols = [f"{vocabulary.lower()}_{cat.lower()}_area_sum" for cat in class_names.values()]
        # get vector
        feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records")

    return image_segmented, feature_vector


if __name__ == "__main__":
    # get models
    predictor_coco, cfg_coco, predictor_lvis, cfg_lvis = get_models()

    # define interface
    app = gr.Interface(
        predict,
        inputs=[
            gr.Image(label="Select image", sources=["upload", "webcam"], type="pil"),
            gr.Dropdown(label="Select vocabulary", choices=["COCO", "LVIS"]),
            gr.Dropdown(label="Select feature aggregation", choices=["bin", "count", "area_max", "area_sum"]),
        ],
        outputs=[
            gr.Image(label="Segmented Image"),
            gr.JSON(label="Feature Vector")
        ],
        title="Protest Segments: What is the Feature Vector of My Image?",
        article = get_article()
    )

    # create queue
    app.queue(
        max_size=100,
        default_concurrency_limit=1,
    )

    # launch
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
    )