royguw commited on
Commit
0cbed7c
·
verified ·
1 Parent(s): 6d923b7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. OpenPVSG/models/mask2former/mask2former.py +270 -0
  2. OpenPVSG/models/mask2former/mask2former_fusion_head.py +404 -0
  3. OpenPVSG/models/mask2former/mask2former_head.py +681 -0
  4. OpenPVSG/models/mask2former/mask2former_head_focal.py +613 -0
  5. OpenPVSG/models/mask2former/mask2former_head_split_focal.py +751 -0
  6. OpenPVSG/models/unitrack/core/__init__.py +0 -0
  7. OpenPVSG/models/unitrack/core/association/__init__.py +0 -0
  8. OpenPVSG/models/unitrack/core/association/matching.py +258 -0
  9. OpenPVSG/models/unitrack/core/motion/kalman_filter.py +277 -0
  10. OpenPVSG/models/unitrack/core/propagation/__init__.py +24 -0
  11. OpenPVSG/models/unitrack/core/propagation/propagate_box.py +13 -0
  12. OpenPVSG/models/unitrack/core/propagation/propagate_mask.py +13 -0
  13. OpenPVSG/models/unitrack/core/propagation/propagate_pose.py +13 -0
  14. OpenPVSG/models/unitrack/data/__init__.py +2 -0
  15. OpenPVSG/models/unitrack/data/query_feat_tracklet.py +38 -0
  16. OpenPVSG/models/unitrack/data/single_video.py +102 -0
  17. OpenPVSG/models/unitrack/data/video.py +414 -0
  18. OpenPVSG/models/unitrack/eval/mots/Evaluator.py +229 -0
  19. OpenPVSG/models/unitrack/eval/mots/LICENSE +21 -0
  20. OpenPVSG/models/unitrack/eval/mots/MOTSVisualization.py +75 -0
  21. OpenPVSG/models/unitrack/eval/mots/MOTS_metrics.py +573 -0
  22. OpenPVSG/models/unitrack/eval/mots/Metrics.py +149 -0
  23. OpenPVSG/models/unitrack/eval/mots/README.md +97 -0
  24. OpenPVSG/models/unitrack/eval/mots/Visualize.py +139 -0
  25. OpenPVSG/models/unitrack/eval/mots/__init__.py +2 -0
  26. OpenPVSG/models/unitrack/eval/mots/evalMOTS.py +53 -0
  27. OpenPVSG/models/unitrack/eval/mots/mots_common/images_to_txt.py +18 -0
  28. OpenPVSG/models/unitrack/eval/mots/mots_common/io.py +135 -0
  29. OpenPVSG/models/unitrack/eval/mots/requirements.txt +14 -0
  30. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/AUTHORS.txt +53 -0
  31. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/ChangeLog.txt +96 -0
  32. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/LICENSE_BSD.txt +25 -0
  33. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/README.txt +411 -0
  34. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/demo_jsonlab_basic.m +181 -0
  35. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/demo_ubjson_basic.m +180 -0
  36. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_basictest.matlab +671 -0
  37. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_selftest.m +27 -0
  38. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_selftest.matlab +154 -0
  39. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_speedtest.m +21 -0
  40. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/jsonopt.m +35 -0
  41. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/loadjson.m +496 -0
  42. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/loadubjson.m +457 -0
  43. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/mergestruct.m +33 -0
  44. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/savejson.m +551 -0
  45. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/saveubjson.m +562 -0
  46. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/struct2jdata.m +96 -0
  47. OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/varargin2struct.m +40 -0
  48. OpenPVSG/models/unitrack/eval/poseval/matlab/mat2json.m +22 -0
  49. OpenPVSG/models/unitrack/eval/trackeval/__init__.py +5 -0
  50. OpenPVSG/models/unitrack/eval/trackeval/_timing.py +60 -0
OpenPVSG/models/mask2former/mask2former.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import copy
3
+
4
+ import mmcv
5
+ import numpy as np
6
+ from mmdet.utils import get_root_logger
7
+
8
+ from mmdet.core import INSTANCE_OFFSET, bbox2result
9
+ from mmdet.core.visualization import imshow_det_bboxes
10
+ from mmdet.models.builder import DETECTORS, build_backbone, build_head, build_neck
11
+ from mmdet.models.detectors.single_stage import SingleStageDetector
12
+
13
+
14
+ @DETECTORS.register_module()
15
+ class Mask2FormerCustom(SingleStageDetector):
16
+ r"""Implementation of `Per-Pixel Classification is
17
+ NOT All You Need for Semantic Segmentation
18
+ <https://arxiv.org/pdf/2107.06278>`_."""
19
+
20
+ async def async_simple_test(self, img, img_metas, **kwargs):
21
+ raise NotImplementedError
22
+
23
+ def __init__(self,
24
+ backbone,
25
+ neck=None,
26
+ panoptic_head=None,
27
+ panoptic_fusion_head=None,
28
+ train_cfg=None,
29
+ test_cfg=None,
30
+ init_cfg=None):
31
+ super(SingleStageDetector, self).__init__(init_cfg=init_cfg)
32
+ self.backbone = build_backbone(backbone)
33
+ if neck is not None:
34
+ self.neck = build_neck(neck)
35
+
36
+ panoptic_head_ = copy.deepcopy(panoptic_head)
37
+ panoptic_head_.update(train_cfg=train_cfg)
38
+ panoptic_head_.update(test_cfg=test_cfg)
39
+ self.panoptic_head = build_head(panoptic_head_)
40
+
41
+ panoptic_fusion_head_ = copy.deepcopy(panoptic_fusion_head)
42
+ panoptic_fusion_head_.update(test_cfg=test_cfg)
43
+ self.panoptic_fusion_head = build_head(panoptic_fusion_head_)
44
+
45
+ self.num_things_classes = self.panoptic_head.num_things_classes
46
+ self.num_stuff_classes = self.panoptic_head.num_stuff_classes
47
+ self.num_classes = self.panoptic_head.num_classes
48
+
49
+ self.train_cfg = train_cfg
50
+ self.test_cfg = test_cfg
51
+
52
+ # BaseDetector.show_result default for instance segmentation
53
+ if self.num_stuff_classes > 0:
54
+ self.show_result = self._show_pan_result
55
+
56
+ self.logger = get_root_logger()
57
+ self.logger.info("[Unified Video Segmentation] Using customized mask2former segmentor.")
58
+
59
+ def forward_dummy(self, img, img_metas):
60
+ """Used for computing network flops. See
61
+ `mmdetection/tools/analysis_tools/get_flops.py`
62
+
63
+ Args:
64
+ img (Tensor): of shape (N, C, H, W) encoding input images.
65
+ Typically these should be mean centered and std scaled.
66
+ img_metas (list[Dict]): list of image info dict where each dict
67
+ has: 'img_shape', 'scale_factor', 'flip', and may also contain
68
+ 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
69
+ For details on the values of these keys see
70
+ `mmdet/datasets/pipelines/formatting.py:Collect`.
71
+ """
72
+ super(SingleStageDetector, self).forward_train(img, img_metas)
73
+ x = self.extract_feat(img)
74
+ outs = self.panoptic_head(x, img_metas)
75
+ return outs
76
+
77
+ def forward_train(self,
78
+ img,
79
+ img_metas,
80
+ gt_bboxes,
81
+ gt_labels,
82
+ gt_masks,
83
+ gt_semantic_seg=None,
84
+ gt_bboxes_ignore=None,
85
+ **kargs):
86
+ """
87
+ Args:
88
+ img (Tensor): of shape (N, C, H, W) encoding input images.
89
+ Typically these should be mean centered and std scaled.
90
+ img_metas (list[Dict]): list of image info dict where each dict
91
+ has: 'img_shape', 'scale_factor', 'flip', and may also contain
92
+ 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
93
+ For details on the values of these keys see
94
+ `mmdet/datasets/pipelines/formatting.py:Collect`.
95
+ gt_bboxes (list[Tensor]): Ground truth bboxes for each image with
96
+ shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.
97
+ gt_labels (list[Tensor]): class indices corresponding to each box.
98
+ gt_masks (list[BitmapMasks]): true segmentation masks for each box
99
+ used if the architecture supports a segmentation task.
100
+ gt_semantic_seg (list[tensor]): semantic segmentation mask for
101
+ images for panoptic segmentation.
102
+ Defaults to None for instance segmentation.
103
+ gt_bboxes_ignore (list[Tensor]): specify which bounding
104
+ boxes can be ignored when computing the loss.
105
+ Defaults to None.
106
+
107
+ Returns:
108
+ dict[str, Tensor]: a dictionary of loss components
109
+ """
110
+ # add batch_input_shape in img_metas
111
+ super(SingleStageDetector, self).forward_train(img, img_metas)
112
+ x = self.extract_feat(img)
113
+ # print("model input:", "labels:", len(gt_labels[0]), "masks:", len(gt_masks[0]))
114
+ losses = self.panoptic_head.forward_train(x, img_metas, gt_bboxes,
115
+ gt_labels, gt_masks,
116
+ gt_semantic_seg,
117
+ gt_bboxes_ignore)
118
+
119
+ return losses
120
+
121
+ def simple_test(self, imgs, img_metas, **kwargs):
122
+ """Test without augmentation.
123
+
124
+ Args:
125
+ imgs (Tensor): A batch of images.
126
+ img_metas (list[dict]): List of image information.
127
+
128
+ Returns:
129
+ list[dict[str, np.array | tuple[list]] | tuple[list]]:
130
+ Semantic segmentation results and panoptic segmentation \
131
+ results of each image for panoptic segmentation, or formatted \
132
+ bbox and mask results of each image for instance segmentation.
133
+
134
+ .. code-block:: none
135
+
136
+ [
137
+ # panoptic segmentation
138
+ {
139
+ 'pan_results': np.array, # shape = [h, w]
140
+ 'ins_results': tuple[list],
141
+ # semantic segmentation results are not supported yet
142
+ 'sem_results': np.array
143
+ },
144
+ ...
145
+ ]
146
+
147
+ or
148
+
149
+ .. code-block:: none
150
+
151
+ [
152
+ # instance segmentation
153
+ (
154
+ bboxes, # list[np.array]
155
+ masks # list[list[np.array]]
156
+ ),
157
+ ...
158
+ ]
159
+ """
160
+ feats = self.extract_feat(imgs) # after backbone + neck
161
+ mask_cls_results, mask_pred_results, query_feats= self.panoptic_head.simple_test_with_query(
162
+ feats, img_metas, **kwargs) # modify -- use simple_test_with_query to return que_fea with mask!
163
+ results = self.panoptic_fusion_head.simple_test_with_query(
164
+ mask_cls_results, mask_pred_results, query_feats, img_metas, **kwargs)
165
+ # import pdb; pdb.set_trace()
166
+ for i in range(len(results)):
167
+ if 'pan_results' in results[i]:
168
+ results[i]['pan_results'] = results[i]['pan_results'].detach(
169
+ ).cpu().numpy()
170
+ if 'query_feats' in results[i]:
171
+ for idx, query_feat_list in results[i]['query_feats'].items():
172
+ results[i]['query_feats'][idx] = [x.detach().cpu().numpy() for x in query_feat_list]
173
+
174
+ if 'ins_results' in results[i]:
175
+ labels_per_image, bboxes, mask_pred_binary = results[i][
176
+ 'ins_results']
177
+ bbox_results = bbox2result(bboxes, labels_per_image,
178
+ self.num_things_classes)
179
+ mask_results = [[] for _ in range(self.num_things_classes)]
180
+ for j, label in enumerate(labels_per_image):
181
+ mask = mask_pred_binary[j].detach().cpu().numpy()
182
+ mask_results[label].append(mask)
183
+ results[i]['ins_results'] = bbox_results, mask_results
184
+
185
+ # assert 'sem_results' not in results[i], 'segmantic segmentation '\
186
+ # 'results are not supported yet.'
187
+
188
+ if self.num_stuff_classes == 0:
189
+ results = [res['ins_results'] for res in results]
190
+
191
+ return results
192
+
193
+ def aug_test(self, imgs, img_metas, **kwargs):
194
+ raise NotImplementedError
195
+
196
+ def onnx_export(self, img, img_metas):
197
+ raise NotImplementedError
198
+
199
+ def _show_pan_result(self,
200
+ img,
201
+ result,
202
+ score_thr=0.3,
203
+ bbox_color=(72, 101, 241),
204
+ text_color=(72, 101, 241),
205
+ mask_color=None,
206
+ thickness=2,
207
+ font_size=13,
208
+ win_name='',
209
+ show=False,
210
+ wait_time=0,
211
+ out_file=None):
212
+ """Draw `panoptic result` over `img`.
213
+
214
+ Args:
215
+ img (str or Tensor): The image to be displayed.
216
+ result (dict): The results.
217
+
218
+ score_thr (float, optional): Minimum score of bboxes to be shown.
219
+ Default: 0.3.
220
+ bbox_color (str or tuple(int) or :obj:`Color`):Color of bbox lines.
221
+ The tuple of color should be in BGR order. Default: 'green'.
222
+ text_color (str or tuple(int) or :obj:`Color`):Color of texts.
223
+ The tuple of color should be in BGR order. Default: 'green'.
224
+ mask_color (None or str or tuple(int) or :obj:`Color`):
225
+ Color of masks. The tuple of color should be in BGR order.
226
+ Default: None.
227
+ thickness (int): Thickness of lines. Default: 2.
228
+ font_size (int): Font size of texts. Default: 13.
229
+ win_name (str): The window name. Default: ''.
230
+ wait_time (float): Value of waitKey param.
231
+ Default: 0.
232
+ show (bool): Whether to show the image.
233
+ Default: False.
234
+ out_file (str or None): The filename to write the image.
235
+ Default: None.
236
+
237
+ Returns:
238
+ img (Tensor): Only if not `show` or `out_file`.
239
+ """
240
+ img = mmcv.imread(img)
241
+ img = img.copy()
242
+ pan_results = result['pan_results']
243
+ # keep objects ahead
244
+ ids = np.unique(pan_results)[::-1]
245
+ legal_indices = ids != self.num_classes # for VOID label
246
+ ids = ids[legal_indices]
247
+ labels = np.array([id % INSTANCE_OFFSET for id in ids], dtype=np.int64)
248
+ segms = (pan_results[None] == ids[:, None, None])
249
+
250
+ # if out_file specified, do not show image in window
251
+ if out_file is not None:
252
+ show = False
253
+ # draw bounding boxes
254
+ img = imshow_det_bboxes(
255
+ img,
256
+ segms=segms,
257
+ labels=labels,
258
+ class_names=self.CLASSES,
259
+ bbox_color=bbox_color,
260
+ text_color=text_color,
261
+ mask_color=mask_color,
262
+ thickness=thickness,
263
+ font_size=font_size,
264
+ win_name=win_name,
265
+ show=show,
266
+ wait_time=wait_time,
267
+ out_file=out_file)
268
+
269
+ if not (show or out_file):
270
+ return img
OpenPVSG/models/mask2former/mask2former_fusion_head.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from collections import defaultdict
3
+ from email.policy import default
4
+ import torch
5
+ import torch.nn.functional as F
6
+
7
+ from mmdet.core.evaluation.panoptic_utils import INSTANCE_OFFSET
8
+ from mmdet.core.mask import mask2bbox
9
+ from mmdet.models.builder import HEADS
10
+ from mmdet.models.seg_heads.panoptic_fusion_heads.base_panoptic_fusion_head import BasePanopticFusionHead # add import from absolute path
11
+
12
+
13
+ @HEADS.register_module()
14
+ class MaskFormerFusionHeadCustom(BasePanopticFusionHead):
15
+
16
+ def __init__(self,
17
+ num_things_classes=80,
18
+ num_stuff_classes=53,
19
+ test_cfg=None,
20
+ loss_panoptic=None,
21
+ init_cfg=None,
22
+ **kwargs):
23
+ super().__init__(num_things_classes, num_stuff_classes, test_cfg,
24
+ loss_panoptic, init_cfg, **kwargs)
25
+
26
+ def forward_train(self, **kwargs):
27
+ """MaskFormerFusionHead has no training loss."""
28
+ return dict()
29
+
30
+ def panoptic_postprocess(self, mask_cls, mask_pred):
31
+ """Panoptic segmengation inference.
32
+
33
+ Args:
34
+ mask_cls (Tensor): Classfication outputs of shape
35
+ (num_queries, cls_out_channels) for a image.
36
+ Note `cls_out_channels` should includes
37
+ background.
38
+ mask_pred (Tensor): Mask outputs of shape
39
+ (num_queries, h, w) for a image.
40
+
41
+ Returns:
42
+ Tensor: Panoptic segment result of shape \
43
+ (h, w), each element in Tensor means: \
44
+ ``segment_id = _cls + instance_id * INSTANCE_OFFSET``.
45
+ """
46
+ object_mask_thr = self.test_cfg.get('object_mask_thr', 0.8)
47
+ iou_thr = self.test_cfg.get('iou_thr', 0.8)
48
+ filter_low_score = self.test_cfg.get('filter_low_score', False)
49
+
50
+ scores, labels = F.softmax(mask_cls, dim=-1).max(-1)
51
+ mask_pred = mask_pred.sigmoid()
52
+
53
+ keep = labels.ne(self.num_classes) & (scores > object_mask_thr)
54
+ cur_scores = scores[keep]
55
+ cur_classes = labels[keep]
56
+ cur_masks = mask_pred[keep]
57
+
58
+ cur_prob_masks = cur_scores.view(-1, 1, 1) * cur_masks
59
+
60
+ h, w = cur_masks.shape[-2:]
61
+ panoptic_seg = torch.full((h, w),
62
+ self.num_classes,
63
+ dtype=torch.int32,
64
+ device=cur_masks.device)
65
+ if cur_masks.shape[0] == 0:
66
+ # We didn't detect any mask :(
67
+ pass
68
+ else:
69
+ cur_mask_ids = cur_prob_masks.argmax(0)
70
+ instance_id = 1
71
+ for k in range(cur_classes.shape[0]):
72
+ pred_class = int(cur_classes[k].item())
73
+ isthing = pred_class < self.num_things_classes
74
+ mask = cur_mask_ids == k
75
+ mask_area = mask.sum().item()
76
+ original_area = (cur_masks[k] >= 0.5).sum().item()
77
+
78
+ if filter_low_score:
79
+ mask = mask & (cur_masks[k] >= 0.5)
80
+
81
+ if mask_area > 0 and original_area > 0:
82
+ if mask_area / original_area < iou_thr:
83
+ continue
84
+
85
+ if not isthing:
86
+ # different stuff regions of same class will be
87
+ # merged here, and stuff share the instance_id 0.
88
+ panoptic_seg[mask] = pred_class
89
+ else:
90
+ panoptic_seg[mask] = (
91
+ pred_class + instance_id * INSTANCE_OFFSET)
92
+ instance_id += 1
93
+
94
+ return panoptic_seg
95
+
96
+ def panoptic_postprocess_with_query(self, mask_cls, mask_pred, query_feats):
97
+ """Panoptic segmengation inference.
98
+
99
+ Args:
100
+ mask_cls (Tensor): Classfication outputs of shape
101
+ (num_queries, cls_out_channels) for a image.
102
+ Note `cls_out_channels` should includes
103
+ background.
104
+ mask_pred (Tensor): Mask outputs of shape
105
+ (num_queries, h, w) for a image.
106
+
107
+ Returns:
108
+ Tensor: Panoptic segment result of shape \
109
+ (h, w), each element in Tensor means: \
110
+ ``segment_id = _cls + instance_id * INSTANCE_OFFSET``.
111
+ """
112
+ # import pdb; pdb.set_trace()
113
+ object_mask_thr = self.test_cfg.get('object_mask_thr', 0.8)
114
+ iou_thr = self.test_cfg.get('iou_thr', 0.8)
115
+ filter_low_score = self.test_cfg.get('filter_low_score', False)
116
+
117
+ scores, labels = F.softmax(mask_cls, dim=-1).max(-1)
118
+ mask_pred = mask_pred.sigmoid()
119
+
120
+ keep = labels.ne(self.num_classes) & (scores > object_mask_thr)
121
+ cur_scores = scores[keep]
122
+ cur_classes = labels[keep]
123
+ cur_masks = mask_pred[keep]
124
+ cur_query_feats = query_feats[keep] # filter query feats
125
+
126
+ cur_prob_masks = cur_scores.view(-1, 1, 1) * cur_masks
127
+
128
+ h, w = cur_masks.shape[-2:]
129
+ panoptic_seg = torch.full((h, w),
130
+ self.num_classes,
131
+ dtype=torch.int32,
132
+ device=cur_masks.device)
133
+ query_feat_dict = defaultdict(list)
134
+
135
+ if cur_masks.shape[0] == 0:
136
+ # We didn't detect any mask :(
137
+ pass
138
+ else:
139
+ cur_mask_ids = cur_prob_masks.argmax(0)
140
+ instance_id = 1
141
+ for k in range(cur_classes.shape[0]):
142
+ pred_class = int(cur_classes[k].item())
143
+ query_feat_k = cur_query_feats[k] # shape - [1, 256]
144
+ isthing = pred_class < self.num_things_classes
145
+ mask = cur_mask_ids == k
146
+ mask_area = mask.sum().item()
147
+ original_area = (cur_masks[k] >= 0.5).sum().item()
148
+
149
+ if filter_low_score:
150
+ mask = mask & (cur_masks[k] >= 0.5)
151
+
152
+ if mask_area > 0 and original_area > 0:
153
+ if mask_area / original_area < iou_thr:
154
+ continue
155
+
156
+ if not isthing:
157
+ # different stuff regions of same class will be
158
+ # merged here, and stuff share the instance_id 0.
159
+ if len(torch.unique(mask)) == 1 and torch.unique(mask).item() == False:
160
+ continue # for the case can reach this step but "mask = mask & (cur_masks[k] >= 0.5)" becomes all "False" when filtering low scores!
161
+ panoptic_seg[mask] = pred_class
162
+ query_feat_dict[pred_class].append(query_feat_k)
163
+ else:
164
+ if len(torch.unique(mask)) == 1 and torch.unique(mask).item() == False:
165
+ continue # for the case can reach this step but "mask = mask & (cur_masks[k] >= 0.5)" becomes all "False" when filtering low scores!
166
+ panoptic_seg[mask] = (
167
+ pred_class + instance_id * INSTANCE_OFFSET)
168
+ query_feat_dict[pred_class + instance_id * INSTANCE_OFFSET].append(query_feat_k)
169
+ instance_id += 1 # update at last!!!
170
+ # import pdb; pdb.set_trace()
171
+ return panoptic_seg, query_feat_dict
172
+
173
+
174
+ def semantic_postprocess(self, mask_cls, mask_pred):
175
+ """Semantic segmengation postprocess.
176
+
177
+ Args:
178
+ mask_cls (Tensor): Classfication outputs of shape
179
+ (num_queries, cls_out_channels) for a image.
180
+ Note `cls_out_channels` should includes
181
+ background.
182
+ mask_pred (Tensor): Mask outputs of shape
183
+ (num_queries, h, w) for a image.
184
+
185
+ Returns:
186
+ Tensor: Semantic segment result of shape \
187
+ (cls_out_channels, h, w).
188
+ """
189
+ # TODO add semantic segmentation result
190
+ raise NotImplementedError
191
+
192
+ def instance_postprocess(self, mask_cls, mask_pred):
193
+ """Instance segmengation postprocess.
194
+
195
+ Args:
196
+ mask_cls (Tensor): Classfication outputs of shape
197
+ (num_queries, cls_out_channels) for a image.
198
+ Note `cls_out_channels` should includes
199
+ background.
200
+ mask_pred (Tensor): Mask outputs of shape
201
+ (num_queries, h, w) for a image.
202
+
203
+ Returns:
204
+ tuple[Tensor]: Instance segmentation results.
205
+
206
+ - labels_per_image (Tensor): Predicted labels,\
207
+ shape (n, ).
208
+ - bboxes (Tensor): Bboxes and scores with shape (n, 5) of \
209
+ positive region in binary mask, the last column is scores.
210
+ - mask_pred_binary (Tensor): Instance masks of \
211
+ shape (n, h, w).
212
+ """
213
+ max_per_image = self.test_cfg.get('max_per_image', 100)
214
+ num_queries = mask_cls.shape[0]
215
+ # shape (num_queries, num_class)
216
+ scores = F.softmax(mask_cls, dim=-1)[:, :-1]
217
+ # shape (num_queries * num_class, )
218
+ labels = torch.arange(self.num_classes, device=mask_cls.device).\
219
+ unsqueeze(0).repeat(num_queries, 1).flatten(0, 1)
220
+ scores_per_image, top_indices = scores.flatten(0, 1).topk(
221
+ max_per_image, sorted=False)
222
+ labels_per_image = labels[top_indices]
223
+
224
+ query_indices = top_indices // self.num_classes
225
+ mask_pred = mask_pred[query_indices]
226
+
227
+ # extract things
228
+ is_thing = labels_per_image < self.num_things_classes
229
+ scores_per_image = scores_per_image[is_thing]
230
+ labels_per_image = labels_per_image[is_thing]
231
+ mask_pred = mask_pred[is_thing]
232
+
233
+ mask_pred_binary = (mask_pred > 0).float()
234
+ mask_scores_per_image = (mask_pred.sigmoid() *
235
+ mask_pred_binary).flatten(1).sum(1) / (
236
+ mask_pred_binary.flatten(1).sum(1) + 1e-6)
237
+ det_scores = scores_per_image * mask_scores_per_image
238
+ mask_pred_binary = mask_pred_binary.bool()
239
+ bboxes = mask2bbox(mask_pred_binary)
240
+ bboxes = torch.cat([bboxes, det_scores[:, None]], dim=-1)
241
+
242
+ return labels_per_image, bboxes, mask_pred_binary
243
+
244
+ def simple_test(self,
245
+ mask_cls_results,
246
+ mask_pred_results,
247
+ img_metas,
248
+ rescale=False,
249
+ **kwargs):
250
+ """Test segment without test-time aumengtation.
251
+
252
+ Only the output of last decoder layers was used.
253
+
254
+ Args:
255
+ mask_cls_results (Tensor): Mask classification logits,
256
+ shape (batch_size, num_queries, cls_out_channels).
257
+ Note `cls_out_channels` should includes background.
258
+ mask_pred_results (Tensor): Mask logits, shape
259
+ (batch_size, num_queries, h, w).
260
+ img_metas (list[dict]): List of image information.
261
+ rescale (bool, optional): If True, return boxes in
262
+ original image space. Default False.
263
+
264
+ Returns:
265
+ list[dict[str, Tensor | tuple[Tensor]]]: Semantic segmentation \
266
+ results and panoptic segmentation results for each \
267
+ image.
268
+
269
+ .. code-block:: none
270
+
271
+ [
272
+ {
273
+ 'pan_results': Tensor, # shape = [h, w]
274
+ 'ins_results': tuple[Tensor],
275
+ # semantic segmentation results are not supported yet
276
+ 'sem_results': Tensor
277
+ },
278
+ ...
279
+ ]
280
+ """
281
+ panoptic_on = self.test_cfg.get('panoptic_on', True)
282
+ semantic_on = self.test_cfg.get('semantic_on', False)
283
+ instance_on = self.test_cfg.get('instance_on', False)
284
+ assert not semantic_on, 'segmantic segmentation '\
285
+ 'results are not supported yet.'
286
+
287
+ results = []
288
+ for mask_cls_result, mask_pred_result, meta in zip(
289
+ mask_cls_results, mask_pred_results, img_metas):
290
+ # remove padding
291
+ img_height, img_width = meta['img_shape'][:2]
292
+ mask_pred_result = mask_pred_result[:, :img_height, :img_width]
293
+
294
+ if rescale:
295
+ # return result in original resolution
296
+ ori_height, ori_width = meta['ori_shape'][:2]
297
+ mask_pred_result = F.interpolate(
298
+ mask_pred_result[:, None],
299
+ size=(ori_height, ori_width),
300
+ mode='bilinear',
301
+ align_corners=False)[:, 0]
302
+
303
+ result = dict()
304
+ if panoptic_on:
305
+ pan_results = self.panoptic_postprocess(
306
+ mask_cls_result, mask_pred_result)
307
+ result['pan_results'] = pan_results
308
+
309
+ if instance_on:
310
+ ins_results = self.instance_postprocess(
311
+ mask_cls_result, mask_pred_result)
312
+ result['ins_results'] = ins_results
313
+
314
+ if semantic_on:
315
+ sem_results = self.semantic_postprocess(
316
+ mask_cls_result, mask_pred_result)
317
+ result['sem_results'] = sem_results
318
+
319
+ results.append(result)
320
+
321
+ return results
322
+
323
+
324
+
325
+ def simple_test_with_query(self,
326
+ mask_cls_results,
327
+ mask_pred_results,
328
+ query_feats, # N query feats
329
+ img_metas,
330
+ rescale=False,
331
+ **kwargs):
332
+ """Test segment without test-time aumengtation.
333
+
334
+ Only the output of last decoder layers was used.
335
+
336
+ Args:
337
+ mask_cls_results (Tensor): Mask classification logits,
338
+ shape (batch_size, num_queries, cls_out_channels).
339
+ Note `cls_out_channels` should includes background.
340
+ mask_pred_results (Tensor): Mask logits, shape
341
+ (batch_size, num_queries, h, w).
342
+ img_metas (list[dict]): List of image information.
343
+ rescale (bool, optional): If True, return boxes in
344
+ original image space. Default False.
345
+
346
+ Returns:
347
+ list[dict[str, Tensor | tuple[Tensor]]]: Semantic segmentation \
348
+ results and panoptic segmentation results for each \
349
+ image.
350
+
351
+ .. code-block:: none
352
+
353
+ [
354
+ {
355
+ 'pan_results': Tensor, # shape = [h, w]
356
+ 'ins_results': tuple[Tensor],
357
+ # semantic segmentation results are not supported yet
358
+ 'sem_results': Tensor
359
+ },
360
+ ...
361
+ ]
362
+ """
363
+ panoptic_on = self.test_cfg.get('panoptic_on', True)
364
+ semantic_on = self.test_cfg.get('semantic_on', False)
365
+ instance_on = self.test_cfg.get('instance_on', False)
366
+ assert not semantic_on, 'segmantic segmentation '\
367
+ 'results are not supported yet.'
368
+
369
+ results = []
370
+ for mask_cls_result, mask_pred_result, query_feat, meta in zip(
371
+ mask_cls_results, mask_pred_results, query_feats, img_metas):
372
+ # remove padding
373
+ img_height, img_width = meta['img_shape'][:2]
374
+ mask_pred_result = mask_pred_result[:, :img_height, :img_width]
375
+
376
+ if rescale:
377
+ # return result in original resolution
378
+ ori_height, ori_width = meta['ori_shape'][:2]
379
+ mask_pred_result = F.interpolate(
380
+ mask_pred_result[:, None],
381
+ size=(ori_height, ori_width),
382
+ mode='bilinear',
383
+ align_corners=False)[:, 0]
384
+
385
+ result = dict()
386
+ if panoptic_on:
387
+ pan_results, query_feat_dict = self.panoptic_postprocess_with_query(
388
+ mask_cls_result, mask_pred_result, query_feat)
389
+ result['pan_results'] = pan_results
390
+ result['query_feats'] = query_feat_dict
391
+
392
+ if instance_on:
393
+ ins_results = self.instance_postprocess(
394
+ mask_cls_result, mask_pred_result)
395
+ result['ins_results'] = ins_results
396
+
397
+ if semantic_on:
398
+ sem_results = self.semantic_postprocess(
399
+ mask_cls_result, mask_pred_result)
400
+ result['sem_results'] = sem_results
401
+
402
+ results.append(result)
403
+
404
+ return results
OpenPVSG/models/mask2former/mask2former_head.py ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import copy
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from mmcv.cnn import Conv2d, build_plugin_layer, caffe2_xavier_init
8
+ from mmcv.cnn.bricks.transformer import (build_positional_encoding,
9
+ build_transformer_layer_sequence)
10
+ from mmcv.ops import point_sample
11
+ from mmcv.runner import ModuleList, force_fp32
12
+
13
+ from mmdet.core import build_assigner, build_sampler, reduce_mean, multi_apply
14
+ from mmdet.models.utils import get_uncertain_point_coords_with_randomness
15
+ from mmdet.models.builder import HEADS, build_loss
16
+ from mmdet.models.dense_heads.anchor_free_head import AnchorFreeHead
17
+ from mmdet.models.dense_heads.maskformer_head import MaskFormerHead
18
+
19
+
20
+ @HEADS.register_module()
21
+ class Mask2FormerHeadCustom(MaskFormerHead):
22
+ """Implements the Mask2Former head.
23
+
24
+ See `Masked-attention Mask Transformer for Universal Image
25
+ Segmentation <https://arxiv.org/pdf/2112.01527>`_ for details.
26
+
27
+ Args:
28
+ in_channels (list[int]): Number of channels in the input feature map.
29
+ feat_channels (int): Number of channels for features.
30
+ out_channels (int): Number of channels for output.
31
+ num_things_classes (int): Number of things.
32
+ num_stuff_classes (int): Number of stuff.
33
+ num_queries (int): Number of query in Transformer decoder.
34
+ pixel_decoder (:obj:`mmcv.ConfigDict` | dict): Config for pixel
35
+ decoder. Defaults to None.
36
+ enforce_decoder_input_project (bool, optional): Whether to add
37
+ a layer to change the embed_dim of tranformer encoder in
38
+ pixel decoder to the embed_dim of transformer decoder.
39
+ Defaults to False.
40
+ transformer_decoder (:obj:`mmcv.ConfigDict` | dict): Config for
41
+ transformer decoder. Defaults to None.
42
+ positional_encoding (:obj:`mmcv.ConfigDict` | dict): Config for
43
+ transformer decoder position encoding. Defaults to None.
44
+ loss_cls (:obj:`mmcv.ConfigDict` | dict): Config of the classification
45
+ loss. Defaults to None.
46
+ loss_mask (:obj:`mmcv.ConfigDict` | dict): Config of the mask loss.
47
+ Defaults to None.
48
+ loss_dice (:obj:`mmcv.ConfigDict` | dict): Config of the dice loss.
49
+ Defaults to None.
50
+ train_cfg (:obj:`mmcv.ConfigDict` | dict): Training config of
51
+ Mask2Former head.
52
+ test_cfg (:obj:`mmcv.ConfigDict` | dict): Testing config of
53
+ Mask2Former head.
54
+ init_cfg (dict or list[dict], optional): Initialization config dict.
55
+ Defaults to None.
56
+ """
57
+
58
+ def __init__(self,
59
+ in_channels,
60
+ feat_channels,
61
+ out_channels,
62
+ num_things_classes=80,
63
+ num_stuff_classes=53,
64
+ num_queries=100,
65
+ num_transformer_feat_level=3,
66
+ pixel_decoder=None,
67
+ enforce_decoder_input_project=False,
68
+ transformer_decoder=None,
69
+ positional_encoding=None,
70
+ loss_cls=None,
71
+ loss_mask=None,
72
+ loss_dice=None,
73
+ train_cfg=None,
74
+ test_cfg=None,
75
+ init_cfg=None,
76
+ **kwargs):
77
+ super(AnchorFreeHead, self).__init__(init_cfg)
78
+ self.num_things_classes = num_things_classes
79
+ self.num_stuff_classes = num_stuff_classes
80
+ self.num_classes = self.num_things_classes + self.num_stuff_classes
81
+ self.num_queries = num_queries
82
+ self.num_transformer_feat_level = num_transformer_feat_level
83
+ self.num_heads = transformer_decoder.transformerlayers.\
84
+ attn_cfgs.num_heads
85
+ self.num_transformer_decoder_layers = transformer_decoder.num_layers
86
+ assert pixel_decoder.encoder.transformerlayers.\
87
+ attn_cfgs.num_levels == num_transformer_feat_level
88
+ pixel_decoder_ = copy.deepcopy(pixel_decoder)
89
+ pixel_decoder_.update(
90
+ in_channels=in_channels,
91
+ feat_channels=feat_channels,
92
+ out_channels=out_channels)
93
+ self.pixel_decoder = build_plugin_layer(pixel_decoder_)[1]
94
+ self.transformer_decoder = build_transformer_layer_sequence(
95
+ transformer_decoder)
96
+ self.decoder_embed_dims = self.transformer_decoder.embed_dims
97
+
98
+ self.decoder_input_projs = ModuleList()
99
+ # from low resolution to high resolution
100
+ for _ in range(num_transformer_feat_level):
101
+ if (self.decoder_embed_dims != feat_channels
102
+ or enforce_decoder_input_project):
103
+ self.decoder_input_projs.append(
104
+ Conv2d(
105
+ feat_channels, self.decoder_embed_dims, kernel_size=1))
106
+ else:
107
+ self.decoder_input_projs.append(nn.Identity())
108
+ self.decoder_positional_encoding = build_positional_encoding(
109
+ positional_encoding)
110
+ self.query_embed = nn.Embedding(self.num_queries, feat_channels)
111
+ self.query_feat = nn.Embedding(self.num_queries, feat_channels)
112
+ # from low resolution to high resolution
113
+ self.level_embed = nn.Embedding(self.num_transformer_feat_level,
114
+ feat_channels)
115
+
116
+ self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1)
117
+ self.mask_embed = nn.Sequential(
118
+ nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
119
+ nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
120
+ nn.Linear(feat_channels, out_channels))
121
+
122
+ self.test_cfg = test_cfg
123
+ self.train_cfg = train_cfg
124
+ if train_cfg:
125
+ self.assigner = build_assigner(self.train_cfg.assigner)
126
+ self.sampler = build_sampler(self.train_cfg.sampler, context=self)
127
+ self.num_points = self.train_cfg.get('num_points', 12544)
128
+ self.oversample_ratio = self.train_cfg.get('oversample_ratio', 3.0)
129
+ self.importance_sample_ratio = self.train_cfg.get(
130
+ 'importance_sample_ratio', 0.75)
131
+
132
+ self.class_weight = loss_cls.class_weight
133
+ self.loss_cls = build_loss(loss_cls)
134
+ self.loss_mask = build_loss(loss_mask)
135
+ self.loss_dice = build_loss(loss_dice)
136
+
137
+ def init_weights(self):
138
+ for m in self.decoder_input_projs:
139
+ if isinstance(m, Conv2d):
140
+ caffe2_xavier_init(m, bias=0)
141
+
142
+ self.pixel_decoder.init_weights()
143
+
144
+ for p in self.transformer_decoder.parameters():
145
+ if p.dim() > 1:
146
+ nn.init.xavier_normal_(p)
147
+
148
+ def _get_target_single(self, cls_score, mask_pred, gt_labels, gt_masks,
149
+ img_metas):
150
+ """Compute classification and mask targets for one image.
151
+
152
+ Args:
153
+ cls_score (Tensor): Mask score logits from a single decoder layer
154
+ for one image. Shape (num_queries, cls_out_channels).
155
+ mask_pred (Tensor): Mask logits for a single decoder layer for one
156
+ image. Shape (num_queries, h, w).
157
+ gt_labels (Tensor): Ground truth class indices for one image with
158
+ shape (num_gts, ).
159
+ gt_masks (Tensor): Ground truth mask for each image, each with
160
+ shape (num_gts, h, w).
161
+ img_metas (dict): Image information.
162
+
163
+ Returns:
164
+ tuple[Tensor]: A tuple containing the following for one image.
165
+
166
+ - labels (Tensor): Labels of each image. \
167
+ shape (num_queries, ).
168
+ - label_weights (Tensor): Label weights of each image. \
169
+ shape (num_queries, ).
170
+ - mask_targets (Tensor): Mask targets of each image. \
171
+ shape (num_queries, h, w).
172
+ - mask_weights (Tensor): Mask weights of each image. \
173
+ shape (num_queries, ).
174
+ - pos_inds (Tensor): Sampled positive indices for each \
175
+ image.
176
+ - neg_inds (Tensor): Sampled negative indices for each \
177
+ image.
178
+ """
179
+
180
+ # sample points
181
+ num_queries = cls_score.shape[0]
182
+ num_gts = gt_labels.shape[0]
183
+
184
+ point_coords = torch.rand((1, self.num_points, 2),
185
+ device=cls_score.device)
186
+ # shape (num_queries, num_points)
187
+ mask_points_pred = point_sample(
188
+ mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1,
189
+ 1)).squeeze(1)
190
+ # shape (num_gts, num_points)
191
+ gt_points_masks = point_sample(
192
+ gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1,
193
+ 1)).squeeze(1)
194
+
195
+ # assign and sample
196
+ assign_result = self.assigner.assign(cls_score, mask_points_pred,
197
+ gt_labels, gt_points_masks,
198
+ img_metas)
199
+ sampling_result = self.sampler.sample(assign_result, mask_pred,
200
+ gt_masks)
201
+ pos_inds = sampling_result.pos_inds
202
+ neg_inds = sampling_result.neg_inds
203
+
204
+ # label target (thing or stuff labels)
205
+ labels = gt_labels.new_full((num_queries, ),
206
+ self.num_classes,
207
+ dtype=torch.long)
208
+ labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds]
209
+ label_weights = gt_labels.new_ones((num_queries, ))
210
+
211
+ # mask target
212
+ mask_targets = gt_masks[sampling_result.pos_assigned_gt_inds]
213
+ mask_weights = mask_pred.new_zeros((num_queries, ))
214
+ mask_weights[pos_inds] = 1.0
215
+
216
+ return (labels, label_weights, mask_targets, mask_weights, pos_inds,
217
+ neg_inds)
218
+
219
+ def loss_single(self, cls_scores, mask_preds, gt_labels_list,
220
+ gt_masks_list, img_metas):
221
+ """Loss function for outputs from a single decoder layer.
222
+
223
+ Args:
224
+ cls_scores (Tensor): Mask score logits from a single decoder layer
225
+ for all images. Shape (batch_size, num_queries,
226
+ cls_out_channels). Note `cls_out_channels` should includes
227
+ background.
228
+ mask_preds (Tensor): Mask logits for a pixel decoder for all
229
+ images. Shape (batch_size, num_queries, h, w).
230
+ gt_labels_list (list[Tensor]): Ground truth class indices for each
231
+ image, each with shape (num_gts, ).
232
+ gt_masks_list (list[Tensor]): Ground truth mask for each image,
233
+ each with shape (num_gts, h, w).
234
+ img_metas (list[dict]): List of image meta information.
235
+
236
+ Returns:
237
+ tuple[Tensor]: Loss components for outputs from a single \
238
+ decoder layer.
239
+ """
240
+ num_imgs = cls_scores.size(0)
241
+ cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
242
+ mask_preds_list = [mask_preds[i] for i in range(num_imgs)]
243
+ (labels_list, label_weights_list, mask_targets_list, mask_weights_list,
244
+ num_total_pos,
245
+ num_total_neg) = self.get_targets(cls_scores_list, mask_preds_list,
246
+ gt_labels_list, gt_masks_list,
247
+ img_metas)
248
+
249
+ # shape (batch_size, num_queries)
250
+ labels = torch.stack(labels_list, dim=0)
251
+ # shape (batch_size, num_queries)
252
+ label_weights = torch.stack(label_weights_list, dim=0)
253
+ # shape (num_total_gts, h, w)
254
+ mask_targets = torch.cat(mask_targets_list, dim=0)
255
+ # shape (batch_size, num_queries)
256
+ mask_weights = torch.stack(mask_weights_list, dim=0)
257
+
258
+ # classification loss
259
+ # shape (batch_size * num_queries, )
260
+ cls_scores = cls_scores.flatten(0, 1)
261
+ labels = labels.flatten(0, 1)
262
+ label_weights = label_weights.flatten(0, 1)
263
+
264
+ class_weight = cls_scores.new_tensor(self.class_weight)
265
+ loss_cls = self.loss_cls(
266
+ cls_scores,
267
+ labels,
268
+ label_weights,
269
+ avg_factor=class_weight[labels].sum())
270
+
271
+ num_total_masks = reduce_mean(cls_scores.new_tensor([num_total_pos]))
272
+ num_total_masks = max(num_total_masks, 1)
273
+
274
+ # extract positive ones
275
+ # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w)
276
+ mask_preds = mask_preds[mask_weights > 0]
277
+
278
+ if mask_targets.shape[0] == 0:
279
+ # zero match
280
+ loss_dice = mask_preds.sum()
281
+ loss_mask = mask_preds.sum()
282
+ return loss_cls, loss_mask, loss_dice
283
+
284
+ with torch.no_grad():
285
+ points_coords = get_uncertain_point_coords_with_randomness(
286
+ mask_preds.unsqueeze(1), None, self.num_points,
287
+ self.oversample_ratio, self.importance_sample_ratio)
288
+ # shape (num_total_gts, h, w) -> (num_total_gts, num_points)
289
+ mask_point_targets = point_sample(
290
+ mask_targets.unsqueeze(1).float(), points_coords).squeeze(1)
291
+ # shape (num_queries, h, w) -> (num_queries, num_points)
292
+ mask_point_preds = point_sample(
293
+ mask_preds.unsqueeze(1), points_coords).squeeze(1)
294
+
295
+ # dice loss
296
+ loss_dice = self.loss_dice(
297
+ mask_point_preds, mask_point_targets, avg_factor=num_total_masks)
298
+
299
+ # mask loss
300
+ # shape (num_queries, num_points) -> (num_queries * num_points, )
301
+ mask_point_preds = mask_point_preds.reshape(-1)
302
+ # shape (num_total_gts, num_points) -> (num_total_gts * num_points, )
303
+ mask_point_targets = mask_point_targets.reshape(-1)
304
+ loss_mask = self.loss_mask(
305
+ mask_point_preds,
306
+ mask_point_targets,
307
+ avg_factor=num_total_masks * self.num_points)
308
+
309
+ return loss_cls, loss_mask, loss_dice
310
+
311
+ def get_targets(self, cls_scores_list, mask_preds_list, gt_labels_list,
312
+ gt_masks_list, img_metas):
313
+ """Compute classification and mask targets for all images for a decoder
314
+ layer.
315
+
316
+ Args:
317
+ cls_scores_list (list[Tensor]): Mask score logits from a single
318
+ decoder layer for all images. Each with shape (num_queries,
319
+ cls_out_channels).
320
+ mask_preds_list (list[Tensor]): Mask logits from a single decoder
321
+ layer for all images. Each with shape (num_queries, h, w).
322
+ gt_labels_list (list[Tensor]): Ground truth class indices for all
323
+ images. Each with shape (n, ), n is the sum of number of stuff
324
+ type and number of instance in a image.
325
+ gt_masks_list (list[Tensor]): Ground truth mask for each image,
326
+ each with shape (n, h, w).
327
+ img_metas (list[dict]): List of image meta information.
328
+
329
+ Returns:
330
+ tuple[list[Tensor]]: a tuple containing the following targets.
331
+ - labels_list (list[Tensor]): Labels of all images.\
332
+ Each with shape (num_queries, ).
333
+ - label_weights_list (list[Tensor]): Label weights\
334
+ of all images. Each with shape (num_queries, ).
335
+ - mask_targets_list (list[Tensor]): Mask targets of\
336
+ all images. Each with shape (num_queries, h, w).
337
+ - mask_weights_list (list[Tensor]): Mask weights of\
338
+ all images. Each with shape (num_queries, ).
339
+ - num_total_pos (int): Number of positive samples in\
340
+ all images.
341
+ - num_total_neg (int): Number of negative samples in\
342
+ all images.
343
+ """
344
+ (labels_list, label_weights_list, mask_targets_list, mask_weights_list,
345
+ pos_inds_list,
346
+ neg_inds_list) = multi_apply(self._get_target_single, cls_scores_list,
347
+ mask_preds_list, gt_labels_list,
348
+ gt_masks_list, img_metas)
349
+
350
+ num_total_pos = sum((inds.numel() for inds in pos_inds_list))
351
+ num_total_neg = sum((inds.numel() for inds in neg_inds_list))
352
+ return (labels_list, label_weights_list, mask_targets_list,
353
+ mask_weights_list, num_total_pos, num_total_neg)
354
+
355
+ def forward_head(self, decoder_out, mask_feature, attn_mask_target_size):
356
+ """Forward for head part which is called after every decoder layer.
357
+
358
+ Args:
359
+ decoder_out (Tensor): in shape (num_queries, batch_size, c).
360
+ mask_feature (Tensor): in shape (batch_size, c, h, w).
361
+ attn_mask_target_size (tuple[int, int]): target attention
362
+ mask size.
363
+
364
+ Returns:
365
+ tuple: A tuple contain three elements.
366
+
367
+ - cls_pred (Tensor): Classification scores in shape \
368
+ (batch_size, num_queries, cls_out_channels). \
369
+ Note `cls_out_channels` should includes background.
370
+ - mask_pred (Tensor): Mask scores in shape \
371
+ (batch_size, num_queries,h, w).
372
+ - attn_mask (Tensor): Attention mask in shape \
373
+ (batch_size * num_heads, num_queries, h, w).
374
+ """
375
+ decoder_out = self.transformer_decoder.post_norm(decoder_out)
376
+ decoder_out = decoder_out.transpose(0, 1)
377
+ # shape (num_queries, batch_size, c)
378
+ cls_pred = self.cls_embed(decoder_out)
379
+ # shape (num_queries, batch_size, c)
380
+ mask_embed = self.mask_embed(decoder_out)
381
+ # shape (num_queries, batch_size, h, w)
382
+ mask_pred = torch.einsum('bqc,bchw->bqhw', mask_embed, mask_feature)
383
+ attn_mask = F.interpolate(
384
+ mask_pred,
385
+ attn_mask_target_size,
386
+ mode='bilinear',
387
+ align_corners=False)
388
+ # shape (num_queries, batch_size, h, w) ->
389
+ # (batch_size * num_head, num_queries, h, w)
390
+ attn_mask = attn_mask.flatten(2).unsqueeze(1).repeat(
391
+ (1, self.num_heads, 1, 1)).flatten(0, 1)
392
+ attn_mask = attn_mask.sigmoid() < 0.5
393
+ attn_mask = attn_mask.detach()
394
+
395
+ return cls_pred, mask_pred, attn_mask
396
+
397
+ def forward(self, feats, img_metas, return_query=False):
398
+ """Forward function.
399
+
400
+ Args:
401
+ feats (list[Tensor]): Multi scale Features from the
402
+ upstream network, each is a 4D-tensor.
403
+ img_metas (list[dict]): List of image information.
404
+
405
+ Returns:
406
+ tuple: A tuple contains two elements.
407
+
408
+ - cls_pred_list (list[Tensor)]: Classification logits \
409
+ for each decoder layer. Each is a 3D-tensor with shape \
410
+ (batch_size, num_queries, cls_out_channels). \
411
+ Note `cls_out_channels` should includes background.
412
+ - mask_pred_list (list[Tensor]): Mask logits for each \
413
+ decoder layer. Each with shape (batch_size, num_queries, \
414
+ h, w).
415
+ """
416
+ batch_size = len(img_metas)
417
+ mask_features, multi_scale_memorys = self.pixel_decoder(feats)
418
+ # multi_scale_memorys (from low resolution to high resolution)
419
+ decoder_inputs = []
420
+ decoder_positional_encodings = []
421
+ for i in range(self.num_transformer_feat_level):
422
+ decoder_input = self.decoder_input_projs[i](multi_scale_memorys[i])
423
+ # shape (batch_size, c, h, w) -> (h*w, batch_size, c)
424
+ decoder_input = decoder_input.flatten(2).permute(2, 0, 1)
425
+ level_embed = self.level_embed.weight[i].view(1, 1, -1)
426
+ decoder_input = decoder_input + level_embed
427
+ # shape (batch_size, c, h, w) -> (h*w, batch_size, c)
428
+ mask = decoder_input.new_zeros(
429
+ (batch_size, ) + multi_scale_memorys[i].shape[-2:],
430
+ dtype=torch.bool)
431
+ decoder_positional_encoding = self.decoder_positional_encoding(
432
+ mask)
433
+ decoder_positional_encoding = decoder_positional_encoding.flatten(
434
+ 2).permute(2, 0, 1)
435
+ decoder_inputs.append(decoder_input)
436
+ decoder_positional_encodings.append(decoder_positional_encoding)
437
+ # shape (num_queries, c) -> (num_queries, batch_size, c)
438
+ query_feat = self.query_feat.weight.unsqueeze(1).repeat(
439
+ (1, batch_size, 1))
440
+ query_embed = self.query_embed.weight.unsqueeze(1).repeat(
441
+ (1, batch_size, 1))
442
+
443
+ cls_pred_list = []
444
+ mask_pred_list = []
445
+ cls_pred, mask_pred, attn_mask = self.forward_head(
446
+ query_feat, mask_features, multi_scale_memorys[0].shape[-2:])
447
+ cls_pred_list.append(cls_pred)
448
+ mask_pred_list.append(mask_pred)
449
+
450
+ for i in range(self.num_transformer_decoder_layers):
451
+ level_idx = i % self.num_transformer_feat_level
452
+ # if a mask is all True(all background), then set it all False.
453
+ attn_mask[torch.where(
454
+ attn_mask.sum(-1) == attn_mask.shape[-1])] = False
455
+
456
+ # cross_attn + self_attn
457
+ layer = self.transformer_decoder.layers[i]
458
+ attn_masks = [attn_mask, None]
459
+ query_feat = layer(
460
+ query=query_feat,
461
+ key=decoder_inputs[level_idx],
462
+ value=decoder_inputs[level_idx],
463
+ query_pos=query_embed,
464
+ key_pos=decoder_positional_encodings[level_idx],
465
+ attn_masks=attn_masks,
466
+ query_key_padding_mask=None,
467
+ # here we do not apply masking on padded region
468
+ key_padding_mask=None)
469
+ cls_pred, mask_pred, attn_mask = self.forward_head(
470
+ query_feat, mask_features, multi_scale_memorys[
471
+ (i + 1) % self.num_transformer_feat_level].shape[-2:])
472
+
473
+ cls_pred_list.append(cls_pred)
474
+ mask_pred_list.append(mask_pred)
475
+
476
+ if return_query:
477
+ return cls_pred_list, mask_pred_list, query_feat
478
+ else:
479
+ return cls_pred_list, mask_pred_list
480
+
481
+ def forward_train(self,
482
+ feats,
483
+ img_metas,
484
+ gt_bboxes,
485
+ gt_labels,
486
+ gt_masks,
487
+ gt_semantic_seg,
488
+ gt_bboxes_ignore=None):
489
+ """Forward function for training mode.
490
+
491
+ Args:
492
+ feats (list[Tensor]): Multi-level features from the upstream
493
+ network, each is a 4D-tensor.
494
+ img_metas (list[Dict]): List of image information.
495
+ gt_bboxes (list[Tensor]): Each element is ground truth bboxes of
496
+ the image, shape (num_gts, 4). Not used here.
497
+ gt_labels (list[Tensor]): Each element is ground truth labels of
498
+ each box, shape (num_gts,).
499
+ gt_masks (list[BitmapMasks]): Each element is masks of instances
500
+ of a image, shape (num_gts, h, w).
501
+ gt_semantic_seg (list[tensor] | None): Each element is the ground
502
+ truth of semantic segmentation with the shape (N, H, W).
503
+ [0, num_thing_class - 1] means things,
504
+ [num_thing_class, num_class-1] means stuff,
505
+ 255 means VOID. It's None when training instance segmentation.
506
+ gt_bboxes_ignore (list[Tensor]): Ground truth bboxes to be
507
+ ignored. Defaults to None.
508
+
509
+ Returns:
510
+ dict[str, Tensor]: a dictionary of loss components
511
+ """
512
+ # not consider ignoring bboxes
513
+ assert gt_bboxes_ignore is None
514
+
515
+ # forward
516
+ all_cls_scores, all_mask_preds = self(feats, img_metas)
517
+
518
+ # preprocess ground truth
519
+ gt_labels, gt_masks = self.preprocess_gt(gt_labels, gt_masks,
520
+ gt_semantic_seg, img_metas)
521
+
522
+ # loss
523
+ losses = self.loss(all_cls_scores, all_mask_preds, gt_labels, gt_masks,
524
+ gt_semantic_seg, img_metas)
525
+
526
+ return losses
527
+
528
+ @force_fp32(apply_to=('all_cls_scores', 'all_mask_preds'))
529
+ def loss(self, all_cls_scores, all_mask_preds, gt_labels_list,
530
+ gt_masks_list, gt_semantic_seg, img_metas):
531
+ """Loss function.
532
+
533
+ Args:
534
+ all_cls_scores (Tensor): Classification scores for all decoder
535
+ layers with shape (num_decoder, batch_size, num_queries,
536
+ cls_out_channels). Note `cls_out_channels` should includes
537
+ background.
538
+ all_mask_preds (Tensor): Mask scores for all decoder layers with
539
+ shape (num_decoder, batch_size, num_queries, h, w).
540
+ gt_labels_list (list[Tensor]): Ground truth class indices for each
541
+ image with shape (n, ). n is the sum of number of stuff type
542
+ and number of instance in a image.
543
+ gt_masks_list (list[Tensor]): Ground truth mask for each image with
544
+ shape (n, h, w).
545
+ img_metas (list[dict]): List of image meta information.
546
+
547
+ Returns:
548
+ dict[str, Tensor]: A dictionary of loss components.
549
+ """
550
+
551
+ num_dec_layers = len(all_cls_scores)
552
+ stuff_gt_labels = []
553
+ stuff_gt_masks = []
554
+ thing_gt_labels = []
555
+ thing_gt_masks = []
556
+
557
+ for gt_labels, gt_masks in zip(gt_labels_list, gt_masks_list):
558
+ num_stuff = sum(torch.unique(gt_labels) >= self.num_things_classes)
559
+ stuff_gt_labels.append(gt_labels[-num_stuff:])
560
+ stuff_gt_masks.append(gt_masks[-num_stuff:])
561
+ thing_gt_labels.append(gt_labels[:-num_stuff])
562
+ thing_gt_masks.append(gt_masks[:-num_stuff])
563
+
564
+ stuff_gt_labels_list = [stuff_gt_labels for _ in range(num_dec_layers)]
565
+ stuff_gt_masks_list = [stuff_gt_masks for _ in range(num_dec_layers)]
566
+
567
+ thing_gt_labels_list = [thing_gt_labels for _ in range(num_dec_layers)]
568
+ thing_gt_masks_list = [thing_gt_masks for _ in range(num_dec_layers)]
569
+
570
+ stuff_scores = [all_cls_score[:, -self.num_stuff_classes:, :] for all_cls_score in all_cls_scores]
571
+ stuff_mask_preds = [all_mask_pred[:, -self.num_stuff_classes:, :, :] for all_mask_pred in all_mask_preds ]
572
+
573
+ thing_scores = [all_cls_score[:, :-self.num_stuff_classes, :] for all_cls_score in all_cls_scores]
574
+ thing_mask_preds = [all_mask_pred[:, :-self.num_stuff_classes, :, :] for all_mask_pred in all_mask_preds]
575
+
576
+ img_metas_list = [img_metas for _ in range(num_dec_layers)]
577
+
578
+ losses_cls_stuff, losses_mask_stuff, losses_dice_stuff = multi_apply(
579
+ self.loss_single, stuff_scores, stuff_mask_preds,
580
+ stuff_gt_labels_list, stuff_gt_masks_list, img_metas_list)
581
+
582
+ losses_cls_thing, losses_mask_thing, losses_dice_thing = multi_apply(
583
+ self.loss_single, thing_scores, thing_mask_preds,
584
+ thing_gt_labels_list, thing_gt_masks_list, img_metas_list)
585
+
586
+ loss_dict = dict()
587
+
588
+ # loss from the last decoder layer
589
+ loss_dict['loss_cls'] = losses_cls_stuff[-1] + losses_cls_thing[-1]
590
+ loss_dict['loss_mask'] = losses_mask_stuff[-1] + losses_mask_thing[-1]
591
+ loss_dict['loss_dice'] = losses_dice_stuff[-1] + losses_dice_thing[-1]
592
+
593
+ # loss from other decoder layers stuff
594
+ num_dec_layer = 0
595
+ for loss_cls_i, loss_mask_i, loss_dice_i in zip(
596
+ losses_cls_stuff[:-1],
597
+ losses_mask_stuff[:-1],
598
+ losses_dice_stuff[:-1]):
599
+
600
+ loss_dict[f'd{num_dec_layer}.stuff_loss_cls'] = loss_cls_i
601
+ loss_dict[f'd{num_dec_layer}.stuff_loss_mask'] = loss_mask_i
602
+ loss_dict[f'd{num_dec_layer}.stuff_loss_dice'] = loss_dice_i
603
+ num_dec_layer += 1
604
+
605
+ # loss from other decoder layers thing
606
+ num_dec_layer = 0
607
+ for loss_cls_i, loss_mask_i, loss_dice_i in zip(
608
+ losses_mask_thing[:-1],
609
+ losses_mask_thing[:-1],
610
+ losses_mask_thing[:-1]):
611
+ loss_dict[f'd{num_dec_layer}.thing_loss_cls'] = loss_cls_i
612
+ loss_dict[f'd{num_dec_layer}.thing_loss_mask'] = loss_mask_i
613
+ loss_dict[f'd{num_dec_layer}.thing_loss_dice'] = loss_dice_i
614
+ num_dec_layer += 1
615
+
616
+ return loss_dict
617
+
618
+
619
+ def simple_test(self, feats, img_metas, **kwargs):
620
+ """Test without augmentaton.
621
+
622
+ Args:
623
+ feats (list[Tensor]): Multi-level features from the
624
+ upstream network, each is a 4D-tensor.
625
+ img_metas (list[dict]): List of image information.
626
+
627
+ Returns:
628
+ tuple: A tuple contains two tensors.
629
+
630
+ - mask_cls_results (Tensor): Mask classification logits,\
631
+ shape (batch_size, num_queries, cls_out_channels).
632
+ Note `cls_out_channels` should includes background.
633
+ - mask_pred_results (Tensor): Mask logits, shape \
634
+ (batch_size, num_queries, h, w).
635
+ """
636
+ all_cls_scores, all_mask_preds = self(feats, img_metas)
637
+ mask_cls_results = all_cls_scores[-1]
638
+ mask_pred_results = all_mask_preds[-1]
639
+
640
+ # upsample masks
641
+ img_shape = img_metas[0]['batch_input_shape']
642
+ mask_pred_results = F.interpolate(
643
+ mask_pred_results,
644
+ size=(img_shape[0], img_shape[1]),
645
+ mode='bilinear',
646
+ align_corners=False)
647
+
648
+ return mask_cls_results, mask_pred_results
649
+
650
+ def simple_test_with_query(self, feats, img_metas, **kwargs):
651
+ """Test without augmentaton.
652
+
653
+ Args:
654
+ feats (list[Tensor]): Multi-level features from the
655
+ upstream network, each is a 4D-tensor.
656
+ img_metas (list[dict]): List of image information.
657
+
658
+ Returns:
659
+ tuple: A tuple contains two tensors.
660
+
661
+ - mask_cls_results (Tensor): Mask classification logits,\
662
+ shape (batch_size, num_queries, cls_out_channels).
663
+ Note `cls_out_channels` should includes background.
664
+ - mask_pred_results (Tensor): Mask logits, shape \
665
+ (batch_size, num_queries, h, w).
666
+ """
667
+ all_cls_scores, all_mask_preds, query_feats = self.forward(feats, img_metas,return_query=True)
668
+ mask_cls_results = all_cls_scores[-1]
669
+ mask_pred_results = all_mask_preds[-1]
670
+
671
+ query_feats = torch.unsqueeze(query_feats, dim=0) # expand dim
672
+
673
+ # upsample masks
674
+ img_shape = img_metas[0]['batch_input_shape']
675
+ mask_pred_results = F.interpolate(
676
+ mask_pred_results,
677
+ size=(img_shape[0], img_shape[1]),
678
+ mode='bilinear',
679
+ align_corners=False)
680
+
681
+ return mask_cls_results, mask_pred_results, query_feats
OpenPVSG/models/mask2former/mask2former_head_focal.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import copy
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from mmcv.cnn import Conv2d, build_plugin_layer, caffe2_xavier_init
8
+ from mmcv.cnn.bricks.transformer import (build_positional_encoding,
9
+ build_transformer_layer_sequence)
10
+ from mmcv.ops import point_sample
11
+ from mmcv.runner import ModuleList, force_fp32
12
+
13
+ from mmdet.core import build_assigner, build_sampler, reduce_mean, multi_apply
14
+ from mmdet.models.utils import get_uncertain_point_coords_with_randomness
15
+ from mmdet.models.builder import HEADS, build_loss
16
+ from mmdet.models.dense_heads.anchor_free_head import AnchorFreeHead
17
+ from mmdet.models.dense_heads.maskformer_head import MaskFormerHead
18
+
19
+ @HEADS.register_module()
20
+ class Mask2FormerHeadFocal(MaskFormerHead):
21
+ """Implements the Mask2Former head.
22
+
23
+ See `Masked-attention Mask Transformer for Universal Image
24
+ Segmentation <https://arxiv.org/pdf/2112.01527>`_ for details.
25
+
26
+ Args:
27
+ in_channels (list[int]): Number of channels in the input feature map.
28
+ feat_channels (int): Number of channels for features.
29
+ out_channels (int): Number of channels for output.
30
+ num_things_classes (int): Number of things.
31
+ num_stuff_classes (int): Number of stuff.
32
+ num_queries (int): Number of query in Transformer decoder.
33
+ pixel_decoder (:obj:`mmcv.ConfigDict` | dict): Config for pixel
34
+ decoder. Defaults to None.
35
+ enforce_decoder_input_project (bool, optional): Whether to add
36
+ a layer to change the embed_dim of tranformer encoder in
37
+ pixel decoder to the embed_dim of transformer decoder.
38
+ Defaults to False.
39
+ transformer_decoder (:obj:`mmcv.ConfigDict` | dict): Config for
40
+ transformer decoder. Defaults to None.
41
+ positional_encoding (:obj:`mmcv.ConfigDict` | dict): Config for
42
+ transformer decoder position encoding. Defaults to None.
43
+ loss_cls (:obj:`mmcv.ConfigDict` | dict): Config of the classification
44
+ loss. Defaults to None.
45
+ loss_mask (:obj:`mmcv.ConfigDict` | dict): Config of the mask loss.
46
+ Defaults to None.
47
+ loss_dice (:obj:`mmcv.ConfigDict` | dict): Config of the dice loss.
48
+ Defaults to None.
49
+ train_cfg (:obj:`mmcv.ConfigDict` | dict): Training config of
50
+ Mask2Former head.
51
+ test_cfg (:obj:`mmcv.ConfigDict` | dict): Testing config of
52
+ Mask2Former head.
53
+ init_cfg (dict or list[dict], optional): Initialization config dict.
54
+ Defaults to None.
55
+ """
56
+
57
+ def __init__(self,
58
+ in_channels,
59
+ feat_channels,
60
+ out_channels,
61
+ num_things_classes=80,
62
+ num_stuff_classes=53,
63
+ num_queries=100,
64
+ num_transformer_feat_level=3,
65
+ pixel_decoder=None,
66
+ enforce_decoder_input_project=False,
67
+ transformer_decoder=None,
68
+ positional_encoding=None,
69
+ loss_cls=None,
70
+ loss_mask=None,
71
+ loss_dice=None,
72
+ train_cfg=None,
73
+ test_cfg=None,
74
+ init_cfg=None,
75
+ **kwargs):
76
+ super(AnchorFreeHead, self).__init__(init_cfg)
77
+ self.num_things_classes = num_things_classes
78
+ self.num_stuff_classes = num_stuff_classes
79
+ self.num_classes = self.num_things_classes + self.num_stuff_classes
80
+ self.num_queries = num_queries
81
+ self.num_transformer_feat_level = num_transformer_feat_level
82
+ self.num_heads = transformer_decoder.transformerlayers.\
83
+ attn_cfgs.num_heads
84
+ self.num_transformer_decoder_layers = transformer_decoder.num_layers
85
+ assert pixel_decoder.encoder.transformerlayers.\
86
+ attn_cfgs.num_levels == num_transformer_feat_level
87
+ pixel_decoder_ = copy.deepcopy(pixel_decoder)
88
+ pixel_decoder_.update(
89
+ in_channels=in_channels,
90
+ feat_channels=feat_channels,
91
+ out_channels=out_channels)
92
+ self.pixel_decoder = build_plugin_layer(pixel_decoder_)[1]
93
+ self.transformer_decoder = build_transformer_layer_sequence(
94
+ transformer_decoder)
95
+ self.decoder_embed_dims = self.transformer_decoder.embed_dims
96
+
97
+ self.decoder_input_projs = ModuleList()
98
+ # from low resolution to high resolution
99
+ for _ in range(num_transformer_feat_level):
100
+ if (self.decoder_embed_dims != feat_channels
101
+ or enforce_decoder_input_project):
102
+ self.decoder_input_projs.append(
103
+ Conv2d(
104
+ feat_channels, self.decoder_embed_dims, kernel_size=1))
105
+ else:
106
+ self.decoder_input_projs.append(nn.Identity())
107
+ self.decoder_positional_encoding = build_positional_encoding(
108
+ positional_encoding)
109
+ self.query_embed = nn.Embedding(self.num_queries, feat_channels)
110
+ self.query_feat = nn.Embedding(self.num_queries, feat_channels)
111
+ # from low resolution to high resolution
112
+ self.level_embed = nn.Embedding(self.num_transformer_feat_level,
113
+ feat_channels)
114
+
115
+ self.cls_embed = nn.Linear(feat_channels, self.num_classes)
116
+
117
+ self.mask_embed = nn.Sequential(
118
+ nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
119
+ nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
120
+ nn.Linear(feat_channels, out_channels))
121
+
122
+ self.test_cfg = test_cfg
123
+ self.train_cfg = train_cfg
124
+ if train_cfg:
125
+ self.assigner = build_assigner(self.train_cfg.assigner)
126
+ self.sampler = build_sampler(self.train_cfg.sampler, context=self)
127
+ self.num_points = self.train_cfg.get('num_points', 12544)
128
+ self.oversample_ratio = self.train_cfg.get('oversample_ratio', 3.0)
129
+ self.importance_sample_ratio = self.train_cfg.get(
130
+ 'importance_sample_ratio', 0.75)
131
+
132
+ self.loss_cls = build_loss(loss_cls)
133
+ self.loss_mask = build_loss(loss_mask)
134
+ self.loss_dice = build_loss(loss_dice)
135
+
136
+ def init_weights(self):
137
+ for m in self.decoder_input_projs:
138
+ if isinstance(m, Conv2d):
139
+ caffe2_xavier_init(m, bias=0)
140
+
141
+ self.pixel_decoder.init_weights()
142
+
143
+ for p in self.transformer_decoder.parameters():
144
+ if p.dim() > 1:
145
+ nn.init.xavier_normal_(p)
146
+
147
+ def _get_target_single(self, cls_score, mask_pred, gt_labels, gt_masks,
148
+ img_metas):
149
+ """Compute classification and mask targets for one image.
150
+
151
+ Args:
152
+ cls_score (Tensor): Mask score logits from a single decoder layer
153
+ for one image. Shape (num_queries, cls_out_channels).
154
+ mask_pred (Tensor): Mask logits for a single decoder layer for one
155
+ image. Shape (num_queries, h, w).
156
+ gt_labels (Tensor): Ground truth class indices for one image with
157
+ shape (num_gts, ).
158
+ gt_masks (Tensor): Ground truth mask for each image, each with
159
+ shape (num_gts, h, w).
160
+ img_metas (dict): Image information.
161
+
162
+ Returns:
163
+ tuple[Tensor]: A tuple containing the following for one image.
164
+
165
+ - labels (Tensor): Labels of each image. \
166
+ shape (num_queries, ).
167
+ - label_weights (Tensor): Label weights of each image. \
168
+ shape (num_queries, ).
169
+ - mask_targets (Tensor): Mask targets of each image. \
170
+ shape (num_queries, h, w).
171
+ - mask_weights (Tensor): Mask weights of each image. \
172
+ shape (num_queries, ).
173
+ - pos_inds (Tensor): Sampled positive indices for each \
174
+ image.
175
+ - neg_inds (Tensor): Sampled negative indices for each \
176
+ image.
177
+ """
178
+
179
+ # sample points
180
+ num_queries = cls_score.shape[0]
181
+ num_gts = gt_labels.shape[0]
182
+
183
+ point_coords = torch.rand((1, self.num_points, 2),
184
+ device=cls_score.device)
185
+ # shape (num_queries, num_points)
186
+ mask_points_pred = point_sample(
187
+ mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1,
188
+ 1)).squeeze(1)
189
+ # shape (num_gts, num_points)
190
+ gt_points_masks = point_sample(
191
+ gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1,
192
+ 1)).squeeze(1)
193
+
194
+ # assign and sample
195
+ assign_result = self.assigner.assign(cls_score, mask_points_pred,
196
+ gt_labels, gt_points_masks,
197
+ img_metas)
198
+ sampling_result = self.sampler.sample(assign_result, mask_pred,
199
+ gt_masks)
200
+ pos_inds = sampling_result.pos_inds
201
+ neg_inds = sampling_result.neg_inds
202
+
203
+ # label target (thing or stuff labels)
204
+ labels = gt_labels.new_full((num_queries, ),
205
+ self.num_classes,
206
+ dtype=torch.long)
207
+ labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds]
208
+ label_weights = gt_labels.new_ones((num_queries, ))
209
+
210
+ # mask target
211
+ mask_targets = gt_masks[sampling_result.pos_assigned_gt_inds]
212
+ mask_weights = mask_pred.new_zeros((num_queries, ))
213
+ mask_weights[pos_inds] = 1.0
214
+
215
+ return (labels, label_weights, mask_targets, mask_weights, pos_inds,
216
+ neg_inds)
217
+
218
+ def loss_single(self, cls_scores, mask_preds, gt_labels_list,
219
+ gt_masks_list, img_metas):
220
+ """Loss function for outputs from a single decoder layer.
221
+
222
+ Args:
223
+ cls_scores (Tensor): Mask score logits from a single decoder layer
224
+ for all images. Shape (batch_size, num_queries,
225
+ cls_out_channels). Note `cls_out_channels` should includes
226
+ background.
227
+ mask_preds (Tensor): Mask logits for a pixel decoder for all
228
+ images. Shape (batch_size, num_queries, h, w).
229
+ gt_labels_list (list[Tensor]): Ground truth class indices for each
230
+ image, each with shape (num_gts, ).
231
+ gt_masks_list (list[Tensor]): Ground truth mask for each image,
232
+ each with shape (num_gts, h, w).
233
+ img_metas (list[dict]): List of image meta information.
234
+
235
+ Returns:
236
+ tuple[Tensor]: Loss components for outputs from a single \
237
+ decoder layer.
238
+ """
239
+ num_imgs = cls_scores.size(0)
240
+ cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
241
+ mask_preds_list = [mask_preds[i] for i in range(num_imgs)]
242
+ (labels_list, label_weights_list, mask_targets_list, mask_weights_list,
243
+ num_total_pos,
244
+ num_total_neg) = self.get_targets(cls_scores_list, mask_preds_list,
245
+ gt_labels_list, gt_masks_list,
246
+ img_metas)
247
+
248
+ # shape (batch_size, num_queries)
249
+ labels = torch.stack(labels_list, dim=0)
250
+ # shape (batch_size, num_queries)
251
+ label_weights = torch.stack(label_weights_list, dim=0)
252
+ # shape (num_total_gts, h, w)
253
+ mask_targets = torch.cat(mask_targets_list, dim=0)
254
+ # shape (batch_size, num_queries)
255
+ mask_weights = torch.stack(mask_weights_list, dim=0)
256
+
257
+ # classification loss
258
+ # shape (batch_size * num_queries, )
259
+ cls_scores = cls_scores.flatten(0, 1)
260
+ labels = labels.flatten(0, 1)
261
+ label_weights = label_weights.flatten(0, 1)
262
+
263
+ num_total_masks = reduce_mean(cls_scores.new_tensor([num_total_pos]))
264
+ num_total_masks = max(num_total_masks, 1)
265
+
266
+ # class_weight = cls_scores.new_tensor(self.class_weight)
267
+ loss_cls = self.loss_cls(
268
+ cls_scores,
269
+ labels,
270
+ label_weights,
271
+ avg_factor=num_total_masks
272
+ )
273
+
274
+ # extract positive ones
275
+ # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w)
276
+ mask_preds = mask_preds[mask_weights > 0]
277
+
278
+ if mask_targets.shape[0] == 0:
279
+ # zero match
280
+ loss_dice = mask_preds.sum()
281
+ loss_mask = mask_preds.sum()
282
+ return loss_cls, loss_mask, loss_dice
283
+
284
+ with torch.no_grad():
285
+ points_coords = get_uncertain_point_coords_with_randomness(
286
+ mask_preds.unsqueeze(1), None, self.num_points,
287
+ self.oversample_ratio, self.importance_sample_ratio)
288
+ # shape (num_total_gts, h, w) -> (num_total_gts, num_points)
289
+ mask_point_targets = point_sample(
290
+ mask_targets.unsqueeze(1).float(), points_coords).squeeze(1)
291
+ # shape (num_queries, h, w) -> (num_queries, num_points)
292
+ mask_point_preds = point_sample(
293
+ mask_preds.unsqueeze(1), points_coords).squeeze(1)
294
+
295
+ # dice loss
296
+ loss_dice = self.loss_dice(
297
+ mask_point_preds, mask_point_targets, avg_factor=num_total_masks)
298
+
299
+ # mask loss
300
+ # shape (num_queries, num_points) -> (num_queries * num_points, )
301
+ mask_point_preds = mask_point_preds.reshape(-1)
302
+ # shape (num_total_gts, num_points) -> (num_total_gts * num_points, )
303
+ mask_point_targets = mask_point_targets.reshape(-1)
304
+ loss_mask = self.loss_mask(
305
+ mask_point_preds,
306
+ mask_point_targets,
307
+ avg_factor=num_total_masks * self.num_points)
308
+
309
+ return loss_cls, loss_mask, loss_dice
310
+
311
+ def get_targets(self, cls_scores_list, mask_preds_list, gt_labels_list,
312
+ gt_masks_list, img_metas):
313
+ """Compute classification and mask targets for all images for a decoder
314
+ layer.
315
+
316
+ Args:
317
+ cls_scores_list (list[Tensor]): Mask score logits from a single
318
+ decoder layer for all images. Each with shape (num_queries,
319
+ cls_out_channels).
320
+ mask_preds_list (list[Tensor]): Mask logits from a single decoder
321
+ layer for all images. Each with shape (num_queries, h, w).
322
+ gt_labels_list (list[Tensor]): Ground truth class indices for all
323
+ images. Each with shape (n, ), n is the sum of number of stuff
324
+ type and number of instance in a image.
325
+ gt_masks_list (list[Tensor]): Ground truth mask for each image,
326
+ each with shape (n, h, w).
327
+ img_metas (list[dict]): List of image meta information.
328
+
329
+ Returns:
330
+ tuple[list[Tensor]]: a tuple containing the following targets.
331
+ - labels_list (list[Tensor]): Labels of all images.\
332
+ Each with shape (num_queries, ).
333
+ - label_weights_list (list[Tensor]): Label weights\
334
+ of all images. Each with shape (num_queries, ).
335
+ - mask_targets_list (list[Tensor]): Mask targets of\
336
+ all images. Each with shape (num_queries, h, w).
337
+ - mask_weights_list (list[Tensor]): Mask weights of\
338
+ all images. Each with shape (num_queries, ).
339
+ - num_total_pos (int): Number of positive samples in\
340
+ all images.
341
+ - num_total_neg (int): Number of negative samples in\
342
+ all images.
343
+ """
344
+ (labels_list, label_weights_list, mask_targets_list, mask_weights_list,
345
+ pos_inds_list,
346
+ neg_inds_list) = multi_apply(self._get_target_single, cls_scores_list,
347
+ mask_preds_list, gt_labels_list,
348
+ gt_masks_list, img_metas)
349
+
350
+ num_total_pos = sum((inds.numel() for inds in pos_inds_list))
351
+ num_total_neg = sum((inds.numel() for inds in neg_inds_list))
352
+ return (labels_list, label_weights_list, mask_targets_list,
353
+ mask_weights_list, num_total_pos, num_total_neg)
354
+
355
+ def forward_head(self, decoder_out, mask_feature, attn_mask_target_size):
356
+ """Forward for head part which is called after every decoder layer.
357
+
358
+ Args:
359
+ decoder_out (Tensor): in shape (num_queries, batch_size, c).
360
+ mask_feature (Tensor): in shape (batch_size, c, h, w).
361
+ attn_mask_target_size (tuple[int, int]): target attention
362
+ mask size.
363
+
364
+ Returns:
365
+ tuple: A tuple contain three elements.
366
+
367
+ - cls_pred (Tensor): Classification scores in shape \
368
+ (batch_size, num_queries, cls_out_channels). \
369
+ Note `cls_out_channels` should includes background.
370
+ - mask_pred (Tensor): Mask scores in shape \
371
+ (batch_size, num_queries,h, w).
372
+ - attn_mask (Tensor): Attention mask in shape \
373
+ (batch_size * num_heads, num_queries, h, w).
374
+ """
375
+ decoder_out = self.transformer_decoder.post_norm(decoder_out)
376
+ decoder_out = decoder_out.transpose(0, 1)
377
+ # shape (num_queries, batch_size, c)
378
+ cls_pred = self.cls_embed(decoder_out)
379
+ # shape (num_queries, batch_size, c)
380
+ mask_embed = self.mask_embed(decoder_out)
381
+ # shape (num_queries, batch_size, h, w)
382
+ mask_pred = torch.einsum('bqc,bchw->bqhw', mask_embed, mask_feature)
383
+ attn_mask = F.interpolate(
384
+ mask_pred,
385
+ attn_mask_target_size,
386
+ mode='bilinear',
387
+ align_corners=False)
388
+ # shape (num_queries, batch_size, h, w) ->
389
+ # (batch_size * num_head, num_queries, h, w)
390
+ attn_mask = attn_mask.flatten(2).unsqueeze(1).repeat(
391
+ (1, self.num_heads, 1, 1)).flatten(0, 1)
392
+ attn_mask = attn_mask.sigmoid() < 0.5
393
+ attn_mask = attn_mask.detach()
394
+
395
+ return cls_pred, mask_pred, attn_mask
396
+
397
+ def forward(self, feats, img_metas):
398
+ """Forward function.
399
+
400
+ Args:
401
+ feats (list[Tensor]): Multi scale Features from the
402
+ upstream network, each is a 4D-tensor.
403
+ img_metas (list[dict]): List of image information.
404
+
405
+ Returns:
406
+ tuple: A tuple contains two elements.
407
+
408
+ - cls_pred_list (list[Tensor)]: Classification logits \
409
+ for each decoder layer. Each is a 3D-tensor with shape \
410
+ (batch_size, num_queries, cls_out_channels). \
411
+ Note `cls_out_channels` should includes background.
412
+ - mask_pred_list (list[Tensor]): Mask logits for each \
413
+ decoder layer. Each with shape (batch_size, num_queries, \
414
+ h, w).
415
+ """
416
+ batch_size = len(img_metas)
417
+ mask_features, multi_scale_memorys = self.pixel_decoder(feats)
418
+ # multi_scale_memorys (from low resolution to high resolution)
419
+ decoder_inputs = []
420
+ decoder_positional_encodings = []
421
+ for i in range(self.num_transformer_feat_level):
422
+ decoder_input = self.decoder_input_projs[i](multi_scale_memorys[i])
423
+ # shape (batch_size, c, h, w) -> (h*w, batch_size, c)
424
+ decoder_input = decoder_input.flatten(2).permute(2, 0, 1)
425
+ level_embed = self.level_embed.weight[i].view(1, 1, -1)
426
+ decoder_input = decoder_input + level_embed
427
+ # shape (batch_size, c, h, w) -> (h*w, batch_size, c)
428
+ mask = decoder_input.new_zeros(
429
+ (batch_size, ) + multi_scale_memorys[i].shape[-2:],
430
+ dtype=torch.bool)
431
+ decoder_positional_encoding = self.decoder_positional_encoding(
432
+ mask)
433
+ decoder_positional_encoding = decoder_positional_encoding.flatten(
434
+ 2).permute(2, 0, 1)
435
+ decoder_inputs.append(decoder_input)
436
+ decoder_positional_encodings.append(decoder_positional_encoding)
437
+ # shape (num_queries, c) -> (num_queries, batch_size, c)
438
+ query_feat = self.query_feat.weight.unsqueeze(1).repeat(
439
+ (1, batch_size, 1))
440
+ query_embed = self.query_embed.weight.unsqueeze(1).repeat(
441
+ (1, batch_size, 1))
442
+
443
+ cls_pred_list = []
444
+ mask_pred_list = []
445
+ cls_pred, mask_pred, attn_mask = self.forward_head(
446
+ query_feat, mask_features, multi_scale_memorys[0].shape[-2:])
447
+ cls_pred_list.append(cls_pred)
448
+ mask_pred_list.append(mask_pred)
449
+
450
+ for i in range(self.num_transformer_decoder_layers):
451
+ level_idx = i % self.num_transformer_feat_level
452
+ # if a mask is all True(all background), then set it all False.
453
+ attn_mask[torch.where(
454
+ attn_mask.sum(-1) == attn_mask.shape[-1])] = False
455
+
456
+ # cross_attn + self_attn
457
+ layer = self.transformer_decoder.layers[i]
458
+ attn_masks = [attn_mask, None]
459
+ query_feat = layer(
460
+ query=query_feat,
461
+ key=decoder_inputs[level_idx],
462
+ value=decoder_inputs[level_idx],
463
+ query_pos=query_embed,
464
+ key_pos=decoder_positional_encodings[level_idx],
465
+ attn_masks=attn_masks,
466
+ query_key_padding_mask=None,
467
+ # here we do not apply masking on padded region
468
+ key_padding_mask=None)
469
+ cls_pred, mask_pred, attn_mask = self.forward_head(
470
+ query_feat, mask_features, multi_scale_memorys[
471
+ (i + 1) % self.num_transformer_feat_level].shape[-2:])
472
+
473
+ cls_pred_list.append(cls_pred)
474
+ mask_pred_list.append(mask_pred)
475
+
476
+ return cls_pred_list, mask_pred_list
477
+
478
+ def forward_train(self,
479
+ feats,
480
+ img_metas,
481
+ gt_bboxes,
482
+ gt_labels,
483
+ gt_masks,
484
+ gt_semantic_seg,
485
+ gt_bboxes_ignore=None):
486
+ """Forward function for training mode.
487
+
488
+ Args:
489
+ feats (list[Tensor]): Multi-level features from the upstream
490
+ network, each is a 4D-tensor.
491
+ img_metas (list[Dict]): List of image information.
492
+ gt_bboxes (list[Tensor]): Each element is ground truth bboxes of
493
+ the image, shape (num_gts, 4). Not used here.
494
+ gt_labels (list[Tensor]): Each element is ground truth labels of
495
+ each box, shape (num_gts,).
496
+ gt_masks (list[BitmapMasks]): Each element is masks of instances
497
+ of a image, shape (num_gts, h, w).
498
+ gt_semantic_seg (list[tensor] | None): Each element is the ground
499
+ truth of semantic segmentation with the shape (N, H, W).
500
+ [0, num_thing_class - 1] means things,
501
+ [num_thing_class, num_class-1] means stuff,
502
+ 255 means VOID. It's None when training instance segmentation.
503
+ gt_bboxes_ignore (list[Tensor]): Ground truth bboxes to be
504
+ ignored. Defaults to None.
505
+
506
+ Returns:
507
+ dict[str, Tensor]: a dictionary of loss components
508
+ """
509
+ # not consider ignoring bboxes
510
+ assert gt_bboxes_ignore is None
511
+
512
+ # forward
513
+ all_cls_scores, all_mask_preds = self(feats, img_metas)
514
+
515
+ # preprocess ground truth
516
+ gt_labels, gt_masks = self.preprocess_gt(gt_labels, gt_masks,
517
+ gt_semantic_seg, img_metas)
518
+
519
+ # loss
520
+ losses = self.loss(all_cls_scores, all_mask_preds, gt_labels, gt_masks,
521
+ gt_semantic_seg, img_metas)
522
+
523
+ return losses
524
+
525
+ @force_fp32(apply_to=('all_cls_scores', 'all_mask_preds'))
526
+ def loss(self, all_cls_scores, all_mask_preds, gt_labels_list,
527
+ gt_masks_list, gt_semantic_seg, img_metas):
528
+ """Loss function.
529
+
530
+ Args:
531
+ all_cls_scores (Tensor): Classification scores for all decoder
532
+ layers with shape (num_decoder, batch_size, num_queries,
533
+ cls_out_channels). Note `cls_out_channels` should includes
534
+ background.
535
+ all_mask_preds (Tensor): Mask scores for all decoder layers with
536
+ shape (num_decoder, batch_size, num_queries, h, w).
537
+ gt_labels_list (list[Tensor]): Ground truth class indices for each
538
+ image with shape (n, ). n is the sum of number of stuff type
539
+ and number of instance in a image.
540
+ gt_masks_list (list[Tensor]): Ground truth mask for each image with
541
+ shape (n, h, w).
542
+ img_metas (list[dict]): List of image meta information.
543
+
544
+ Returns:
545
+ dict[str, Tensor]: A dictionary of loss components.
546
+ """
547
+
548
+ num_dec_layers = len(all_cls_scores)
549
+ stuff_gt_labels = []
550
+ stuff_gt_masks = []
551
+ thing_gt_labels = []
552
+ thing_gt_masks = []
553
+
554
+ for gt_labels, gt_masks in zip(gt_labels_list, gt_masks_list):
555
+ num_stuff = sum(torch.unique(gt_labels) >= self.num_things_classes)
556
+ stuff_gt_labels.append(gt_labels[-num_stuff:])
557
+ stuff_gt_masks.append(gt_masks[-num_stuff:])
558
+ thing_gt_labels.append(gt_labels[:-num_stuff])
559
+ thing_gt_masks.append(gt_masks[:-num_stuff])
560
+
561
+ stuff_gt_labels_list = [stuff_gt_labels for _ in range(num_dec_layers)]
562
+ stuff_gt_masks_list = [stuff_gt_masks for _ in range(num_dec_layers)]
563
+
564
+ thing_gt_labels_list = [thing_gt_labels for _ in range(num_dec_layers)]
565
+ thing_gt_masks_list = [thing_gt_masks for _ in range(num_dec_layers)]
566
+
567
+ stuff_scores = [all_cls_score[:, -self.num_stuff_classes:, :] for all_cls_score in all_cls_scores]
568
+ stuff_mask_preds = [all_mask_pred[:, -self.num_stuff_classes:, :, :] for all_mask_pred in all_mask_preds ]
569
+
570
+ thing_scores = [all_cls_score[:, :-self.num_stuff_classes, :] for all_cls_score in all_cls_scores]
571
+ thing_mask_preds = [all_mask_pred[:, :-self.num_stuff_classes, :, :] for all_mask_pred in all_mask_preds]
572
+
573
+ img_metas_list = [img_metas for _ in range(num_dec_layers)]
574
+
575
+ losses_cls_stuff, losses_mask_stuff, losses_dice_stuff = multi_apply(
576
+ self.loss_single, stuff_scores, stuff_mask_preds,
577
+ stuff_gt_labels_list, stuff_gt_masks_list, img_metas_list)
578
+
579
+ losses_cls_thing, losses_mask_thing, losses_dice_thing = multi_apply(
580
+ self.loss_single, thing_scores, thing_mask_preds,
581
+ thing_gt_labels_list, thing_gt_masks_list, img_metas_list)
582
+
583
+ loss_dict = dict()
584
+
585
+ # loss from the last decoder layer
586
+ loss_dict['loss_cls'] = losses_cls_stuff[-1] + losses_cls_thing[-1]
587
+ loss_dict['loss_mask'] = losses_mask_stuff[-1] + losses_mask_thing[-1]
588
+ loss_dict['loss_dice'] = losses_dice_stuff[-1] + losses_dice_thing[-1]
589
+
590
+ # loss from other decoder layers stuff
591
+ num_dec_layer = 0
592
+ for loss_cls_i, loss_mask_i, loss_dice_i in zip(
593
+ losses_cls_stuff[:-1],
594
+ losses_mask_stuff[:-1],
595
+ losses_dice_stuff[:-1]):
596
+
597
+ loss_dict[f'd{num_dec_layer}.stuff_loss_cls'] = loss_cls_i
598
+ loss_dict[f'd{num_dec_layer}.stuff_loss_mask'] = loss_mask_i
599
+ loss_dict[f'd{num_dec_layer}.stuff_loss_dice'] = loss_dice_i
600
+ num_dec_layer += 1
601
+
602
+ # loss from other decoder layers thing
603
+ num_dec_layer = 0
604
+ for loss_cls_i, loss_mask_i, loss_dice_i in zip(
605
+ losses_mask_thing[:-1],
606
+ losses_mask_thing[:-1],
607
+ losses_mask_thing[:-1]):
608
+ loss_dict[f'd{num_dec_layer}.thing_loss_cls'] = loss_cls_i
609
+ loss_dict[f'd{num_dec_layer}.thing_loss_mask'] = loss_mask_i
610
+ loss_dict[f'd{num_dec_layer}.thing_loss_dice'] = loss_dice_i
611
+ num_dec_layer += 1
612
+
613
+ return loss_dict
OpenPVSG/models/mask2former/mask2former_head_split_focal.py ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import copy
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from mmcv.cnn import Conv2d, build_plugin_layer, caffe2_xavier_init
8
+ from mmcv.cnn.bricks.transformer import (build_positional_encoding,
9
+ build_transformer_layer_sequence)
10
+ from mmcv.ops import point_sample
11
+ from mmcv.runner import ModuleList, force_fp32
12
+
13
+ from mmdet.core import build_assigner, build_sampler, reduce_mean, multi_apply
14
+ from mmdet.models.utils import get_uncertain_point_coords_with_randomness
15
+ from mmdet.models.builder import HEADS, build_loss
16
+ from mmdet.models.dense_heads.anchor_free_head import AnchorFreeHead
17
+ from mmdet.models.dense_heads.maskformer_head import MaskFormerHead
18
+
19
+
20
+ @HEADS.register_module()
21
+ class Mask2FormerHeadSplitFocal(MaskFormerHead):
22
+ """Implements the Mask2Former head.
23
+
24
+ See `Masked-attention Mask Transformer for Universal Image
25
+ Segmentation <https://arxiv.org/pdf/2112.01527>`_ for details.
26
+
27
+ Args:
28
+ in_channels (list[int]): Number of channels in the input feature map.
29
+ feat_channels (int): Number of channels for features.
30
+ out_channels (int): Number of channels for output.
31
+ num_things_classes (int): Number of things.
32
+ num_stuff_classes (int): Number of stuff.
33
+ num_queries (int): Number of query in Transformer decoder.
34
+ pixel_decoder (:obj:`mmcv.ConfigDict` | dict): Config for pixel
35
+ decoder. Defaults to None.
36
+ enforce_decoder_input_project (bool, optional): Whether to add
37
+ a layer to change the embed_dim of tranformer encoder in
38
+ pixel decoder to the embed_dim of transformer decoder.
39
+ Defaults to False.
40
+ transformer_decoder (:obj:`mmcv.ConfigDict` | dict): Config for
41
+ transformer decoder. Defaults to None.
42
+ positional_encoding (:obj:`mmcv.ConfigDict` | dict): Config for
43
+ transformer decoder position encoding. Defaults to None.
44
+ loss_cls (:obj:`mmcv.ConfigDict` | dict): Config of the classification
45
+ loss. Defaults to None.
46
+ loss_mask (:obj:`mmcv.ConfigDict` | dict): Config of the mask loss.
47
+ Defaults to None.
48
+ loss_dice (:obj:`mmcv.ConfigDict` | dict): Config of the dice loss.
49
+ Defaults to None.
50
+ train_cfg (:obj:`mmcv.ConfigDict` | dict): Training config of
51
+ Mask2Former head.
52
+ test_cfg (:obj:`mmcv.ConfigDict` | dict): Testing config of
53
+ Mask2Former head.
54
+ init_cfg (dict or list[dict], optional): Initialization config dict.
55
+ Defaults to None.
56
+ """
57
+
58
+ def __init__(self,
59
+ in_channels,
60
+ feat_channels,
61
+ out_channels,
62
+ num_things_classes=80,
63
+ num_stuff_classes=53,
64
+ num_queries=100,
65
+ num_transformer_feat_level=3,
66
+ pixel_decoder=None,
67
+ enforce_decoder_input_project=False,
68
+ transformer_decoder=None,
69
+ positional_encoding=None,
70
+ thing_class_weight=None,
71
+ stuff_class_weight=None,
72
+ loss_cls=None,
73
+ loss_mask=None,
74
+ loss_dice=None,
75
+ train_cfg=None,
76
+ test_cfg=None,
77
+ init_cfg=None,
78
+ **kwargs):
79
+ super(AnchorFreeHead, self).__init__(init_cfg)
80
+ self.num_things_classes = num_things_classes
81
+ self.num_stuff_classes = num_stuff_classes
82
+ self.num_classes = self.num_things_classes + self.num_stuff_classes
83
+ self.num_queries = num_queries
84
+ self.num_transformer_feat_level = num_transformer_feat_level
85
+ self.num_heads = transformer_decoder.transformerlayers.\
86
+ attn_cfgs.num_heads
87
+ self.num_transformer_decoder_layers = transformer_decoder.num_layers
88
+ assert pixel_decoder.encoder.transformerlayers.\
89
+ attn_cfgs.num_levels == num_transformer_feat_level
90
+ pixel_decoder_ = copy.deepcopy(pixel_decoder)
91
+ pixel_decoder_.update(
92
+ in_channels=in_channels,
93
+ feat_channels=feat_channels,
94
+ out_channels=out_channels)
95
+ self.pixel_decoder = build_plugin_layer(pixel_decoder_)[1]
96
+ self.transformer_decoder = build_transformer_layer_sequence(
97
+ transformer_decoder)
98
+ self.decoder_embed_dims = self.transformer_decoder.embed_dims
99
+
100
+ self.decoder_input_projs = ModuleList()
101
+ # from low resolution to high resolution
102
+ for _ in range(num_transformer_feat_level):
103
+ if (self.decoder_embed_dims != feat_channels
104
+ or enforce_decoder_input_project):
105
+ self.decoder_input_projs.append(
106
+ Conv2d(
107
+ feat_channels, self.decoder_embed_dims, kernel_size=1))
108
+ else:
109
+ self.decoder_input_projs.append(nn.Identity())
110
+ self.decoder_positional_encoding = build_positional_encoding(
111
+ positional_encoding)
112
+ self.query_embed = nn.Embedding(self.num_queries, feat_channels)
113
+ self.query_feat = nn.Embedding(self.num_queries, feat_channels)
114
+ # from low resolution to high resolution
115
+ self.level_embed = nn.Embedding(self.num_transformer_feat_level,
116
+ feat_channels)
117
+ # cls embed output
118
+ self.thing_embed = nn.Linear(feat_channels, self.num_things_classes)
119
+ self.stuff_embed = nn.Linear(feat_channels, self.num_stuff_classes)
120
+
121
+ self.mask_embed = nn.Sequential(
122
+ nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
123
+ nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
124
+ nn.Linear(feat_channels, out_channels))
125
+
126
+ self.test_cfg = test_cfg
127
+ self.train_cfg = train_cfg
128
+
129
+ if train_cfg:
130
+ self.assigner = build_assigner(self.train_cfg.assigner)
131
+ self.sampler = build_sampler(self.train_cfg.sampler, context=self)
132
+ self.num_points = self.train_cfg.get('num_points', 12544)
133
+ self.oversample_ratio = self.train_cfg.get('oversample_ratio', 3.0)
134
+ self.importance_sample_ratio = self.train_cfg.get(
135
+ 'importance_sample_ratio', 0.75)
136
+
137
+ self.thing_class_weight = thing_class_weight
138
+ self.stuff_class_weight = stuff_class_weight
139
+
140
+ self.loss_cls = build_loss(loss_cls)
141
+ self.loss_mask = build_loss(loss_mask)
142
+ self.loss_dice = build_loss(loss_dice)
143
+
144
+ def init_weights(self):
145
+ for m in self.decoder_input_projs:
146
+ if isinstance(m, Conv2d):
147
+ caffe2_xavier_init(m, bias=0)
148
+
149
+ self.pixel_decoder.init_weights()
150
+
151
+ for p in self.transformer_decoder.parameters():
152
+ if p.dim() > 1:
153
+ nn.init.xavier_normal_(p)
154
+
155
+ def _get_target_single(self, cls_score, mask_pred, gt_labels, gt_masks,
156
+ img_metas):
157
+ """Compute classification and mask targets for one image.
158
+
159
+ Args:
160
+ cls_score (Tensor): Mask score logits from a single decoder layer
161
+ for one image. Shape (num_queries, cls_out_channels).
162
+ mask_pred (Tensor): Mask logits for a single decoder layer for one
163
+ image. Shape (num_queries, h, w).
164
+ gt_labels (Tensor): Ground truth class indices for one image with
165
+ shape (num_gts, ).
166
+ gt_masks (Tensor): Ground truth mask for each image, each with
167
+ shape (num_gts, h, w).
168
+ img_metas (dict): Image information.
169
+
170
+ Returns:
171
+ tuple[Tensor]: A tuple containing the following for one image.
172
+
173
+ - labels (Tensor): Labels of each image. \
174
+ shape (num_queries, ).
175
+ - label_weights (Tensor): Label weights of each image. \
176
+ shape (num_queries, ).
177
+ - mask_targets (Tensor): Mask targets of each image. \
178
+ shape (num_queries, h, w).
179
+ - mask_weights (Tensor): Mask weights of each image. \
180
+ shape (num_queries, ).
181
+ - pos_inds (Tensor): Sampled positive indices for each \
182
+ image.
183
+ - neg_inds (Tensor): Sampled negative indices for each \
184
+ image.
185
+ """
186
+
187
+ # sample points
188
+ num_queries = cls_score.shape[0]
189
+ num_gts = gt_labels.shape[0]
190
+
191
+ point_coords = torch.rand((1, self.num_points, 2),
192
+ device=cls_score.device)
193
+
194
+ # shape (num_queries, num_points)
195
+ mask_points_pred = point_sample(
196
+ mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1,
197
+ 1)).squeeze(1)
198
+ # shape (num_gts, num_points)
199
+ gt_points_masks = point_sample(
200
+ gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1,
201
+ 1)).squeeze(1)
202
+
203
+ # assign and sample
204
+ assign_result = self.assigner.assign(cls_score, mask_points_pred,
205
+ gt_labels, gt_points_masks,
206
+ img_metas)
207
+ sampling_result = self.sampler.sample(assign_result, mask_pred,
208
+ gt_masks)
209
+ pos_inds = sampling_result.pos_inds
210
+ neg_inds = sampling_result.neg_inds
211
+
212
+ if num_queries > self.num_stuff_classes:
213
+ label_default = self.num_things_classes
214
+ else:
215
+ label_default = self.num_stuff_classes
216
+
217
+ # label target (thing or stuff labels)
218
+ labels = gt_labels.new_full((num_queries, ),
219
+ label_default,
220
+ dtype=torch.long)
221
+
222
+ labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds]
223
+ label_weights = gt_labels.new_ones((num_queries, ))
224
+
225
+ # mask target
226
+ mask_targets = gt_masks[sampling_result.pos_assigned_gt_inds]
227
+ mask_weights = mask_pred.new_zeros((num_queries, ))
228
+ mask_weights[pos_inds] = 1.0
229
+
230
+ return (labels, label_weights, mask_targets, mask_weights, pos_inds,
231
+ neg_inds)
232
+
233
+ def loss_single(self, cls_scores, mask_preds, gt_labels_list,
234
+ gt_masks_list, img_metas, is_thing_list):
235
+ """Loss function for outputs from a single decoder layer.
236
+
237
+ Args:
238
+ cls_scores (Tensor): Mask score logits from a single decoder layer
239
+ for all images. Shape (batch_size, num_queries,
240
+ cls_out_channels). Note `cls_out_channels` should includes
241
+ background.
242
+ mask_preds (Tensor): Mask logits for a pixel decoder for all
243
+ images. Shape (batch_size, num_queries, h, w).
244
+ gt_labels_list (list[Tensor]): Ground truth class indices for each
245
+ image, each with shape (num_gts, ).
246
+ gt_masks_list (list[Tensor]): Ground truth mask for each image,
247
+ each with shape (num_gts, h, w).
248
+ img_metas (list[dict]): List of image meta information.
249
+
250
+ Returns:
251
+ tuple[Tensor]: Loss components for outputs from a single \
252
+ decoder layer.
253
+ """
254
+ num_imgs = cls_scores.size(0)
255
+ cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
256
+ mask_preds_list = [mask_preds[i] for i in range(num_imgs)]
257
+ (labels_list, label_weights_list, mask_targets_list, mask_weights_list,
258
+ num_total_pos,
259
+ num_total_neg) = self.get_targets(cls_scores_list, mask_preds_list,
260
+ gt_labels_list, gt_masks_list,
261
+ img_metas)
262
+
263
+ # shape (batch_size, num_queries)
264
+ labels = torch.stack(labels_list, dim=0)
265
+ # shape (batch_size, num_queries)
266
+ label_weights = torch.stack(label_weights_list, dim=0)
267
+ # shape (num_total_gts, h, w)
268
+ mask_targets = torch.cat(mask_targets_list, dim=0)
269
+ # shape (batch_size, num_queries)
270
+ mask_weights = torch.stack(mask_weights_list, dim=0)
271
+
272
+ # classification loss
273
+ # shape (batch_size * num_queries, )
274
+ cls_scores = cls_scores.flatten(0, 1)
275
+ labels = labels.flatten(0, 1)
276
+ label_weights = label_weights.flatten(0, 1)
277
+
278
+ # class_weight = cls_scores.new_tensor(self.class_weight)
279
+ if is_thing_list:
280
+ class_weight = cls_scores.new_tensor(self.thing_class_weight)
281
+ else:
282
+ class_weight = cls_scores.new_tensor(self.stuff_class_weight)
283
+
284
+ loss_cls = self.loss_cls(
285
+ cls_scores,
286
+ labels,
287
+ label_weights,
288
+ avg_factor=class_weight[labels].sum()
289
+ )
290
+
291
+ num_total_masks = reduce_mean(cls_scores.new_tensor([num_total_pos]))
292
+ num_total_masks = max(num_total_masks, 1)
293
+
294
+ # extract positive ones
295
+ # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w)
296
+ mask_preds = mask_preds[mask_weights > 0]
297
+
298
+ if mask_targets.shape[0] == 0:
299
+ # zero match
300
+ loss_dice = mask_preds.sum()
301
+ loss_mask = mask_preds.sum()
302
+ return loss_cls, loss_mask, loss_dice
303
+
304
+ with torch.no_grad():
305
+ points_coords = get_uncertain_point_coords_with_randomness(
306
+ mask_preds.unsqueeze(1), None, self.num_points,
307
+ self.oversample_ratio, self.importance_sample_ratio)
308
+ # shape (num_total_gts, h, w) -> (num_total_gts, num_points)
309
+ mask_point_targets = point_sample(
310
+ mask_targets.unsqueeze(1).float(), points_coords).squeeze(1)
311
+ # shape (num_queries, h, w) -> (num_queries, num_points)
312
+ mask_point_preds = point_sample(
313
+ mask_preds.unsqueeze(1), points_coords).squeeze(1)
314
+
315
+ # dice loss
316
+ loss_dice = self.loss_dice(
317
+ mask_point_preds, mask_point_targets, avg_factor=num_total_masks)
318
+
319
+ # mask loss
320
+ # shape (num_queries, num_points) -> (num_queries * num_points, )
321
+ mask_point_preds = mask_point_preds.reshape(-1)
322
+ # shape (num_total_gts, num_points) -> (num_total_gts * num_points, )
323
+ mask_point_targets = mask_point_targets.reshape(-1)
324
+ loss_mask = self.loss_mask(
325
+ mask_point_preds,
326
+ mask_point_targets,
327
+ avg_factor=num_total_masks * self.num_points)
328
+
329
+ return loss_cls, loss_mask, loss_dice
330
+
331
+ def get_targets(self, cls_scores_list, mask_preds_list, gt_labels_list,
332
+ gt_masks_list, img_metas):
333
+ """Compute classification and mask targets for all images for a decoder
334
+ layer.
335
+
336
+ Args:
337
+ cls_scores_list (list[Tensor]): Mask score logits from a single
338
+ decoder layer for all images. Each with shape (num_queries,
339
+ cls_out_channels).
340
+ mask_preds_list (list[Tensor]): Mask logits from a single decoder
341
+ layer for all images. Each with shape (num_queries, h, w).
342
+ gt_labels_list (list[Tensor]): Ground truth class indices for all
343
+ images. Each with shape (n, ), n is the sum of number of stuff
344
+ type and number of instance in a image.
345
+ gt_masks_list (list[Tensor]): Ground truth mask for each image,
346
+ each with shape (n, h, w).
347
+ img_metas (list[dict]): List of image meta information.
348
+
349
+ Returns:
350
+ tuple[list[Tensor]]: a tuple containing the following targets.
351
+ - labels_list (list[Tensor]): Labels of all images.\
352
+ Each with shape (num_queries, ).
353
+ - label_weights_list (list[Tensor]): Label weights\
354
+ of all images. Each with shape (num_queries, ).
355
+ - mask_targets_list (list[Tensor]): Mask targets of\
356
+ all images. Each with shape (num_queries, h, w).
357
+ - mask_weights_list (list[Tensor]): Mask weights of\
358
+ all images. Each with shape (num_queries, ).
359
+ - num_total_pos (int): Number of positive samples in\
360
+ all images.
361
+ - num_total_neg (int): Number of negative samples in\
362
+ all images.
363
+ """
364
+ (labels_list, label_weights_list, mask_targets_list, mask_weights_list,
365
+ pos_inds_list,
366
+ neg_inds_list) = multi_apply(self._get_target_single, cls_scores_list,
367
+ mask_preds_list, gt_labels_list,
368
+ gt_masks_list, img_metas)
369
+
370
+ num_total_pos = sum((inds.numel() for inds in pos_inds_list))
371
+ num_total_neg = sum((inds.numel() for inds in neg_inds_list))
372
+ return (labels_list, label_weights_list, mask_targets_list,
373
+ mask_weights_list, num_total_pos, num_total_neg)
374
+
375
+ def forward_head(self, decoder_out, mask_feature, attn_mask_target_size):
376
+ """Forward for head part which is called after every decoder layer.
377
+
378
+ Args:
379
+ decoder_out (Tensor): in shape (num_queries, batch_size, c).
380
+ mask_feature (Tensor): in shape (batch_size, c, h, w).
381
+ attn_mask_target_size (tuple[int, int]): target attention
382
+ mask size.
383
+
384
+ Returns:
385
+ tuple: A tuple contain three elements.
386
+
387
+ - cls_pred (Tensor): Classification scores in shape \
388
+ (batch_size, num_queries, cls_out_channels). \
389
+ Note `cls_out_channels` should includes background.
390
+ - mask_pred (Tensor): Mask scores in shape \
391
+ (batch_size, num_queries,h, w).
392
+ - attn_mask (Tensor): Attention mask in shape \
393
+ (batch_size * num_heads, num_queries, h, w).
394
+ """
395
+ decoder_out = self.transformer_decoder.post_norm(decoder_out)
396
+ decoder_out = decoder_out.transpose(0, 1)
397
+ # shape (num_queries, batch_size, c) -> (b, n, c)
398
+ # cls_pred = self.cls_embed(decoder_out)
399
+
400
+ th_cls_pred = self.thing_embed(decoder_out[:, :-self.num_stuff_classes])
401
+ st_cls_pred = self.stuff_embed(decoder_out[:, -self.num_stuff_classes:])
402
+
403
+ # (N_{th}, b, c_{th}) (N_{st}, b, c_{stuff})
404
+ cls_pred = [th_cls_pred, st_cls_pred]
405
+
406
+ # shape (num_queries, batch_size, c)
407
+ mask_embed = self.mask_embed(decoder_out)
408
+
409
+ # shape (num_queries, batch_size, h, w)
410
+ mask_pred = torch.einsum('bqc,bchw -> bqhw', mask_embed, mask_feature)
411
+ attn_mask = F.interpolate(
412
+ mask_pred,
413
+ attn_mask_target_size,
414
+ mode='bilinear',
415
+ align_corners=False)
416
+
417
+ # shape (num_queries, batch_size, h, w) ->
418
+ # (batch_size * num_head, num_queries, h, w)
419
+ attn_mask = attn_mask.flatten(2).unsqueeze(1).repeat(
420
+ (1, self.num_heads, 1, 1)).flatten(0, 1)
421
+ attn_mask = attn_mask.sigmoid() < 0.5
422
+
423
+ attn_mask = attn_mask.detach()
424
+
425
+ return cls_pred, mask_pred, attn_mask
426
+
427
+ def forward(self, feats, img_metas):
428
+ """Forward function.
429
+
430
+ Args:
431
+ feats (list[Tensor]): Multi scale Features from the
432
+ upstream network, each is a 4D-tensor.
433
+ img_metas (list[dict]): List of image information.
434
+
435
+ Returns:
436
+ tuple: A tuple contains two elements.
437
+
438
+ - cls_pred_list (list[Tensor)]: Classification logits \
439
+ for each decoder layer. Each is a 3D-tensor with shape \
440
+ (batch_size, num_queries, cls_out_channels). \
441
+ Note `cls_out_channels` should includes background.
442
+ - mask_pred_list (list[Tensor]): Mask logits for each \
443
+ decoder layer. Each with shape (batch_size, num_queries, \
444
+ h, w).
445
+ """
446
+ batch_size = len(img_metas)
447
+ mask_features, multi_scale_memorys = self.pixel_decoder(feats)
448
+ # multi_scale_memorys (from low resolution to high resolution)
449
+ decoder_inputs = []
450
+ decoder_positional_encodings = []
451
+ for i in range(self.num_transformer_feat_level):
452
+ decoder_input = self.decoder_input_projs[i](multi_scale_memorys[i])
453
+ # shape (batch_size, c, h, w) -> (h*w, batch_size, c)
454
+ decoder_input = decoder_input.flatten(2).permute(2, 0, 1)
455
+ level_embed = self.level_embed.weight[i].view(1, 1, -1)
456
+ decoder_input = decoder_input + level_embed
457
+ # shape (batch_size, c, h, w) -> (h*w, batch_size, c)
458
+ mask = decoder_input.new_zeros(
459
+ (batch_size, ) + multi_scale_memorys[i].shape[-2:],
460
+ dtype=torch.bool)
461
+ decoder_positional_encoding = self.decoder_positional_encoding(
462
+ mask)
463
+ decoder_positional_encoding = decoder_positional_encoding.flatten(
464
+ 2).permute(2, 0, 1)
465
+ decoder_inputs.append(decoder_input)
466
+ decoder_positional_encodings.append(decoder_positional_encoding)
467
+ # shape (num_queries, c) -> (num_queries, batch_size, c)
468
+ query_feat = self.query_feat.weight.unsqueeze(1).repeat(
469
+ (1, batch_size, 1))
470
+ query_embed = self.query_embed.weight.unsqueeze(1).repeat(
471
+ (1, batch_size, 1))
472
+
473
+ cls_pred_list = []
474
+ mask_pred_list = []
475
+ cls_pred, mask_pred, attn_mask = self.forward_head(
476
+ query_feat, mask_features, multi_scale_memorys[0].shape[-2:])
477
+ cls_pred_list.append(cls_pred)
478
+ mask_pred_list.append(mask_pred)
479
+
480
+ for i in range(self.num_transformer_decoder_layers):
481
+ level_idx = i % self.num_transformer_feat_level
482
+ # if a mask is all True(all background), then set it all False.
483
+ attn_mask[torch.where(
484
+ attn_mask.sum(-1) == attn_mask.shape[-1])] = False
485
+
486
+ # cross_attn + self_attn
487
+ layer = self.transformer_decoder.layers[i]
488
+ attn_masks = [attn_mask, None]
489
+ query_feat = layer(
490
+ query=query_feat,
491
+ key=decoder_inputs[level_idx],
492
+ value=decoder_inputs[level_idx],
493
+ query_pos=query_embed,
494
+ key_pos=decoder_positional_encodings[level_idx],
495
+ attn_masks=attn_masks,
496
+ query_key_padding_mask=None,
497
+ # here we do not apply masking on padded region
498
+ key_padding_mask=None)
499
+ cls_pred, mask_pred, attn_mask = self.forward_head(
500
+ query_feat, mask_features, multi_scale_memorys[
501
+ (i + 1) % self.num_transformer_feat_level].shape[-2:])
502
+
503
+ cls_pred_list.append(cls_pred)
504
+ mask_pred_list.append(mask_pred)
505
+
506
+ return cls_pred_list, mask_pred_list
507
+
508
+ def forward_train(self,
509
+ feats,
510
+ img_metas,
511
+ gt_bboxes,
512
+ gt_labels,
513
+ gt_masks,
514
+ gt_semantic_seg,
515
+ gt_bboxes_ignore=None):
516
+ """Forward function for training mode.
517
+
518
+ Args:
519
+ feats (list[Tensor]): Multi-level features from the upstream
520
+ network, each is a 4D-tensor.
521
+ img_metas (list[Dict]): List of image information.
522
+ gt_bboxes (list[Tensor]): Each element is ground truth bboxes of
523
+ the image, shape (num_gts, 4). Not used here.
524
+ gt_labels (list[Tensor]): Each element is ground truth labels of
525
+ each box, shape (num_gts,).
526
+ gt_masks (list[BitmapMasks]): Each element is masks of instances
527
+ of a image, shape (num_gts, h, w).
528
+ gt_semantic_seg (list[tensor] | None): Each element is the ground
529
+ truth of semantic segmentation with the shape (N, H, W).
530
+ [0, num_thing_class - 1] means things,
531
+ [num_thing_class, num_class-1] means stuff,
532
+ 255 means VOID. It's None when training instance segmentation.
533
+ gt_bboxes_ignore (list[Tensor]): Ground truth bboxes to be
534
+ ignored. Defaults to None.
535
+
536
+ Returns:
537
+ dict[str, Tensor]: a dictionary of loss components
538
+ """
539
+ # not consider ignoring bboxes
540
+ assert gt_bboxes_ignore is None
541
+
542
+ # forward
543
+ all_cls_scores, all_mask_preds = self(feats, img_metas)
544
+
545
+ # preprocess ground truth
546
+ gt_labels, gt_masks = self.preprocess_gt(gt_labels, gt_masks,
547
+ gt_semantic_seg, img_metas)
548
+
549
+ # loss
550
+ losses = self.loss(all_cls_scores, all_mask_preds, gt_labels, gt_masks,
551
+ gt_semantic_seg, img_metas)
552
+
553
+ return losses
554
+
555
+ @force_fp32(apply_to=('all_cls_scores', 'all_mask_preds'))
556
+ def loss(self, all_cls_scores, all_mask_preds, gt_labels_list,
557
+ gt_masks_list, gt_semantic_seg, img_metas):
558
+ """Loss function.
559
+
560
+ Args:
561
+ all_cls_scores (Tensor): Classification scores for all decoder
562
+ layers with shape (num_decoder, batch_size, num_queries,
563
+ cls_out_channels). Note `cls_out_channels` should includes
564
+ background.
565
+ all_mask_preds (Tensor): Mask scores for all decoder layers with
566
+ shape (num_decoder, batch_size, num_queries, h, w).
567
+ gt_labels_list (list[Tensor]): Ground truth class indices for each
568
+ image with shape (n, ). n is the sum of number of stuff type
569
+ and number of instance in a image.
570
+ gt_masks_list (list[Tensor]): Ground truth mask for each image with
571
+ shape (n, h, w).
572
+ img_metas (list[dict]): List of image meta information.
573
+
574
+ Returns:
575
+ dict[str, Tensor]: A dictionary of loss components.
576
+ """
577
+
578
+ num_dec_layers = len(all_cls_scores)
579
+ stuff_gt_labels = []
580
+ stuff_gt_masks = []
581
+ thing_gt_labels = []
582
+ thing_gt_masks = []
583
+
584
+ for gt_labels, gt_masks in zip(gt_labels_list, gt_masks_list):
585
+ num_stuff = sum(torch.unique(gt_labels) >= self.num_things_classes)
586
+ stuff_gt_labels.append(gt_labels[-num_stuff:])
587
+ stuff_gt_masks.append(gt_masks[-num_stuff:])
588
+ thing_gt_labels.append(gt_labels[:-num_stuff])
589
+ thing_gt_masks.append(gt_masks[:-num_stuff])
590
+
591
+ stuff_gt_labels_list = [stuff_gt_labels for _ in range(num_dec_layers)]
592
+ stuff_gt_masks_list = [stuff_gt_masks for _ in range(num_dec_layers)]
593
+
594
+ thing_gt_labels_list = [thing_gt_labels for _ in range(num_dec_layers)]
595
+ thing_gt_masks_list = [thing_gt_masks for _ in range(num_dec_layers)]
596
+
597
+ stuff_scores = [all_cls_score[1] for all_cls_score in all_cls_scores]
598
+ stuff_mask_preds = [all_mask_pred[:, -self.num_stuff_classes:, :, :] for all_mask_pred in all_mask_preds ]
599
+
600
+ thing_scores = [all_cls_score[0] for all_cls_score in all_cls_scores]
601
+ thing_mask_preds = [all_mask_pred[:, :-self.num_stuff_classes, :, :] for all_mask_pred in all_mask_preds]
602
+
603
+ img_metas_list = [img_metas for _ in range(num_dec_layers)]
604
+ is_thing = [True for _ in range(num_dec_layers) ]
605
+ not_thing = [False for _ in range(num_dec_layers)]
606
+
607
+ losses_cls_stuff, losses_mask_stuff, losses_dice_stuff = multi_apply(
608
+ self.loss_single, stuff_scores, stuff_mask_preds,
609
+ stuff_gt_labels_list, stuff_gt_masks_list, img_metas_list, not_thing)
610
+
611
+ losses_cls_thing, losses_mask_thing, losses_dice_thing = multi_apply(
612
+ self.loss_single, thing_scores, thing_mask_preds,
613
+ thing_gt_labels_list, thing_gt_masks_list, img_metas_list, is_thing)
614
+
615
+ loss_dict = dict()
616
+
617
+ # loss from the last decoder layer
618
+ loss_dict['loss_cls'] = losses_cls_stuff[-1] + losses_cls_thing[-1]
619
+ loss_dict['loss_mask'] = losses_mask_stuff[-1] + losses_mask_thing[-1]
620
+ loss_dict['loss_dice'] = losses_dice_stuff[-1] + losses_dice_thing[-1]
621
+
622
+ # loss from other decoder layers stuff
623
+ num_dec_layer = 0
624
+ for loss_cls_i, loss_mask_i, loss_dice_i in zip(
625
+ losses_cls_stuff[:-1],
626
+ losses_mask_stuff[:-1],
627
+ losses_dice_stuff[:-1]):
628
+
629
+ loss_dict[f'd{num_dec_layer}.stuff_loss_cls'] = loss_cls_i
630
+ loss_dict[f'd{num_dec_layer}.stuff_loss_mask'] = loss_mask_i
631
+ loss_dict[f'd{num_dec_layer}.stuff_loss_dice'] = loss_dice_i
632
+ num_dec_layer += 1
633
+
634
+ # loss from other decoder layers thing
635
+ num_dec_layer = 0
636
+ for loss_cls_i, loss_mask_i, loss_dice_i in zip(
637
+ losses_mask_thing[:-1],
638
+ losses_mask_thing[:-1],
639
+ losses_mask_thing[:-1]):
640
+ loss_dict[f'd{num_dec_layer}.thing_loss_cls'] = loss_cls_i
641
+ loss_dict[f'd{num_dec_layer}.thing_loss_mask'] = loss_mask_i
642
+ loss_dict[f'd{num_dec_layer}.thing_loss_dice'] = loss_dice_i
643
+ num_dec_layer += 1
644
+
645
+ return loss_dict
646
+
647
+
648
+ def preprocess_gt(self, gt_labels_list, gt_masks_list, gt_semantic_segs,
649
+ img_metas):
650
+ """Preprocess the ground truth for all images.
651
+
652
+ Args:
653
+ gt_labels_list (list[Tensor]): Each is ground truth
654
+ labels of each bbox, with shape (num_gts, ).
655
+ gt_masks_list (list[BitmapMasks]): Each is ground truth
656
+ masks of each instances of a image, shape
657
+ (num_gts, h, w).
658
+ gt_semantic_seg (Tensor | None): Ground truth of semantic
659
+ segmentation with the shape (batch_size, n, h, w).
660
+ [0, num_thing_class - 1] means things,
661
+ [num_thing_class, num_class-1] means stuff,
662
+ 255 means VOID. It's None when training instance segmentation.
663
+ img_metas (list[dict]): List of image meta information.
664
+
665
+ Returns:
666
+ tuple: a tuple containing the following targets.
667
+ - labels (list[Tensor]): Ground truth class indices\
668
+ for all images. Each with shape (n, ), n is the sum of\
669
+ number of stuff type and number of instance in a image.
670
+ - masks (list[Tensor]): Ground truth mask for each\
671
+ image, each with shape (n, h, w).
672
+ """
673
+ num_things_list = [self.num_things_classes] * len(gt_labels_list)
674
+ num_stuff_list = [self.num_stuff_classes] * len(gt_labels_list)
675
+ if gt_semantic_segs is None:
676
+ gt_semantic_segs = [None] * len(gt_labels_list)
677
+
678
+ targets = multi_apply(preprocess_panoptic_gt_split_th_st, gt_labels_list,
679
+ gt_masks_list, gt_semantic_segs, num_things_list,
680
+ num_stuff_list, img_metas)
681
+ labels, masks = targets
682
+ return labels, masks
683
+
684
+
685
+ def preprocess_panoptic_gt_split_th_st(gt_labels, gt_masks, gt_semantic_seg, num_things,
686
+ num_stuff, img_metas):
687
+ """Preprocess the ground truth for a image.
688
+
689
+ Args:
690
+ gt_labels (Tensor): Ground truth labels of each bbox,
691
+ with shape (num_gts, ).
692
+ gt_masks (BitmapMasks): Ground truth masks of each instances
693
+ of a image, shape (num_gts, h, w).
694
+ gt_semantic_seg (Tensor | None): Ground truth of semantic
695
+ segmentation with the shape (1, h, w).
696
+ [0, num_thing_class - 1] means things,
697
+ [num_thing_class, num_class-1] means stuff,
698
+ 255 means VOID. It's None when training instance segmentation.
699
+ img_metas (dict): List of image meta information.
700
+
701
+ Returns:
702
+ tuple: a tuple containing the following targets.
703
+
704
+ - labels (Tensor): Ground truth class indices for a
705
+ image, with shape (n, ), n is the sum of number
706
+ of stuff type and number of instance in a image.
707
+ - masks (Tensor): Ground truth mask for a image, with
708
+ shape (n, h, w). Contains stuff and things when training
709
+ panoptic segmentation, and things only when training
710
+ instance segmentation.
711
+ """
712
+ num_classes = num_things + num_stuff
713
+
714
+ things_masks = gt_masks.pad(img_metas['pad_shape'][:2], pad_val=0)\
715
+ .to_tensor(dtype=torch.bool, device=gt_labels.device)
716
+
717
+ if gt_semantic_seg is None:
718
+ masks = things_masks.long()
719
+ return gt_labels, masks
720
+
721
+ things_labels = gt_labels
722
+ gt_semantic_seg = gt_semantic_seg.squeeze(0)
723
+
724
+ semantic_labels = torch.unique(
725
+ gt_semantic_seg,
726
+ sorted=False,
727
+ return_inverse=False,
728
+ return_counts=False)
729
+
730
+ stuff_masks_list = []
731
+ stuff_labels_list = []
732
+ for label in semantic_labels:
733
+ if label < num_things or label >= num_classes:
734
+ continue
735
+ stuff_mask = gt_semantic_seg == label
736
+ stuff_masks_list.append(stuff_mask)
737
+ # new stuff label: 0 - N_{stuff} -1
738
+ stuff_labels_list.append(label - num_things)
739
+
740
+ if len(stuff_masks_list) > 0:
741
+ stuff_masks = torch.stack(stuff_masks_list, dim=0)
742
+ stuff_labels = torch.stack(stuff_labels_list, dim=0)
743
+ labels = torch.cat([things_labels, stuff_labels], dim=0)
744
+ masks = torch.cat([things_masks, stuff_masks], dim=0)
745
+ else:
746
+ labels = things_labels
747
+ masks = things_masks
748
+
749
+ masks = masks.long()
750
+
751
+ return labels, masks
OpenPVSG/models/unitrack/core/__init__.py ADDED
File without changes
OpenPVSG/models/unitrack/core/association/__init__.py ADDED
File without changes
OpenPVSG/models/unitrack/core/association/matching.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import numpy as np
4
+ import scipy
5
+ from scipy.spatial.distance import cdist
6
+ import lap
7
+
8
+ from cython_bbox import bbox_overlaps as bbox_ious
9
+ from ..motion import kalman_filter
10
+
11
+
12
+ def merge_matches(m1, m2, shape):
13
+ O,P,Q = shape
14
+ m1 = np.asarray(m1)
15
+ m2 = np.asarray(m2)
16
+
17
+ M1 = scipy.sparse.coo_matrix((np.ones(len(m1)), (m1[:, 0], m1[:, 1])), shape=(O, P))
18
+ M2 = scipy.sparse.coo_matrix((np.ones(len(m2)), (m2[:, 0], m2[:, 1])), shape=(P, Q))
19
+
20
+ mask = M1*M2
21
+ match = mask.nonzero()
22
+ match = list(zip(match[0], match[1]))
23
+ unmatched_O = tuple(set(range(O)) - set([i for i, j in match]))
24
+ unmatched_Q = tuple(set(range(Q)) - set([j for i, j in match]))
25
+
26
+ return match, unmatched_O, unmatched_Q
27
+
28
+
29
+ def linear_assignment(cost_matrix, thresh):
30
+ if cost_matrix.size == 0:
31
+ return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
32
+ matches, unmatched_a, unmatched_b = [], [], []
33
+ cost, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
34
+ for ix, mx in enumerate(x):
35
+ if mx >= 0:
36
+ matches.append([ix, mx])
37
+ unmatched_a = np.where(x < 0)[0]
38
+ unmatched_b = np.where(y < 0)[0]
39
+ matches = np.asarray(matches)
40
+ return matches, unmatched_a, unmatched_b
41
+
42
+
43
+ def ious(atlbrs, btlbrs):
44
+ """
45
+ Compute cost based on IoU
46
+ :type atlbrs: list[tlbr] | np.ndarray
47
+ :type atlbrs: list[tlbr] | np.ndarray
48
+
49
+ :rtype ious np.ndarray
50
+ """
51
+ ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float)
52
+ if ious.size == 0:
53
+ return ious
54
+
55
+ ious = bbox_ious(
56
+ np.ascontiguousarray(atlbrs, dtype=np.float),
57
+ np.ascontiguousarray(btlbrs, dtype=np.float)
58
+ )
59
+
60
+ return ious
61
+
62
+
63
+ def iou_distance(atracks, btracks):
64
+ """
65
+ Compute cost based on IoU
66
+ :type atracks: list[STrack]
67
+ :type btracks: list[STrack]
68
+
69
+ :rtype cost_matrix np.ndarray
70
+ """
71
+
72
+ if (len(atracks)>0 and isinstance(atracks[0], np.ndarray)) or (len(btracks) > 0 and isinstance(btracks[0], np.ndarray)):
73
+ atlbrs = atracks
74
+ btlbrs = btracks
75
+ else:
76
+ atlbrs = [track.tlbr for track in atracks]
77
+ btlbrs = [track.tlbr for track in btracks]
78
+ _ious = ious(atlbrs, btlbrs)
79
+ cost_matrix = 1 - _ious
80
+
81
+ return cost_matrix
82
+
83
+ def embedding_distance(tracks, detections, metric='cosine'):
84
+ """
85
+ :param tracks: list[STrack]
86
+ :param detections: list[BaseTrack]
87
+ :param metric:
88
+ :return: cost_matrix np.ndarray
89
+ """
90
+
91
+ cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float)
92
+ if cost_matrix.size == 0:
93
+ return cost_matrix
94
+ det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float)
95
+ track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float)
96
+ cost_matrix = np.maximum(0.0, cdist(track_features, det_features)) # Nomalized features
97
+ return cost_matrix
98
+
99
+
100
+ def fuse_motion(kf, cost_matrix, tracks, detections, only_position=False, lambda_=0.98, gate=True):
101
+ if cost_matrix.size == 0:
102
+ return cost_matrix
103
+ gating_dim = 2 if only_position else 4
104
+ gating_threshold = kalman_filter.chi2inv95[gating_dim]
105
+ measurements = np.asarray([det.to_xyah() for det in detections])
106
+ for row, track in enumerate(tracks):
107
+ gating_distance = kf.gating_distance(
108
+ track.mean, track.covariance, measurements, only_position, metric='maha')
109
+ if gate:
110
+ cost_matrix[row, gating_distance > gating_threshold] = np.inf
111
+ cost_matrix[row] = lambda_ * cost_matrix[row] + (1-lambda_)* gating_distance
112
+ return cost_matrix
113
+
114
+
115
+ def center_emb_distance(tracks, detections, metric='cosine'):
116
+ """
117
+ :param tracks: list[STrack]
118
+ :param detections: list[BaseTrack]
119
+ :param metric:
120
+ :return: cost_matrix np.ndarray
121
+ """
122
+
123
+ cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float)
124
+ if cost_matrix.size == 0:
125
+ return cost_matrix
126
+ det_features = torch.stack([track.curr_feat.squeeze() for track in detections])
127
+ track_features = torch.stack([track.smooth_feat.squeeze() for track in tracks])
128
+ normed_det = F.normalize(det_features)
129
+ normed_track = F.normalize(track_features)
130
+ cost_matrix = torch.mm(normed_track, normed_det.T)
131
+ cost_matrix = 1 - cost_matrix.detach().cpu().numpy()
132
+ return cost_matrix
133
+
134
+ def recons_distance(tracks, detections, tmp=100):
135
+ """
136
+ :param tracks: list[STrack]
137
+ :param detections: list[BaseTrack]
138
+ :param metric:
139
+ :return: cost_matrix np.ndarray
140
+ """
141
+
142
+ cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float)
143
+ if cost_matrix.size == 0:
144
+ return cost_matrix
145
+ det_features_ = torch.stack([track.curr_feat.squeeze() for track in detections])
146
+ track_features_ = torch.stack([track.smooth_feat for track in tracks])
147
+ det_features = F.normalize(det_features_, dim=1)
148
+ track_features = F.normalize(track_features_, dim=1)
149
+
150
+ ndet, ndim, nw, nh = det_features.shape
151
+ ntrk, _, _, _ = track_features.shape
152
+ fdet = det_features.permute(0,2,3,1).reshape(-1, ndim).cuda() # ndet*nw*nh, ndim
153
+ ftrk = track_features.permute(0,2,3,1).reshape(-1, ndim).cuda() # ntrk*nw*nh, ndim
154
+
155
+ aff = torch.mm(ftrk, fdet.transpose(0,1)) # ntrk*nw*nh, ndet*nw*nh
156
+ aff_td = F.softmax(tmp*aff, dim=1)
157
+ aff_dt = F.softmax(tmp*aff, dim=0).transpose(0,1)
158
+
159
+ recons_ftrk = torch.einsum('tds,dsm->tdm', aff_td.view(ntrk*nw*nh, ndet, nw*nh),
160
+ fdet.view(ndet, nw*nh, ndim)) # ntrk*nw*nh, ndet, ndim
161
+ recons_fdet = torch.einsum('dts,tsm->dtm', aff_dt.view(ndet*nw*nh, ntrk, nw*nh),
162
+ ftrk.view(ntrk, nw*nh, ndim)) # ndet*nw*nh, ntrk, ndim
163
+
164
+ res_ftrk = (recons_ftrk.permute(0,2,1) - ftrk.unsqueeze(-1)).view(ntrk, nw*nh*ndim, ndet)
165
+ res_fdet = (recons_fdet.permute(0,2,1) - fdet.unsqueeze(-1)).view(ndet, nw*nh*ndim, ntrk)
166
+
167
+ cost_matrix = (torch.abs(res_ftrk).mean(1) + torch.abs(res_fdet).mean(1).transpose(0,1)) * 0.5
168
+ cost_matrix = cost_matrix / cost_matrix.max(1)[0].unsqueeze(-1)
169
+ #pdb.set_trace()
170
+ cost_matrix = cost_matrix.cpu().numpy()
171
+ return cost_matrix
172
+
173
+
174
+ def get_track_feat(tracks, feat_flag='curr'):
175
+ if feat_flag == 'curr':
176
+ feat_list = [track.curr_feat.squeeze(0) for track in tracks]
177
+ elif feat_flag == 'smooth':
178
+ feat_list = [track.smooth_feat.squeeze(0) for track in tracks]
179
+ else:
180
+ raise NotImplementedError
181
+
182
+ n = len(tracks)
183
+ fdim = feat_list[0].shape[0]
184
+ fdim_num = len(feat_list[0].shape)
185
+ if fdim_num > 2:
186
+ feat_list = [f.view(fdim,-1) for f in feat_list]
187
+ numels = [f.shape[1] for f in feat_list]
188
+
189
+ ret = torch.zeros(n, fdim, np.max(numels)).to(feat_list[0].device)
190
+ for i, f in enumerate(feat_list):
191
+ ret[i, :, :numels[i]] = f
192
+ return ret
193
+
194
+ def reconsdot_distance(tracks, detections, tmp=100):
195
+ """
196
+ :param tracks: list[STrack]
197
+ :param detections: list[BaseTrack]
198
+ :param metric:
199
+ :return: cost_matrix np.ndarray
200
+ """
201
+ cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float)
202
+ if cost_matrix.size == 0:
203
+ return cost_matrix, None
204
+ det_features_ = get_track_feat(detections)
205
+ track_features_ = get_track_feat(tracks, feat_flag='curr')
206
+
207
+ det_features = F.normalize(det_features_, dim=1)
208
+ track_features = F.normalize(track_features_, dim=1)
209
+
210
+ ndet, ndim, nsd = det_features.shape
211
+ ntrk, _, nst = track_features.shape
212
+
213
+ fdet = det_features.permute(0, 2, 1).reshape(-1, ndim)
214
+ ftrk = track_features.permute(0, 2, 1).reshape(-1, ndim)
215
+
216
+ aff = torch.mm(ftrk, fdet.transpose(0, 1))
217
+ aff_td = F.softmax(tmp*aff, dim=1)
218
+ aff_dt = F.softmax(tmp*aff, dim=0).transpose(0, 1)
219
+
220
+ recons_ftrk = torch.einsum('tds,dsm->tdm', aff_td.view(ntrk*nst, ndet, nsd),
221
+ fdet.view(ndet, nsd, ndim))
222
+ recons_fdet = torch.einsum('dts,tsm->dtm', aff_dt.view(ndet*nsd, ntrk, nst),
223
+ ftrk.view(ntrk, nst, ndim))
224
+
225
+ recons_ftrk = recons_ftrk.permute(0, 2, 1).reshape((ntrk, nst*ndim, ndet))
226
+ recons_ftrk_norm = F.normalize(recons_ftrk, dim=1)
227
+ recons_fdet = recons_fdet.permute(0, 2, 1).view(ndet, nsd*ndim, ntrk)
228
+ recons_fdet_norm = F.normalize(recons_fdet, dim=1)
229
+
230
+ dot_td = torch.einsum('tad,ta->td', recons_ftrk_norm,
231
+ F.normalize(ftrk.reshape(ntrk, nst*ndim), dim=1))
232
+ dot_dt = torch.einsum('dat,da->dt', recons_fdet_norm,
233
+ F.normalize(fdet.reshape(ndet, nsd*ndim), dim=1))
234
+
235
+ cost_matrix = 1 - 0.5 * (dot_td + dot_dt.transpose(0, 1))
236
+ cost_matrix = cost_matrix.detach().cpu().numpy()
237
+
238
+ return cost_matrix, None
239
+
240
+
241
+ def category_gate(cost_matrix, tracks, detections):
242
+ """
243
+ :param tracks: list[STrack]
244
+ :param detections: list[BaseTrack]
245
+ :param metric:
246
+ :return: cost_matrix np.ndarray
247
+ """
248
+ if cost_matrix.size == 0:
249
+ return cost_matrix
250
+
251
+ det_categories = np.array([d.category for d in detections])
252
+ trk_categories = np.array([t.category for t in tracks])
253
+
254
+ cost_matrix = cost_matrix + np.abs(
255
+ det_categories[None, :] - trk_categories[:, None])
256
+ return cost_matrix
257
+
258
+
OpenPVSG/models/unitrack/core/motion/kalman_filter.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # vim: expandtab:ts=4:sw=4
2
+ import numpy as np
3
+ import scipy.linalg
4
+
5
+
6
+ """
7
+ Table for the 0.95 quantile of the chi-square distribution with N degrees of
8
+ freedom (contains values for N=1, ..., 9). Taken from MATLAB/Octave's chi2inv
9
+ function and used as Mahalanobis gating threshold.
10
+ """
11
+ chi2inv95 = {
12
+ 1: 3.8415,
13
+ 2: 5.9915,
14
+ 3: 7.8147,
15
+ 4: 9.4877,
16
+ 5: 11.070,
17
+ 6: 12.592,
18
+ 7: 14.067,
19
+ 8: 15.507,
20
+ 9: 16.919}
21
+
22
+
23
+ class KalmanFilter(object):
24
+ """
25
+ A simple Kalman filter for tracking bounding boxes in image space.
26
+
27
+ The 8-dimensional state space
28
+
29
+ x, y, a, h, vx, vy, va, vh
30
+
31
+ contains the bounding box center position (x, y), aspect ratio a, height h,
32
+ and their respective velocities.
33
+
34
+ Object motion follows a constant velocity model. The bounding box location
35
+ (x, y, a, h) is taken as direct observation of the state space (linear
36
+ observation model).
37
+
38
+ """
39
+
40
+ def __init__(self):
41
+ ndim, dt = 4, 1.
42
+
43
+ # Create Kalman filter model matrices.
44
+ self._motion_mat = np.eye(2 * ndim, 2 * ndim)
45
+ for i in range(ndim):
46
+ self._motion_mat[i, ndim + i] = dt
47
+ self._update_mat = np.eye(ndim, 2 * ndim)
48
+
49
+ # Motion and observation uncertainty are chosen relative to the current
50
+ # state estimate. These weights control the amount of uncertainty in
51
+ # the model. This is a bit hacky.
52
+ self._std_weight_position = 1. / 20
53
+ self._std_weight_velocity = 1. / 160
54
+
55
+ def initiate(self, measurement):
56
+ """Create track from unassociated measurement.
57
+
58
+ Parameters
59
+ ----------
60
+ measurement : ndarray
61
+ Bounding box coordinates (x, y, a, h) with center position (x, y),
62
+ aspect ratio a, and height h.
63
+
64
+ Returns
65
+ -------
66
+ (ndarray, ndarray)
67
+ Returns the mean vector (8 dimensional) and covariance matrix (8x8
68
+ dimensional) of the new track. Unobserved velocities are initialized
69
+ to 0 mean.
70
+
71
+ """
72
+ mean_pos = measurement
73
+ mean_vel = np.zeros_like(mean_pos)
74
+ mean = np.r_[mean_pos, mean_vel]
75
+
76
+ std = [
77
+ 2 * self._std_weight_position * measurement[3],
78
+ 2 * self._std_weight_position * measurement[3],
79
+ 1e-2,
80
+ 2 * self._std_weight_position * measurement[3],
81
+ 10 * self._std_weight_velocity * measurement[3],
82
+ 10 * self._std_weight_velocity * measurement[3],
83
+ 1e-5,
84
+ 10 * self._std_weight_velocity * measurement[3]]
85
+ covariance = np.diag(np.square(std))
86
+ return mean, covariance
87
+
88
+ def predict(self, mean, covariance):
89
+ """Run Kalman filter prediction step.
90
+
91
+ Parameters
92
+ ----------
93
+ mean : ndarray
94
+ The 8 dimensional mean vector of the object state at the previous
95
+ time step.
96
+ covariance : ndarray
97
+ The 8x8 dimensional covariance matrix of the object state at the
98
+ previous time step.
99
+
100
+ Returns
101
+ -------
102
+ (ndarray, ndarray)
103
+ Returns the mean vector and covariance matrix of the predicted
104
+ state. Unobserved velocities are initialized to 0 mean.
105
+
106
+ """
107
+ std_pos = [
108
+ self._std_weight_position * mean[3],
109
+ self._std_weight_position * mean[3],
110
+ 1e-2,
111
+ self._std_weight_position * mean[3]]
112
+ std_vel = [
113
+ self._std_weight_velocity * mean[3],
114
+ self._std_weight_velocity * mean[3],
115
+ 1e-5,
116
+ self._std_weight_velocity * mean[3]]
117
+ motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))
118
+
119
+ mean = np.dot(mean, self._motion_mat.T)
120
+ covariance = np.linalg.multi_dot((
121
+ self._motion_mat, covariance, self._motion_mat.T)) + motion_cov
122
+
123
+ return mean, covariance
124
+
125
+ def project(self, mean, covariance):
126
+ """Project state distribution to measurement space.
127
+
128
+ Parameters
129
+ ----------
130
+ mean : ndarray
131
+ The state's mean vector (8 dimensional array).
132
+ covariance : ndarray
133
+ The state's covariance matrix (8x8 dimensional).
134
+
135
+ Returns
136
+ -------
137
+ (ndarray, ndarray)
138
+ Returns the projected mean and covariance matrix of the given state
139
+ estimate.
140
+
141
+ """
142
+ std = [
143
+ self._std_weight_position * mean[3],
144
+ self._std_weight_position * mean[3],
145
+ 1e-1,
146
+ self._std_weight_position * mean[3]]
147
+ innovation_cov = np.diag(np.square(std))
148
+
149
+ mean = np.dot(self._update_mat, mean)
150
+ covariance = np.linalg.multi_dot((
151
+ self._update_mat, covariance, self._update_mat.T))
152
+ return mean, covariance + innovation_cov
153
+
154
+ def multi_predict(self, mean, covariance):
155
+ """Run Kalman filter prediction step (Vectorized version).
156
+
157
+ Parameters
158
+ ----------
159
+ mean : ndarray
160
+ The Nx8 dimensional mean matrix of the object states at the previous
161
+ time step.
162
+ covariance : ndarray
163
+ The Nx8x8 dimensional covariance matrics of the object states at the
164
+ previous time step.
165
+
166
+ Returns
167
+ -------
168
+ (ndarray, ndarray)
169
+ Returns the mean vector and covariance matrix of the predicted
170
+ state. Unobserved velocities are initialized to 0 mean.
171
+
172
+ """
173
+ std_pos = [
174
+ self._std_weight_position * mean[:, 3],
175
+ self._std_weight_position * mean[:, 3],
176
+ 1e-2 * np.ones_like(mean[:, 3]),
177
+ self._std_weight_position * mean[:, 3]]
178
+ std_vel = [
179
+ self._std_weight_velocity * mean[:, 3],
180
+ self._std_weight_velocity * mean[:, 3],
181
+ 1e-5 * np.ones_like(mean[:, 3]),
182
+ self._std_weight_velocity * mean[:, 3]]
183
+ sqr = np.square(np.r_[std_pos, std_vel]).T
184
+
185
+ motion_cov = []
186
+ for i in range(len(mean)):
187
+ motion_cov.append(np.diag(sqr[i]))
188
+ motion_cov = np.asarray(motion_cov)
189
+
190
+ mean = np.dot(mean, self._motion_mat.T)
191
+ left = np.dot(self._motion_mat, covariance).transpose((1,0,2))
192
+ covariance = np.dot(left, self._motion_mat.T) + motion_cov
193
+
194
+ return mean, covariance
195
+
196
+ def update(self, mean, covariance, measurement):
197
+ """Run Kalman filter correction step.
198
+
199
+ Parameters
200
+ ----------
201
+ mean : ndarray
202
+ The predicted state's mean vector (8 dimensional).
203
+ covariance : ndarray
204
+ The state's covariance matrix (8x8 dimensional).
205
+ measurement : ndarray
206
+ The 4 dimensional measurement vector (x, y, a, h), where (x, y)
207
+ is the center position, a the aspect ratio, and h the height of the
208
+ bounding box.
209
+
210
+ Returns
211
+ -------
212
+ (ndarray, ndarray)
213
+ Returns the measurement-corrected state distribution.
214
+
215
+ """
216
+ projected_mean, projected_cov = self.project(mean, covariance)
217
+
218
+ chol_factor, lower = scipy.linalg.cho_factor(
219
+ projected_cov, lower=True, check_finite=False)
220
+ kalman_gain = scipy.linalg.cho_solve(
221
+ (chol_factor, lower), np.dot(covariance, self._update_mat.T).T,
222
+ check_finite=False).T
223
+ innovation = measurement - projected_mean
224
+
225
+ new_mean = mean + np.dot(innovation, kalman_gain.T)
226
+ new_covariance = covariance - np.linalg.multi_dot((
227
+ kalman_gain, projected_cov, kalman_gain.T))
228
+ return new_mean, new_covariance
229
+
230
+ def gating_distance(self, mean, covariance, measurements,
231
+ only_position=False, metric='maha'):
232
+ """Compute gating distance between state distribution and measurements.
233
+
234
+ A suitable distance threshold can be obtained from `chi2inv95`. If
235
+ `only_position` is False, the chi-square distribution has 4 degrees of
236
+ freedom, otherwise 2.
237
+
238
+ Parameters
239
+ ----------
240
+ mean : ndarray
241
+ Mean vector over the state distribution (8 dimensional).
242
+ covariance : ndarray
243
+ Covariance of the state distribution (8x8 dimensional).
244
+ measurements : ndarray
245
+ An Nx4 dimensional matrix of N measurements, each in
246
+ format (x, y, a, h) where (x, y) is the bounding box center
247
+ position, a the aspect ratio, and h the height.
248
+ only_position : Optional[bool]
249
+ If True, distance computation is done with respect to the bounding
250
+ box center position only.
251
+
252
+ Returns
253
+ -------
254
+ ndarray
255
+ Returns an array of length N, where the i-th element contains the
256
+ squared Mahalanobis distance between (mean, covariance) and
257
+ `measurements[i]`.
258
+
259
+ """
260
+ mean, covariance = self.project(mean, covariance)
261
+ if only_position:
262
+ mean, covariance = mean[:2], covariance[:2, :2]
263
+ measurements = measurements[:, :2]
264
+
265
+ d = measurements - mean
266
+ if metric == 'gaussian':
267
+ return np.sum(d * d, axis=1)
268
+ elif metric == 'maha':
269
+ cholesky_factor = np.linalg.cholesky(covariance)
270
+ z = scipy.linalg.solve_triangular(
271
+ cholesky_factor, d.T, lower=True, check_finite=False,
272
+ overwrite_b=True)
273
+ squared_maha = np.sum(z * z, axis=0)
274
+ return squared_maha
275
+ else:
276
+ raise ValueError('invalid distance metric')
277
+
OpenPVSG/models/unitrack/core/propagation/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###################################################################
2
+ # File Name: __init__.py
3
+ # Author: Zhongdao Wang
4
+ # mail: wcd17@mails.tsinghua.edu.cn
5
+ # Created Time: Mon Jan 18 15:57:34 2021
6
+ ###################################################################
7
+
8
+ from __future__ import print_function
9
+ from __future__ import division
10
+ from __future__ import absolute_import
11
+
12
+ from .propagate_box import propagate_box
13
+ from .propagate_mask import propagate_mask
14
+ from .propagate_pose import propagate_pose
15
+
16
+ def propagate(temp_feats, obs, img, model, format='box'):
17
+ if format == 'box':
18
+ return propagate_box(temp_feats, obs, img, model)
19
+ elif format == 'mask':
20
+ return propagate_box(temp_feats, obs, img, model)
21
+ elif format == 'pose':
22
+ return propagate_pose(temp_feats, obs, img, model)
23
+ else:
24
+ raise ValueError('Observation format not supported.')
OpenPVSG/models/unitrack/core/propagation/propagate_box.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###################################################################
2
+ # File Name: propagate_box.py
3
+ # Author: Zhongdao Wang
4
+ # mail: wcd17@mails.tsinghua.edu.cn
5
+ # Created Time: Mon Jan 18 16:01:46 2021
6
+ ###################################################################
7
+
8
+ from __future__ import print_function
9
+ from __future__ import division
10
+ from __future__ import absolute_import
11
+
12
+ def propagate_box(temp_feats, box, img, model):
13
+ pass
OpenPVSG/models/unitrack/core/propagation/propagate_mask.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###################################################################
2
+ # File Name: propagate_box.py
3
+ # Author: Zhongdao Wang
4
+ # mail: wcd17@mails.tsinghua.edu.cn
5
+ # Created Time: Mon Jan 18 16:01:46 2021
6
+ ###################################################################
7
+
8
+ from __future__ import print_function
9
+ from __future__ import division
10
+ from __future__ import absolute_import
11
+
12
+ def propagate_mask(temp_feats, mask, img, model):
13
+ pass
OpenPVSG/models/unitrack/core/propagation/propagate_pose.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###################################################################
2
+ # File Name: propagate_box.py
3
+ # Author: Zhongdao Wang
4
+ # mail: wcd17@mails.tsinghua.edu.cn
5
+ # Created Time: Mon Jan 18 16:01:46 2021
6
+ ###################################################################
7
+
8
+ from __future__ import print_function
9
+ from __future__ import division
10
+ from __future__ import absolute_import
11
+
12
+ def propagate_pose(temp_feats, pose, img, model):
13
+ pass
OpenPVSG/models/unitrack/data/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .single_video import LoadOutputsFromMask2Former
2
+ from .query_feat_tracklet import QueryFeatTube
OpenPVSG/models/unitrack/data/query_feat_tracklet.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from collections import deque
3
+
4
+
5
+ class QueryFeatTube(object):
6
+ def __init__(self, start_frame_id, track_id, query_feat):
7
+ self.track_id = track_id
8
+ self.start_frame_id = start_frame_id
9
+ self.end_frame_id = start_frame_id
10
+ self.len = 1
11
+ qf_tube = self._init_previous_tube()
12
+ qf_tube.append(query_feat)
13
+ self.qf_tube = qf_tube
14
+
15
+ def __repr__(self):
16
+ return 'QFT_{}_({}_{})'.format(self.track_id, self.start_frame_id,
17
+ self.end_frame_id)
18
+
19
+ def _init_previous_tube(self):
20
+ # called when a new detection is found - fill previous position with "None"
21
+ qf_tube = [None for i in range(self.start_frame_id - 1)]
22
+ return qf_tube
23
+
24
+ def update(self, query_feat, cur_frame_id):
25
+ if self.end_frame_id < cur_frame_id:
26
+ self.qf_tube.extend(
27
+ [None for i in range(cur_frame_id - self.end_frame_id - 1)])
28
+ self.qf_tube.append(query_feat)
29
+ self.end_frame_id = cur_frame_id
30
+ self.len += 1
31
+
32
+ def complete_empty_postfix(self, last_frame_idx):
33
+ if len(self.qf_tube) == last_frame_idx + 1:
34
+ return self
35
+ self.qf_tube.extend(
36
+ [None for i in range(last_frame_idx + 1 - self.end_frame_id)])
37
+ # self.end_frame_id = last_frame_idx + 1
38
+ return self
OpenPVSG/models/unitrack/data/single_video.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from pathlib import Path
3
+ import torch
4
+ import cv2
5
+ from torchvision.transforms import transforms as T
6
+
7
+ from mmdet.core import INSTANCE_OFFSET
8
+
9
+
10
+ class LoadOutputsFromMask2Former:
11
+ """Process outputs of all images of a singel video from mask2former to
12
+ inputs of unitracker.
13
+
14
+ Modification from LoadImagesAndMaskObsMOTS: get_data
15
+ """
16
+ def __init__(
17
+ self,
18
+ data_cfg, # data_cfg = data.test (in data base config)
19
+ outputs,
20
+ tracker_cfg, # add cfg! (follow unitrack opt)
21
+ classes):
22
+ data_root = Path(data_cfg.data_root)
23
+ video_name = data_cfg.video_name
24
+ if video_name.startswith('P'):
25
+ data_source = 'epic_kitchen'
26
+ elif video_name.split('_')[0].isdigit() and len(
27
+ video_name.split('_')[0]) == 4:
28
+ data_source = 'vidor'
29
+ else:
30
+ data_source = 'ego4d'
31
+
32
+ video_folder = data_root / data_source / 'frames' / video_name
33
+ self.num_classes = len(classes)
34
+ self.img_files = sorted(
35
+ [str(x) for x in (video_folder.rglob('*.png'))])
36
+ self.transforms = T.Compose([
37
+ T.ToTensor(),
38
+ T.Normalize(tracker_cfg.common.im_mean, tracker_cfg.common.im_std)
39
+ ])
40
+
41
+ pan_masks_all_images = []
42
+ query_feat_dicts_all_images = []
43
+ for frame_output in outputs:
44
+ pan_masks_all_images.append(frame_output['pan_results'])
45
+ query_feat_dicts_all_images.append(frame_output['query_feats'])
46
+ self.pan_masks_all_images = pan_masks_all_images
47
+ self.query_feat_dicts_all_images = query_feat_dicts_all_images
48
+
49
+ def _get_binary_masks_and_query_feats(
50
+ self, pan_mask, query_feat_dict): # for single frame all objects
51
+ object_ids = list(np.unique(pan_mask))
52
+ if self.num_classes in object_ids:
53
+ object_ids.remove(self.num_classes)
54
+ if len(
55
+ object_ids
56
+ ) == 0: # deal with the case that no mask was detected from mask2former!!!!
57
+ return np.array([]), []
58
+ assert len(list(query_feat_dict.keys())) == len(
59
+ object_ids), 'Masks and query feats should match!'
60
+
61
+ binary_masks = []
62
+ query_feats = []
63
+ for object_id in object_ids:
64
+ # binary masks
65
+ obj_binary_mask = (pan_mask == object_id).astype(np.int)
66
+ binary_masks.append(obj_binary_mask)
67
+ # cls ids
68
+ cls_id = object_id % INSTANCE_OFFSET
69
+ # query feat list (map masks order)
70
+ query_feats.append(
71
+ dict(query_feat=self._unify_query_feat_dim(
72
+ query_feat_dict[object_id]),
73
+ cls_id=cls_id)) # zip the two things together
74
+
75
+ return np.stack(
76
+ binary_masks
77
+ ), query_feats # obs should be numpy array ! not tensor
78
+
79
+ def _unify_query_feat_dim(self, query_feat_list):
80
+ if len(query_feat_list) == 1:
81
+ return query_feat_list[0].squeeze() # squeeze (1,256) to (256,)
82
+ else: # get average for stuff
83
+ query_feat_list = [x.squeeze() for x in query_feat_list]
84
+ query_feat_stack = np.stack(query_feat_list)
85
+ return query_feat_stack.mean(axis=0)
86
+
87
+ def __getitem__(self, idx):
88
+ img_ori = cv2.imread(self.img_files[idx])
89
+ if img_ori is None:
90
+ raise ValueError('File corrupt {}'.format(self.img_files[idx]))
91
+ # process img: copy from unitrack-video.py
92
+ h, w, _ = img_ori.shape
93
+ img = img_ori
94
+ img = img / 255.
95
+ img = np.ascontiguousarray(img[:, :, ::-1]) # BGR to RGB
96
+ if self.transforms is not None:
97
+ img = self.transforms(img)
98
+ # process masks and get cls_id
99
+ labels, query_feats = self._get_binary_masks_and_query_feats(
100
+ self.pan_masks_all_images[idx],
101
+ self.query_feat_dicts_all_images[idx])
102
+ return img, labels, img_ori, (h, w), query_feats
OpenPVSG/models/unitrack/data/video.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pdb
3
+ import glob
4
+ import json
5
+ import os.path as osp
6
+
7
+ import cv2
8
+ import numpy as np
9
+
10
+ import pycocotools.mask as mask_utils
11
+ from utils.box import xyxy2xywh
12
+
13
+ from torchvision.transforms import transforms as T
14
+
15
+
16
+ class LoadImages: # for inference
17
+ def __init__(self, path, img_size=(1088, 608)):
18
+ if os.path.isdir(path):
19
+ image_format = ['.jpg', '.jpeg', '.png', '.tif']
20
+ self.files = sorted(glob.glob('%s/*.*' % path))
21
+ self.files = list(
22
+ filter(
23
+ lambda x: os.path.splitext(x)[1].lower() in image_format,
24
+ self.files))
25
+ elif os.path.isfile(path):
26
+ self.files = [path]
27
+
28
+ self.nF = len(self.files) # number of image files
29
+ self.width = img_size[0]
30
+ self.height = img_size[1]
31
+ self.count = 0
32
+
33
+ assert self.nF > 0, 'No images found in ' + path
34
+
35
+ def __iter__(self):
36
+ self.count = -1
37
+ return self
38
+
39
+ def __next__(self):
40
+ self.count += 1
41
+ if self.count == self.nF:
42
+ raise StopIteration
43
+ img_path = self.files[self.count]
44
+
45
+ # Read image
46
+ img0 = cv2.imread(img_path) # BGR
47
+ assert img0 is not None, 'Failed to load ' + img_path
48
+
49
+ # Padded resize
50
+ img, _, _, _ = letterbox(img0, height=self.height, width=self.width)
51
+
52
+ # Normalize RGB
53
+ img = img[:, :, ::-1].transpose(2, 0, 1)
54
+ img = np.ascontiguousarray(img, dtype=np.float32)
55
+ img /= 255.0
56
+
57
+ return img_path, img, img0
58
+
59
+ def __getitem__(self, idx):
60
+ idx = idx % self.nF
61
+ img_path = self.files[idx]
62
+
63
+ # Read image
64
+ img0 = cv2.imread(img_path) # BGR
65
+ assert img0 is not None, 'Failed to load ' + img_path
66
+
67
+ # Padded resize
68
+ img, _, _, _ = letterbox(img0, height=self.height, width=self.width)
69
+
70
+ # Normalize RGB
71
+ img = img[:, :, ::-1].transpose(2, 0, 1)
72
+ img = np.ascontiguousarray(img, dtype=np.float32)
73
+ img /= 255.0
74
+
75
+ return img_path, img, img0
76
+
77
+ def __len__(self):
78
+ return self.nF # number of files
79
+
80
+
81
+ class LoadVideo: # for inference
82
+ def __init__(self, path, img_size=(1088, 608)):
83
+ self.cap = cv2.VideoCapture(path)
84
+ self.frame_rate = int(round(self.cap.get(cv2.CAP_PROP_FPS)))
85
+ self.vw = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
86
+ self.vh = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
87
+ self.vn = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
88
+
89
+ self.width = img_size[0]
90
+ self.height = img_size[1]
91
+ self.count = 0
92
+
93
+ self.w, self.h = self.get_size(self.vw, self.vh, self.width,
94
+ self.height)
95
+ print('Lenth of the video: {:d} frames'.format(self.vn))
96
+
97
+ def get_size(self, vw, vh, dw, dh):
98
+ wa, ha = float(dw) / vw, float(dh) / vh
99
+ a = min(wa, ha)
100
+ return int(vw * a), int(vh * a)
101
+
102
+ def __iter__(self):
103
+ self.count = -1
104
+ return self
105
+
106
+ def __next__(self):
107
+ self.count += 1
108
+ if self.count == len(self):
109
+ raise StopIteration
110
+ # Read image
111
+ res, img0 = self.cap.read() # BGR
112
+ assert img0 is not None, 'Failed to load frame {:d}'.format(self.count)
113
+ img0 = cv2.resize(img0, (self.w, self.h))
114
+
115
+ # Padded resize
116
+ img, _, _, _ = letterbox(img0, height=self.height, width=self.width)
117
+
118
+ # Normalize RGB
119
+ img = img[:, :, ::-1]
120
+ img = np.ascontiguousarray(img, dtype=np.float32)
121
+
122
+ return self.count, img, img0
123
+
124
+ def __len__(self):
125
+ return self.vn # number of files
126
+
127
+
128
+ class LoadImagesAndObs:
129
+ def __init__(self, path, opt):
130
+ obid = opt.obid
131
+ img_size = getattr(opt, 'img_size', None)
132
+ if os.path.isdir(path):
133
+ image_format = ['.jpg', '.jpeg', '.png', '.tif']
134
+ self.img_files = sorted(glob.glob('%s/*.*' % path))
135
+ self.img_files = list(
136
+ filter(
137
+ lambda x: os.path.splitext(x)[1].lower() in image_format,
138
+ self.img_files))
139
+ elif os.path.isfile(path):
140
+ self.img_files = [
141
+ path,
142
+ ]
143
+
144
+ # self.label_files = [x.replace('images', osp.join('obs', obid)).replace(
145
+ # '.png', '.txt').replace('.jpg', '.txt') for x in self.img_files]
146
+ self.label_files = [
147
+ x.replace('images',
148
+ osp.join('obs', obid)).replace('.png', '.txt').replace(
149
+ '.jpg', '.txt').replace('train',
150
+ 'obs/COSTA_st/train')
151
+ for x in self.img_files
152
+ ]
153
+
154
+ self.nF = len(self.img_files) # number of image files
155
+ self.transforms = T.Compose(
156
+ [T.ToTensor(), T.Normalize(opt.im_mean, opt.im_std)])
157
+ self.use_lab = getattr(opt, 'use_lab', False)
158
+ if not img_size is None:
159
+ self.width = img_size[0]
160
+ self.height = img_size[1]
161
+
162
+ def __getitem__(self, files_index):
163
+ img_path = self.img_files[files_index]
164
+ label_path = self.label_files[files_index]
165
+ return self.get_data(img_path, label_path)
166
+
167
+ def get_data(self, img_path, label_path):
168
+ height = self.height
169
+ width = self.width
170
+ img_ori = cv2.imread(img_path) # BGR
171
+ if img_ori is None:
172
+ raise ValueError('File corrupt {}'.format(img_path))
173
+
174
+ h, w, _ = img_ori.shape
175
+ img, ratio, padw, padh = letterbox(img_ori, height=height, width=width)
176
+
177
+ # Load labels
178
+ if os.path.isfile(label_path):
179
+ labels0 = np.loadtxt(label_path, dtype=np.float32).reshape(-1, 5)
180
+ # Normalized xywh to pixel xyxy format
181
+ labels = labels0.copy()
182
+ labels[:,
183
+ 0] = ratio * w * (labels0[:, 0] - labels0[:, 2] / 2) + padw
184
+ labels[:,
185
+ 1] = ratio * h * (labels0[:, 1] - labels0[:, 3] / 2) + padh
186
+ labels[:,
187
+ 2] = ratio * w * (labels0[:, 0] + labels0[:, 2] / 2) + padw
188
+ labels[:,
189
+ 3] = ratio * h * (labels0[:, 1] + labels0[:, 3] / 2) + padh
190
+ else:
191
+ labels = np.array([])
192
+ nL = len(labels)
193
+ if nL > 0:
194
+ # convert xyxy to xywh
195
+ labels[:, 0:4] = xyxy2xywh(labels[:, 0:4].copy())
196
+ labels[:, 0] /= width
197
+ labels[:, 1] /= height
198
+ labels[:, 2] /= width
199
+ labels[:, 3] /= height
200
+
201
+ if self.use_lab:
202
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
203
+ img = np.array([
204
+ img[:, :, 0],
205
+ ] * 3)
206
+ img = img.transpose(1, 2, 0)
207
+ img = img / 255.
208
+ img = np.ascontiguousarray(img[:, :, ::-1]) # BGR to RGB
209
+ if self.transforms is not None:
210
+ img = self.transforms(img)
211
+
212
+ return img, labels, img_ori, (h, w)
213
+
214
+ def __len__(self):
215
+ return self.nF # number of batches
216
+
217
+
218
+ class LoadImagesAndObsTAO:
219
+ def __init__(self, root, video_meta, obs, opt):
220
+ self.dataroot = root
221
+ self.img_ind = [x['id'] for x in video_meta]
222
+ self.img_files = [x['file_name'] for x in video_meta]
223
+ self.img_files = [osp.join(root, 'frames', x) for x in self.img_files]
224
+ self.obs = [obs.get(x, []) for x in self.img_ind]
225
+ self.use_lab = getattr(opt, 'use_lab', False)
226
+ self.transforms = T.Compose(
227
+ [T.ToTensor(), T.Normalize(opt.im_mean, opt.im_std)])
228
+
229
+ def __getitem__(self, index):
230
+ img_ori = cv2.imread(self.img_files[index])
231
+ if img_ori is None:
232
+ raise ValueError('File corrupt {}'.format(img_path))
233
+
234
+ h, w, _ = img_ori.shape
235
+ img = img_ori
236
+ if self.use_lab:
237
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
238
+ img = np.array([
239
+ img[:, :, 0],
240
+ ] * 3)
241
+ img = img.transpose(1, 2, 0)
242
+ img = img / 255.
243
+ img = np.ascontiguousarray(img[:, :, ::-1]) # BGR to RGB
244
+ if self.transforms is not None:
245
+ img = self.transforms(img)
246
+
247
+ obs = self.obs[index]
248
+ if len(obs) == 0:
249
+ labels = np.array([[0, 0, 1, 1, -1, -1]])
250
+ else:
251
+ boxes = np.array([x.get('bbox', [0, 0, 1, 1]) for x in obs])
252
+ scores = np.array([x.get('score', 0) for x in obs])[:, None]
253
+ cat_ids = np.array([x.get('category_id', -1) for x in obs])[:,
254
+ None]
255
+ labels = np.concatenate([boxes, scores, cat_ids], axis=1)
256
+ if len(labels) > 0:
257
+ # From tlwh to xywh: (x,y) is the box center
258
+ labels[:, 0] = labels[:, 0] + labels[:, 2] / 2
259
+ labels[:, 1] = labels[:, 1] + labels[:, 3] / 2
260
+ labels[:, 0] /= w
261
+ labels[:, 1] /= h
262
+ labels[:, 2] /= w
263
+ labels[:, 3] /= h
264
+
265
+ return img, labels, img_ori, (h, w)
266
+
267
+ def __len__(self):
268
+ return len(self.img_files)
269
+
270
+
271
+ class LoadImagesAndMaskObsVIS:
272
+ def __init__(self, path, info, obs, opt):
273
+ self.dataroot = path
274
+ self.nF = info['length']
275
+ self.img_files = [osp.join(path, p) for p in info['file_names']]
276
+ self.obsbyobj = obs
277
+ self.transforms = T.Compose(
278
+ [T.ToTensor(), T.Normalize(opt.im_mean, opt.im_std)])
279
+ self.use_lab = getattr(opt, 'use_lab', False)
280
+
281
+ def __getitem__(self, idx):
282
+ img_ori = cv2.imread(self.img_files[idx])
283
+ if img_ori is None:
284
+ raise ValueError('File corrupt {}'.format(img_path))
285
+
286
+ h, w, _ = img_ori.shape
287
+ img = img_ori
288
+ if self.use_lab:
289
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
290
+ img = np.array([
291
+ img[:, :, 0],
292
+ ] * 3)
293
+ img = img.transpose(1, 2, 0)
294
+ img = img / 255.
295
+ img = np.ascontiguousarray(img[:, :, ::-1]) # BGR to RGB
296
+ if self.transforms is not None:
297
+ img = self.transforms(img)
298
+
299
+ labels = list()
300
+ for obj in self.obsbyobj:
301
+ RLE = obj['segmentations'][idx]
302
+ if RLE: labels.append(mask_utils.decode(RLE))
303
+ else: labels.append(np.zeros((h, w), dtype=np.uint8))
304
+ labels = np.stack(labels)
305
+
306
+ return img, labels, img_ori, (h, w)
307
+
308
+ def __len__(self):
309
+ return self.nF
310
+
311
+
312
+ class LoadImagesAndMaskObsMOTS(LoadImagesAndObs):
313
+ def __init__(self, path, opt):
314
+ super(LoadImagesAndMaskObsMOTS, self).__init__(path, opt)
315
+
316
+ def get_data(self, img_path, label_path):
317
+ img_ori = cv2.imread(img_path) # BGR
318
+ if img_ori is None:
319
+ raise ValueError('File corrupt {}'.format(img_path))
320
+ h, w, _ = img_ori.shape
321
+
322
+ img = img_ori
323
+ if self.use_lab:
324
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
325
+ img = np.array([
326
+ img[:, :, 0],
327
+ ] * 3)
328
+ img = img.transpose(1, 2, 0)
329
+ img = img / 255.
330
+ img = np.ascontiguousarray(
331
+ img[:, :, ::-1]) # BGR to RGB eg. (1080, 1920, 3)
332
+ if self.transforms is not None:
333
+ img = self.transforms(img)
334
+
335
+ # Load labels
336
+ labels = []
337
+ if os.path.isfile(label_path):
338
+ with open(label_path, 'r') as f:
339
+ for line in f:
340
+ labels.append(line.strip().split())
341
+ nL = len(labels)
342
+ if nL > 0:
343
+ labels = [{'size':(int(h),int(w)), 'counts':m} for \
344
+ _, _,cid,h,w,m in labels if cid=='2']
345
+ labels = [mask_utils.decode(rle) for rle in labels]
346
+ labels = np.stack(labels)
347
+ return img, labels, img_ori, (h, w)
348
+
349
+
350
+ class LoadImagesAndPoseObs(LoadImagesAndObs):
351
+ def __init__(self, obs_jpath, opt):
352
+ fjson = open(obs_jpath, 'r')
353
+ self.infoj = json.load(fjson)['annolist']
354
+ self.dataroot = opt.data_root
355
+ self.nF = len(self.infoj)
356
+ self.img_files = [
357
+ osp.join(opt.data_root, p['image'][0]['name']) for p in self.infoj
358
+ ]
359
+ self.transforms = T.Compose(
360
+ [T.ToTensor(), T.Normalize(opt.im_mean, opt.im_std)])
361
+ self.use_lab = getattr(opt, 'use_lab', False)
362
+
363
+ def __getitem__(self, idx):
364
+ img_ori = cv2.imread(self.img_files[idx])
365
+ if img_ori is None:
366
+ raise ValueError('File corrupt {}'.format(img_path))
367
+
368
+ h, w, _ = img_ori.shape
369
+ img = img_ori
370
+
371
+ if self.use_lab:
372
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
373
+ img = np.array([
374
+ img[:, :, 0],
375
+ ] * 3)
376
+ img = img.transpose(1, 2, 0)
377
+
378
+ img = img / 255.
379
+ img = np.ascontiguousarray(img[:, :, ::-1]) # BGR to RGB
380
+ if self.transforms is not None:
381
+ img = self.transforms(img)
382
+
383
+ info_label = self.infoj[idx]['annorect']
384
+ nobj = len(info_label)
385
+ labels = list()
386
+ labels = [l['annopoints'][0]['point'] for l in info_label]
387
+
388
+ return img, labels, img_ori, (h, w)
389
+
390
+
391
+ def letterbox(
392
+ img,
393
+ height=608,
394
+ width=1088,
395
+ color=(127.5, 127.5,
396
+ 127.5)): # resize a rectangular image to a padded rectangular
397
+ shape = img.shape[:2] # shape = [height, width]
398
+ ratio = min(float(height) / shape[0], float(width) / shape[1])
399
+ new_shape = (round(shape[1] * ratio), round(shape[0] * ratio)
400
+ ) # new_shape = [width, height]
401
+ dw = (width - new_shape[0]) / 2 # width padding
402
+ dh = (height - new_shape[1]) / 2 # height padding
403
+ top, bottom = round(dh - 0.1), round(dh + 0.1)
404
+ left, right = round(dw - 0.1), round(dw + 0.1)
405
+ img = cv2.resize(img, new_shape,
406
+ interpolation=cv2.INTER_AREA) # resized, no border
407
+ img = cv2.copyMakeBorder(img,
408
+ top,
409
+ bottom,
410
+ left,
411
+ right,
412
+ cv2.BORDER_CONSTANT,
413
+ value=color) # padded rectangular
414
+ return img, ratio, dw, dh
OpenPVSG/models/unitrack/eval/mots/Evaluator.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdb
2
+ import sys, os
3
+ sys.path.append(os.getcwd())
4
+ import argparse
5
+
6
+ import traceback
7
+ import time
8
+ import pickle
9
+ import pandas as pd
10
+ import glob
11
+ from os import path
12
+ import numpy as np
13
+
14
+
15
+
16
+ class Evaluator(object):
17
+ """ The `Evaluator` class runs evaluation per sequence and computes the overall performance on the benchmark"""
18
+ def __init__(self):
19
+ pass
20
+
21
+ def run(self, benchmark_name = None , gt_dir = None, res_dir = None, save_pkl = None, eval_mode = "train", seqmaps_dir = "seqmaps"):
22
+ """
23
+ Params
24
+ -----
25
+ benchmark_name: Name of benchmark, e.g. MOT17
26
+ gt_dir: directory of folders with gt data, including the c-files with sequences
27
+ res_dir: directory with result files
28
+ <seq1>.txt
29
+ <seq2>.txt
30
+ ...
31
+ <seq3>.txt
32
+ eval_mode:
33
+ seqmaps_dir:
34
+ seq_file: File name of file containing sequences, e.g. 'c10-train.txt'
35
+ save_pkl: path to output directory for final results
36
+ """
37
+
38
+ start_time = time.time()
39
+
40
+ self.benchmark_gt_dir = gt_dir
41
+ self.seq_file = "{}-{}.txt".format(benchmark_name, eval_mode)
42
+
43
+ res_dir = res_dir
44
+ self.benchmark_name = benchmark_name
45
+ self.seqmaps_dir = seqmaps_dir
46
+
47
+ self.mode = eval_mode
48
+
49
+ self.datadir = os.path.join(gt_dir, self.mode)
50
+
51
+ # getting names of sequences to evaluate
52
+ error_traceback = ""
53
+ assert self.mode in ["train", "test", "all"], "mode: %s not valid " %s
54
+
55
+ print("Evaluating Benchmark: %s" % self.benchmark_name)
56
+
57
+ # ======================================================
58
+ # Handle evaluation
59
+ # ======================================================
60
+
61
+
62
+
63
+ # load list of all sequences
64
+ self.sequences = os.listdir(self.datadir)
65
+
66
+ self.gtfiles = []
67
+ self.tsfiles = []
68
+ for seq in self.sequences:
69
+ gtf = os.path.join(self.benchmark_gt_dir, self.mode ,seq, 'gt/gt.txt')
70
+ if path.exists(gtf): self.gtfiles.append(gtf)
71
+ else: raise Exception("Ground Truth %s missing" % gtf)
72
+ tsf = os.path.join( res_dir, "%s.txt" % seq)
73
+ if path.exists(gtf): self.tsfiles.append(tsf)
74
+ else: raise Exception("Result file %s missing" % tsf)
75
+
76
+
77
+ print('Found {} ground truth files and {} test files.'.format(len(self.gtfiles), len(self.tsfiles)))
78
+ print( self.tsfiles)
79
+
80
+ self.MULTIPROCESSING = False
81
+ MAX_NR_CORES = 10
82
+ # set number of core for mutliprocessing
83
+ if self.MULTIPROCESSING: self.NR_CORES = np.minimum( MAX_NR_CORES, len(self.tsfiles))
84
+ try:
85
+
86
+ """ run evaluation """
87
+ results = self.eval()
88
+
89
+ # calculate overall results
90
+ results_attributes = self.Overall_Results.metrics.keys()
91
+
92
+ for attr in results_attributes:
93
+ """ accumulate evaluation values over all sequences """
94
+ try:
95
+ self.Overall_Results.__dict__[attr] = sum(obj.__dict__[attr] for obj in self.results)
96
+ except:
97
+ pass
98
+ cache_attributes = self.Overall_Results.cache_dict.keys()
99
+ for attr in cache_attributes:
100
+ """ accumulate cache values over all sequences """
101
+ try:
102
+ self.Overall_Results.__dict__[attr] = self.Overall_Results.cache_dict[attr]['func']([obj.__dict__[attr] for obj in self.results])
103
+ except:
104
+ pass
105
+ print("evaluation successful")
106
+
107
+
108
+ # Compute clearmot metrics for overall and all sequences
109
+ for res in self.results:
110
+ res.compute_clearmot()
111
+ self.Overall_Results.compute_clearmot()
112
+
113
+
114
+ self.accumulate_df(type = "mail")
115
+ self.failed = False
116
+ error = None
117
+
118
+
119
+ except Exception as e:
120
+ print(str(traceback.format_exc()))
121
+ print ("<br> Evaluation failed! <br>")
122
+
123
+ error_traceback+= str(traceback.format_exc())
124
+ self.failed = True
125
+ self.summary = None
126
+
127
+ end_time=time.time()
128
+
129
+ self.duration = (end_time - start_time)/60.
130
+
131
+
132
+
133
+ # ======================================================
134
+ # Collect evaluation errors
135
+ # ======================================================
136
+ if self.failed:
137
+
138
+ startExc = error_traceback.split("<exc>")
139
+ error_traceback = [m.split("<!exc>")[0] for m in startExc[1:]]
140
+
141
+ error = ""
142
+
143
+ for err in error_traceback:
144
+ error+="Error: %s" % err
145
+
146
+
147
+ print( "Error Message", error)
148
+ self.error = error
149
+ print("ERROR %s" % error)
150
+
151
+
152
+ print ("Evaluation Finished")
153
+ print("Your Results")
154
+ print(self.render_summary())
155
+ # save results if path set
156
+ if save_pkl:
157
+
158
+
159
+ self.Overall_Results.save_dict(os.path.join( save_pkl, "%s-%s-overall.pkl" % (self.benchmark_name, self.mode)))
160
+ for res in self.results:
161
+ res.save_dict(os.path.join( save_pkl, "%s-%s-%s.pkl" % (self.benchmark_name, self.mode, res.seqName)))
162
+ print("Successfully save results")
163
+
164
+ return self.Overall_Results, self.results
165
+ def eval(self):
166
+ raise NotImplementedError
167
+
168
+
169
+ def accumulate_df(self, type = None):
170
+ """ create accumulated dataframe with all sequences """
171
+ for k, res in enumerate(self.results):
172
+ res.to_dataframe(display_name = True, type = type )
173
+ if k == 0: summary = res.df
174
+ else: summary = summary.append(res.df)
175
+ summary = summary.sort_index()
176
+
177
+
178
+ self.Overall_Results.to_dataframe(display_name = True, type = type )
179
+
180
+ self.summary = summary.append(self.Overall_Results.df)
181
+
182
+
183
+
184
+ def render_summary( self, buf = None):
185
+ """Render metrics summary to console friendly tabular output.
186
+
187
+ Params
188
+ ------
189
+ summary : pd.DataFrame
190
+ Dataframe containing summaries in rows.
191
+
192
+ Kwargs
193
+ ------
194
+ buf : StringIO-like, optional
195
+ Buffer to write to
196
+ formatters : dict, optional
197
+ Dicionary defining custom formatters for individual metrics.
198
+ I.e `{'mota': '{:.2%}'.format}`. You can get preset formatters
199
+ from MetricsHost.formatters
200
+ namemap : dict, optional
201
+ Dictionary defining new metric names for display. I.e
202
+ `{'num_false_positives': 'FP'}`.
203
+
204
+ Returns
205
+ -------
206
+ string
207
+ Formatted string
208
+ """
209
+
210
+ output = self.summary.to_string(
211
+ buf=buf,
212
+ formatters=self.Overall_Results.formatters,
213
+ justify = "left"
214
+ )
215
+
216
+ return output
217
+ def run_metrics( metricObject, args ):
218
+ """ Runs metric for individual sequences
219
+ Params:
220
+ -----
221
+ metricObject: metricObject that has computer_compute_metrics_per_sequence function
222
+ args: dictionary with args for evaluation function
223
+ """
224
+ metricObject.compute_metrics_per_sequence(**args)
225
+ return metricObject
226
+
227
+
228
+ if __name__ == "__main__":
229
+ Evaluator()
OpenPVSG/models/unitrack/eval/mots/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Visual Computing Institute
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
OpenPVSG/models/unitrack/eval/mots/MOTSVisualization.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from Visualize import Visualizer
3
+ from mots_common.io import load_sequences, load_seqmap, load_txt
4
+ import pycocotools.mask as rletools
5
+ import glob
6
+ import os
7
+ import cv2
8
+ import colorsys
9
+ import numpy as np
10
+
11
+ def apply_mask(image, mask, color, alpha=0.5):
12
+ """
13
+ Apply the given mask to the image.
14
+ """
15
+ for c in range(3):
16
+ image[:, :, c] = np.where(mask == 1, image[:, :, c] * (1 - alpha) + alpha * color[c],image[:, :, c])
17
+ return image
18
+
19
+
20
+ class MOTSVisualizer(Visualizer):
21
+
22
+ def load(self, FilePath):
23
+ return load_txt(FilePath)
24
+
25
+
26
+
27
+ def drawResults(self, im = None, t = 0):
28
+ self.draw_boxes = False
29
+
30
+
31
+ for obj in self.resFile[t]:
32
+
33
+ color = self.colors[obj.track_id % len(self.colors)]
34
+
35
+ color = tuple([int(c*255) for c in color])
36
+
37
+
38
+ if obj.class_id == 1:
39
+ category_name = "Car"
40
+ elif obj.class_id == 2:
41
+ category_name = "Ped"
42
+ else:
43
+ category_name = "Ignore"
44
+ color = (0.7*255, 0.7*255, 0.7*255)
45
+
46
+ if obj.class_id == 1 or obj.class_id == 2: # Don't show boxes or ids for ignore regions
47
+ x, y, w, h = rletools.toBbox(obj.mask)
48
+
49
+ pt1=(int(x),int(y))
50
+ pt2=(int(x+w),int(y+h))
51
+
52
+ category_name += ":" + str(obj.track_id)
53
+ cv2.putText(im, category_name, (int(x + 0.5 * w), int( y + 0.5 * h)), cv2.FONT_HERSHEY_TRIPLEX,self.imScale,color,thickness =2)
54
+ if self.draw_boxes:
55
+ cv2.rectangle(im,pt1,pt2,color,2)
56
+
57
+
58
+ binary_mask = rletools.decode(obj.mask)
59
+
60
+ im = apply_mask(im, binary_mask, color)
61
+ return im
62
+
63
+ if __name__ == "__main__":
64
+ visualizer = MOTSVisualizer(
65
+ seqName = "MOTS20-11",
66
+ FilePath ="data/MOTS/train/MOTS20-11/gt/gt.txt",
67
+ image_dir = "data/MOTS/train/MOTS20-11/img1",
68
+ mode = "gt",
69
+ output_dir = "vid")
70
+
71
+ visualizer.generateVideo(
72
+ displayTime = True,
73
+ displayName = "seg",
74
+ showOccluder = True,
75
+ fps = 25 )
OpenPVSG/models/unitrack/eval/mots/MOTS_metrics.py ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections import defaultdict
3
+ import pycocotools.mask as rletools
4
+ from mots_common.io import SegmentedObject
5
+ from mots_common.io import load_seqmap, load_sequences, load_txt
6
+ from Metrics import Metrics
7
+ import os, sys
8
+ import numpy as np
9
+ from scipy.optimize import linear_sum_assignment as linear_assignment
10
+
11
+ # we only consider pedestrians
12
+ IGNORE_CLASS = 10
13
+ CLASS_ID = 2
14
+
15
+
16
+
17
+ def mask_iou(a, b, criterion="union"):
18
+ is_crowd = criterion != "union"
19
+ return rletools.iou([a.mask], [b.mask], [is_crowd])[0][0]
20
+
21
+
22
+
23
+
24
+ class MOTSMetrics(Metrics):
25
+ def __init__(self, seqName = None):
26
+ super().__init__()
27
+ if seqName:
28
+ self.seqName = seqName
29
+ else: self.seqName = 0
30
+ # Evaluation metrics
31
+
32
+ self.register(name = "sMOTSA", formatter='{:.2f}'.format)
33
+ self.register(name = "MOTSA", formatter='{:.2f}'.format)
34
+ self.register(name = "MOTSP", formatter='{:.2f}'.format)
35
+ self.register(name = "MOTSAL", formatter='{:.2f}'.format, write_mail = False)
36
+ self.register(name = "MODSA", formatter='{:.2f}'.format, write_mail = False)
37
+ self.register(name = "MODSP", formatter='{:.2f}'.format, write_mail = False)
38
+
39
+
40
+ self.register(name = "IDF1", formatter='{:.2f}'.format)
41
+ self.register(name = "IDTP", formatter='{:.2f}'.format, write_mail = False)
42
+
43
+
44
+ self.register(name = "MT", formatter='{:.0f}'.format)
45
+ self.register(name = "PT", formatter='{:.0f}'.format, write_mail = False )
46
+ self.register(name = "ML", formatter='{:.0f}'.format)
47
+
48
+ self.register(name = "MTR", formatter='{:.2f}'.format)
49
+ self.register(name = "PTR", formatter='{:.2f}'.format)
50
+ self.register(name = "MLR", formatter='{:.2f}'.format)
51
+
52
+
53
+ self.register(name = "n_gt_trajectories", display_name = "GT",formatter='{:.0f}'.format, write_mail = True)
54
+
55
+ self.register(name = "tp", display_name="TP", formatter='{:.0f}'.format) # number of true positives
56
+ self.register(name = "fp", display_name="FP", formatter='{:.0f}'.format) # number of false positives
57
+ self.register(name = "fn", display_name="FN", formatter='{:.0f}'.format) # number of false negatives
58
+
59
+ self.register(name = "recall", display_name="Rcll", formatter='{:.2f}'.format)
60
+ self.register(name = "precision", display_name="Prcn", formatter='{:.2f}'.format)
61
+
62
+ self.register(name = "F1", display_name="F1", formatter='{:.2f}'.format, write_mail = False)
63
+ self.register(name = "FAR", formatter='{:.2f}'.format, write_mail = False)
64
+ self.register(name = "total_cost", display_name="COST", formatter='{:.0f}'.format, write_mail = False)
65
+ self.register(name = "fragments", display_name="FM", formatter='{:.0f}'.format)
66
+ self.register(name = "fragments_rel", display_name="FMR", formatter='{:.2f}'.format)
67
+ self.register(name = "id_switches", display_name="IDSW", formatter='{:.0f}'.format)
68
+
69
+ self.register(name = "id_switches_rel", display_name="IDSWR", formatter='{:.1f}'.format)
70
+
71
+ self.register(name = "n_tr_trajectories", display_name = "TR", formatter='{:.0f}'.format, write_mail = False)
72
+ self.register(name = "total_num_frames", display_name="TOTAL_NUM", formatter='{:.0f}'.format, write_mail = False)
73
+
74
+
75
+ self.register(name = "n_gt", display_name = "GT_OBJ", formatter='{:.0f}'.format, write_mail = False) # number of ground truth detections
76
+ self.register(name = "n_tr", display_name = "TR_OBJ", formatter='{:.0f}'.format, write_mail = False) # number of tracker detections minus ignored tracker detections
77
+ self.register(name = "n_itr",display_name="IGNORED", formatter='{:.0f}'.format, write_mail = False) # number of ignored tracker detections
78
+ self.register(name = "id_n_tr", display_name = "ID_TR_OBJ", formatter='{:.0f}'.format, write_mail = False)
79
+ self.register(name = "nbox_gt", display_name = "NBOX_GT", formatter='{:.0f}'.format, write_mail = False)
80
+
81
+
82
+
83
+
84
+
85
+ def compute_clearmot(self):
86
+ # precision/recall etc.
87
+ if (self.fp + self.tp) == 0 or (self.tp + self.fn) == 0:
88
+ self.recall = 0.
89
+ self.precision = 0.
90
+ else:
91
+ self.recall = self.tp / float(self.tp + self.fn) * 100.
92
+ self.precision = self.tp / float(self.fp + self.tp) * 100.
93
+ if (self.recall + self.precision) == 0:
94
+ self.F1 = 0.
95
+ else:
96
+ self.F1 = (2. * (self.precision * self.recall) / (self.precision + self.recall) ) * 100.
97
+ if self.total_num_frames == 0:
98
+ self.FAR = "n/a"
99
+ else:
100
+ self.FAR = (self.fp / float(self.total_num_frames) )
101
+ # compute CLEARMOT
102
+ if self.n_gt == 0:
103
+ self.MOTSA = -float("inf")
104
+ self.MODSA = -float("inf")
105
+ self.sMOTSA = -float("inf")
106
+ else:
107
+ self.MOTSA = (1 - (self.fn + self.fp + self.id_switches) / float(self.n_gt) ) * 100.
108
+ self.MODSA = (1 - (self.fn + self.fp) / float(self.n_gt)) * 100.
109
+ self.sMOTSA = ((self.total_cost - self.fp - self.id_switches) / float(self.n_gt)) * 100.
110
+ if self.tp == 0:
111
+ self.MOTSP = float("inf")
112
+ else:
113
+ self.MOTSP = self.total_cost / float(self.tp) * 100.
114
+ if self.n_gt != 0:
115
+ if self.id_switches == 0:
116
+ self.MOTSAL = (1 - (self.fn + self.fp + self.id_switches) / float(self.n_gt)) * 100.
117
+ else:
118
+ self.MOTSAL = (1 - (self.fn + self.fp + math.log10(self.id_switches)) / float(
119
+ self.n_gt))*100.
120
+ else:
121
+ self.MOTSAL = -float("inf")
122
+
123
+ if self.total_num_frames == 0:
124
+ self.MODSP = "n/a"
125
+ else:
126
+ self.MODSP = self.MODSP / float(self.total_num_frames) * 100.
127
+
128
+
129
+
130
+
131
+ if self.n_gt_trajectories == 0:
132
+ self.MTR = 0.
133
+ self.PTR = 0.
134
+ self.MLR = 0.
135
+ else:
136
+ self.MTR = self.MT * 100. / float(self.n_gt_trajectories)
137
+ self.PTR = self.PT * 100. / float(self.n_gt_trajectories)
138
+ self.MLR = self.ML * 100. / float(self.n_gt_trajectories)
139
+
140
+
141
+ # calculate relative IDSW and FM
142
+
143
+ if self.recall != 0:
144
+ self.id_switches_rel = self.id_switches/self.recall*100
145
+ self.fragments_rel = self.fragments/self.recall* 100
146
+
147
+ else:
148
+ self.id_switches_rel = float("inf")
149
+ self.fragments_rel = float("inf")
150
+
151
+
152
+
153
+
154
+ # IDF1
155
+ if self.n_gt_trajectories == 0:
156
+ self.IDF1 = 0.
157
+ else:
158
+ self.IDF1 = (2 * self.IDTP) / (self.nbox_gt + self.id_n_tr) * 100.
159
+ return self
160
+
161
+
162
+
163
+
164
+ # go through all frames and associate ground truth and tracker results
165
+
166
+ def compute_metrics_per_sequence(self, sequence, pred_file, gt_file, gtDataDir, benchmark_name,
167
+ ignore_class = IGNORE_CLASS, class_id = CLASS_ID, overlap_function = mask_iou):
168
+
169
+ gt_seq = load_txt(gt_file)
170
+ results_seq = load_txt(pred_file)
171
+
172
+
173
+ # load information about sequence
174
+ import configparser
175
+ config = configparser.ConfigParser()
176
+
177
+
178
+ config.read(os.path.join(gtDataDir, "seqinfo.ini"))
179
+
180
+ max_frames = int(config['Sequence']["seqlength"])
181
+
182
+ self.total_num_frames = max_frames + 1
183
+
184
+ seq_trajectories = defaultdict(list)
185
+
186
+ # To count number of track ids
187
+ gt_track_ids = set()
188
+ tr_track_ids = set()
189
+
190
+ # Statistics over the current sequence
191
+ seqtp = 0
192
+ seqfn = 0
193
+ seqfp = 0
194
+ seqitr = 0
195
+
196
+ n_gts = 0
197
+ n_trs = 0
198
+
199
+ frame_to_ignore_region = {}
200
+
201
+ # Iterate over frames in this sequence
202
+ for f in range(max_frames + 1):
203
+ g = []
204
+ dc = []
205
+ t = []
206
+
207
+ if f in gt_seq:
208
+ for obj in gt_seq[f]:
209
+ if obj.class_id == ignore_class:
210
+ dc.append(obj)
211
+ elif obj.class_id == class_id:
212
+ g.append(obj)
213
+ gt_track_ids.add(obj.track_id)
214
+ if f in results_seq:
215
+ for obj in results_seq[f]:
216
+ if obj.class_id == class_id:
217
+ t.append(obj)
218
+ tr_track_ids.add(obj.track_id)
219
+
220
+ # Handle ignore regions as one large ignore region
221
+ dc = SegmentedObject(mask=rletools.merge([d.mask for d in dc], intersect=False),
222
+ class_id=ignore_class, track_id=ignore_class)
223
+ frame_to_ignore_region[f] = dc
224
+
225
+ tracks_valid = [False for _ in range(len(t))]
226
+
227
+ # counting total number of ground truth and tracker objects
228
+ self.n_gt += len(g)
229
+ self.n_tr += len(t)
230
+
231
+ n_gts += len(g)
232
+ n_trs += len(t)
233
+
234
+ # tmp variables for sanity checks and MODSP computation
235
+ tmptp = 0
236
+ tmpfp = 0
237
+ tmpfn = 0
238
+ tmpc = 0 # this will sum up the overlaps for all true positives
239
+ tmpcs = [0] * len(g) # this will save the overlaps for all true positives
240
+ # the reason is that some true positives might be ignored
241
+ # later such that the corrsponding overlaps can
242
+ # be subtracted from tmpc for MODSP computation
243
+
244
+ # To associate, simply take for each ground truth the (unique!) detection with IoU>0.5 if it exists
245
+
246
+ # all ground truth trajectories are initially not associated
247
+ # extend groundtruth trajectories lists (merge lists)
248
+ for gg in g:
249
+ seq_trajectories[gg.track_id].append(-1)
250
+ num_associations = 0
251
+ for row, gg in enumerate(g):
252
+ for col, tt in enumerate(t):
253
+ c = overlap_function(gg, tt)
254
+ if c > 0.5:
255
+ tracks_valid[col] = True
256
+ self.total_cost += c
257
+ tmpc += c
258
+ tmpcs[row] = c
259
+ seq_trajectories[g[row].track_id][-1] = t[col].track_id
260
+
261
+ # true positives are only valid associations
262
+ self.tp += 1
263
+ tmptp += 1
264
+
265
+ num_associations += 1
266
+
267
+ # associate tracker and DontCare areas
268
+ # ignore tracker in neighboring classes
269
+ nignoredtracker = 0 # number of ignored tracker detections
270
+
271
+ for i, tt in enumerate(t):
272
+ overlap = overlap_function(tt, dc, "a")
273
+ if overlap > 0.5 and not tracks_valid[i]:
274
+ nignoredtracker += 1
275
+
276
+ # count the number of ignored tracker objects
277
+ self.n_itr += nignoredtracker
278
+
279
+ # false negatives = non-associated gt instances
280
+ #
281
+ tmpfn += len(g) - num_associations
282
+ self.fn += len(g) - num_associations
283
+
284
+ # false positives = tracker instances - associated tracker instances
285
+ # mismatches (mme_t)
286
+ tmpfp += len(t) - tmptp - nignoredtracker
287
+ self.fp += len(t) - tmptp - nignoredtracker
288
+ # tmpfp = len(t) - tmptp - nignoredtp # == len(t) - (tp - ignoredtp) - ignoredtp
289
+ # self.fp += len(t) - tmptp - nignoredtp
290
+
291
+ # update sequence data
292
+ seqtp += tmptp
293
+ seqfp += tmpfp
294
+ seqfn += tmpfn
295
+ seqitr += nignoredtracker
296
+
297
+ # sanity checks
298
+ # - the number of true positives minues ignored true positives
299
+ # should be greater or equal to 0
300
+ # - the number of false negatives should be greater or equal to 0
301
+ # - the number of false positives needs to be greater or equal to 0
302
+ # otherwise ignored detections might be counted double
303
+ # - the number of counted true positives (plus ignored ones)
304
+ # and the number of counted false negatives (plus ignored ones)
305
+ # should match the total number of ground truth objects
306
+ # - the number of counted true positives (plus ignored ones)
307
+ # and the number of counted false positives
308
+ # plus the number of ignored tracker detections should
309
+ # match the total number of tracker detections
310
+ if tmptp < 0:
311
+ print(tmptp)
312
+ raise NameError("Something went wrong! TP is negative")
313
+ if tmpfn < 0:
314
+ print(tmpfn, len(g), num_associations)
315
+ raise NameError("Something went wrong! FN is negative")
316
+ if tmpfp < 0:
317
+ print(tmpfp, len(t), tmptp, nignoredtracker)
318
+ raise NameError("Something went wrong! FP is negative")
319
+ if tmptp + tmpfn != len(g):
320
+ print("seqname", seq_name)
321
+ print("frame ", f)
322
+ print("TP ", tmptp)
323
+ print("FN ", tmpfn)
324
+ print("FP ", tmpfp)
325
+ print("nGT ", len(g))
326
+ print("nAss ", num_associations)
327
+ raise NameError("Something went wrong! nGroundtruth is not TP+FN")
328
+ if tmptp + tmpfp + nignoredtracker != len(t):
329
+ print(seq_name, f, len(t), tmptp, tmpfp)
330
+ print(num_associations)
331
+ raise NameError("Something went wrong! nTracker is not TP+FP")
332
+
333
+ # compute MODSP
334
+ MODSP_f = 1
335
+ if tmptp != 0:
336
+ MODSP_f = tmpc / float(tmptp)
337
+ self.MODSP += MODSP_f
338
+
339
+ assert len(seq_trajectories) == len(gt_track_ids)
340
+ self.n_gt_trajectories = len(gt_track_ids)
341
+ self.n_tr_trajectories = len(tr_track_ids)
342
+
343
+ # compute MT/PT/ML, fragments, idswitches for all groundtruth trajectories
344
+ if len(seq_trajectories) != 0:
345
+ for g in seq_trajectories.values():
346
+ # all frames of this gt trajectory are not assigned to any detections
347
+ if all([this == -1 for this in g]):
348
+ self.ML += 1
349
+ continue
350
+ # compute tracked frames in trajectory
351
+ last_id = g[0]
352
+ # first detection (necessary to be in gt_trajectories) is always tracked
353
+ tracked = 1 if g[0] >= 0 else 0
354
+ for f in range(1, len(g)):
355
+ if last_id != g[f] and last_id != -1 and g[f] != -1:
356
+ self.id_switches += 1
357
+ if f < len(g) - 1 and g[f - 1] != g[f] and last_id != -1 and g[f] != -1 and g[f + 1] != -1:
358
+ self.fragments += 1
359
+ if g[f] != -1:
360
+ tracked += 1
361
+ last_id = g[f]
362
+ # handle last frame; tracked state is handled in for loop (g[f]!=-1)
363
+ if len(g) > 1 and g[f - 1] != g[f] and last_id != -1 and g[f] != -1:
364
+ self.fragments += 1
365
+
366
+ # compute MT/PT/ML
367
+ tracking_ratio = tracked / float(len(g))
368
+ if tracking_ratio > 0.8:
369
+ self.MT += 1
370
+ elif tracking_ratio < 0.2:
371
+ self.ML += 1
372
+ else: # 0.2 <= tracking_ratio <= 0.8
373
+ self.PT += 1
374
+
375
+ # compute IDF1
376
+ idf1, idtp, nbox_gt, id_n_tr = compute_idf1_and_idtp_for_sequence(gt_seq, results_seq, gt_track_ids, tr_track_ids, frame_to_ignore_region)
377
+ self.IDTP = idtp
378
+ #self.id_ign = id_ign
379
+ self.id_n_tr = id_n_tr
380
+ self.nbox_gt = nbox_gt
381
+
382
+ return self
383
+
384
+
385
+
386
+ ### IDF1 stuff
387
+ ### code below adapted from https://github.com/shenh10/mot_evaluation/blob/5dd51e5cb7b45992774ea150e4386aa0b02b586f/utils/measurements.py
388
+ def compute_idf1_and_idtp_for_sequence(frame_to_gt, frame_to_pred, gt_ids, st_ids, frame_to_ignore_region):
389
+ frame_to_can_be_ignored = {}
390
+ for t in frame_to_pred.keys():
391
+ preds_t = frame_to_pred[t]
392
+ pred_masks_t = [p.mask for p in preds_t]
393
+ ignore_region_t = frame_to_ignore_region[t].mask
394
+ overlap = np.squeeze(rletools.iou(pred_masks_t, [ignore_region_t], [1]), axis=1)
395
+ frame_to_can_be_ignored[t] = overlap > 0.5
396
+
397
+ gt_ids = sorted(gt_ids)
398
+ st_ids = sorted(st_ids)
399
+ groundtruth = [[] for _ in gt_ids]
400
+ prediction = [[] for _ in st_ids]
401
+ for t, gts_t in frame_to_gt.items():
402
+ for gt_t in gts_t:
403
+ if gt_t.track_id in gt_ids:
404
+ groundtruth[gt_ids.index(gt_t.track_id)].append((t, gt_t))
405
+ for t in frame_to_pred.keys():
406
+ preds_t = frame_to_pred[t]
407
+ can_be_ignored_t = frame_to_can_be_ignored[t]
408
+ assert len(preds_t) == len(can_be_ignored_t)
409
+ for pred_t, ign_t in zip(preds_t, can_be_ignored_t):
410
+ if pred_t.track_id in st_ids:
411
+ prediction[st_ids.index(pred_t.track_id)].append((t, pred_t, ign_t))
412
+ for gt in groundtruth:
413
+ gt.sort(key=lambda x: x[0])
414
+ for pred in prediction:
415
+ pred.sort(key=lambda x: x[0])
416
+
417
+ n_gt = len(gt_ids)
418
+ n_st = len(st_ids)
419
+ cost = np.zeros((n_gt + n_st, n_st + n_gt), dtype=float)
420
+ cost[n_gt:, :n_st] = sys.maxsize # float('inf')
421
+ cost[:n_gt, n_st:] = sys.maxsize # float('inf')
422
+
423
+ fp = np.zeros(cost.shape)
424
+ fn = np.zeros(cost.shape)
425
+ ign = np.zeros(cost.shape)
426
+ # cost matrix of all trajectory pairs
427
+ cost_block, fp_block, fn_block, ign_block = cost_between_gt_pred(groundtruth, prediction)
428
+ cost[:n_gt, :n_st] = cost_block
429
+ fp[:n_gt, :n_st] = fp_block
430
+ fn[:n_gt, :n_st] = fn_block
431
+ ign[:n_gt, :n_st] = ign_block
432
+
433
+ # computed trajectory match no groundtruth trajectory, FP
434
+ for i in range(n_st):
435
+ #cost[i + n_gt, i] = prediction[i].shape[0]
436
+ #fp[i + n_gt, i] = prediction[i].shape[0]
437
+ # don't count fp in case of ignore region
438
+ fps = sum([~x[2] for x in prediction[i]])
439
+ ig = sum([x[2] for x in prediction[i]])
440
+ cost[i + n_gt, i] = fps
441
+ fp[i + n_gt, i] = fps
442
+ ign[i + n_gt, i] = ig
443
+
444
+ # groundtruth trajectory match no computed trajectory, FN
445
+ for i in range(n_gt):
446
+ #cost[i, i + n_st] = groundtruth[i].shape[0]
447
+ #fn[i, i + n_st] = groundtruth[i].shape[0]
448
+ cost[i, i + n_st] = len(groundtruth[i])
449
+ fn[i, i + n_st] = len(groundtruth[i])
450
+ # TODO: add error handling here?
451
+ matched_indices = linear_assignment(cost)
452
+ #nbox_gt = sum([groundtruth[i].shape[0] for i in range(n_gt)])
453
+ #nbox_st = sum([prediction[i].shape[0] for i in range(n_st)])
454
+ nbox_gt = sum([len(groundtruth[i]) for i in range(n_gt)])
455
+
456
+ nbox_st = sum([len(prediction[i]) for i in range(n_st)])
457
+
458
+ #IDFP = 0
459
+ IDFN = 0
460
+ id_ign = 0
461
+ for matched in zip(*matched_indices):
462
+ #IDFP += fp[matched[0], matched[1]]
463
+ IDFN += fn[matched[0], matched[1]]
464
+ # exclude detections which are not matched and ignored from total count
465
+ id_ign += ign[matched[0], matched[1]]
466
+ id_n_tr = nbox_st - id_ign
467
+
468
+ IDTP = nbox_gt - IDFN
469
+
470
+ IDF1 = 2 * IDTP / (nbox_gt + id_n_tr)
471
+
472
+ return IDF1, IDTP, nbox_gt, id_n_tr
473
+
474
+
475
+
476
+
477
+ def cost_between_gt_pred(groundtruth, prediction):
478
+ n_gt = len(groundtruth)
479
+ n_st = len(prediction)
480
+ cost = np.zeros((n_gt, n_st), dtype=float)
481
+ fp = np.zeros((n_gt, n_st), dtype=float)
482
+ fn = np.zeros((n_gt, n_st), dtype=float)
483
+ ign = np.zeros((n_gt, n_st), dtype=float)
484
+ for i in range(n_gt):
485
+ for j in range(n_st):
486
+ fp[i, j], fn[i, j], ign[i, j] = cost_between_trajectories(groundtruth[i], prediction[j])
487
+ cost[i, j] = fp[i, j] + fn[i, j]
488
+ return cost, fp, fn, ign
489
+
490
+
491
+ def cost_between_trajectories(traj1, traj2):
492
+ #[npoints1, dim1] = traj1.shape
493
+ #[npoints2, dim2] = traj2.shape
494
+ npoints1 = len(traj1)
495
+ npoints2 = len(traj2)
496
+ # find start and end frame of each trajectories
497
+ #start1 = traj1[0, 0]
498
+ #end1 = traj1[-1, 0]
499
+ #start2 = traj2[0, 0]
500
+ #end2 = traj2[-1, 0]
501
+ times1 = [x[0] for x in traj1]
502
+ times2 = [x[0] for x in traj2]
503
+ start1 = min(times1)
504
+ start2 = min(times2)
505
+ end1 = max(times1)
506
+ end2 = max(times2)
507
+
508
+ ign = [traj2[i][2] for i in range(npoints2)]
509
+
510
+ # check frame overlap
511
+ #has_overlap = max(start1, start2) < min(end1, end2)
512
+ # careful, changed this to <=, but I think now it's right
513
+ has_overlap = max(start1, start2) <= min(end1, end2)
514
+ if not has_overlap:
515
+ fn = npoints1
516
+ #fp = npoints2
517
+ # disregard detections which can be ignored
518
+ fp = sum([~x for x in ign])
519
+ ig = sum(ign)
520
+ return fp, fn, ig
521
+
522
+ # gt trajectory mapping to st, check gt missed
523
+ matched_pos1 = corresponding_frame(times1, npoints1, times2, npoints2)
524
+ # st trajectory mapping to gt, check computed one false alarms
525
+ matched_pos2 = corresponding_frame(times2, npoints2, times1, npoints1)
526
+ overlap1 = compute_overlap(traj1, traj2, matched_pos1)
527
+ overlap2 = compute_overlap(traj2, traj1, matched_pos2)
528
+ # FN
529
+ fn = sum([1 for i in range(npoints1) if overlap1[i] < 0.5])
530
+ # FP
531
+ # don't count false positive in case of ignore region
532
+ unmatched = [overlap2[i] < 0.5 for i in range(npoints2)]
533
+ #fp = sum([1 for i in range(npoints2) if overlap2[i] < 0.5 and not traj2[i][2]])
534
+ fp = sum([1 for i in range(npoints2) if unmatched[i] and not ign[i]])
535
+ ig = sum([1 for i in range(npoints2) if unmatched[i] and ign[i]])
536
+ return fp, fn, ig
537
+
538
+
539
+ def corresponding_frame(traj1, len1, traj2, len2):
540
+ """
541
+ Find the matching position in traj2 regarding to traj1
542
+ Assume both trajectories in ascending frame ID
543
+ """
544
+ p1, p2 = 0, 0
545
+ loc = -1 * np.ones((len1,), dtype=int)
546
+ while p1 < len1 and p2 < len2:
547
+ if traj1[p1] < traj2[p2]:
548
+ loc[p1] = -1
549
+ p1 += 1
550
+ elif traj1[p1] == traj2[p2]:
551
+ loc[p1] = p2
552
+ p1 += 1
553
+ p2 += 1
554
+ else:
555
+ p2 += 1
556
+ return loc
557
+
558
+
559
+ def compute_overlap(traj1, traj2, matched_pos):
560
+ """
561
+ Compute the loss hit in traj2 regarding to traj1
562
+ """
563
+ overlap = np.zeros((len(matched_pos),), dtype=float)
564
+ for i in range(len(matched_pos)):
565
+ if matched_pos[i] == -1:
566
+ continue
567
+ else:
568
+ mask1 = traj1[i][1].mask
569
+ mask2 = traj2[matched_pos[i]][1].mask
570
+ iou = rletools.iou([mask1], [mask2], [False])[0][0]
571
+ overlap[i] = iou
572
+ return overlap
573
+
OpenPVSG/models/unitrack/eval/mots/Metrics.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import division
2
+ from collections import OrderedDict, Iterable
3
+ import pandas as pd
4
+ import numpy as np
5
+ import pickle
6
+
7
+ class Metrics(object):
8
+ def __init__(self):
9
+ self.metrics = OrderedDict()
10
+ self.cache_dict = OrderedDict()
11
+
12
+
13
+ def register(self, name=None, value=None, formatter=None,
14
+ display_name=None, write_db = True, write_mail = True):
15
+ """Register a new metric.
16
+ Params
17
+ ------
18
+ name: str
19
+ Name of the metric. Name is used for computation and set as attribute.
20
+ display_name: str or None
21
+ Disoplay name of variable written in db and mail
22
+ value:
23
+ formatter:
24
+ Formatter to present value of metric. E.g. `'{:.2f}'.format`
25
+ write_db: boolean, default = True
26
+ Write value into db
27
+ write_mail: boolean, default = True
28
+ Write metric in result mail to user
29
+ """
30
+ assert not name is None, 'No name specified'.format(name)
31
+
32
+ if not value:
33
+ value = 0
34
+
35
+ self.__setattr__( name, value)
36
+
37
+ if not display_name: display_name = name
38
+ self.metrics[name] = {
39
+ 'name' : name,
40
+ 'write_db' : write_db,
41
+ 'formatter' : formatter,
42
+ 'write_mail' : write_mail,
43
+ 'display_name' : display_name
44
+ }
45
+
46
+ def cache(self, name=None, value=None, func=None):
47
+ assert not name is None, 'No name specified'.format(name)
48
+
49
+
50
+ self.__setattr__( name, value)
51
+
52
+
53
+ self.cache_dict[name] = {
54
+ 'name' : name,
55
+ 'func' : func
56
+ }
57
+
58
+
59
+
60
+ def __call__(self, name):
61
+ return self.metrics[name]
62
+
63
+ @property
64
+ def names(self):
65
+ """Returns the name identifiers of all registered metrics."""
66
+ return [v['name'] for v in self.metrics.values()]
67
+
68
+ @property
69
+ def display_names(self):
70
+ """Returns the display name identifiers of all registered metrics."""
71
+ return [v['display_name'] for v in self.metrics.values()]
72
+
73
+
74
+ @property
75
+ def formatters(self):
76
+ """Returns the formatters for all metrics that have associated formatters."""
77
+ return dict([(v['display_name'], v['formatter']) for k, v in self.metrics.items() if not v['formatter'] is None])
78
+
79
+ #@property
80
+ def val_dict(self, display_name = False, object = "metrics"):
81
+ """Returns dictionary of all registered values of object name or display_name as key.
82
+ Params
83
+ ------
84
+
85
+ display_name: boolean, default = False
86
+ If True, display_name of keys in dict. (default names)
87
+ object: "cache" or "metrics", default = "metrics"
88
+ """
89
+ if display_name: key_string = "display_name"
90
+ else: key_string = "name"
91
+ print("object dict: ", object)
92
+ val_dict = dict([(self.__getattribute__(object)[key][key_string], self.__getattribute__(key)) for key in self.__getattribute__(object).keys() ])
93
+ return val_dict
94
+
95
+ def val_db(self, display_name = True):
96
+ """Returns dictionary of all registered values metrics to write in db."""
97
+ if display_name: key_string = "display_name"
98
+ else: key_string = "name"
99
+ val_dict = dict([(self.metrics[key][key_string], self.__getattribute__(key)) for key in self.metrics.keys() if self.metrics[key]["write_db"] ])
100
+ return val_dict
101
+
102
+
103
+ def val_mail(self, display_name = True):
104
+ """Returns dictionary of all registered values metrics to write in mail."""
105
+ if display_name: key_string = "display_name"
106
+ else: key_string = "name"
107
+ val_dict = dict([(self.metrics[key][key_string], self.__getattribute__(key)) for key in self.metrics.keys() if self.metrics[key]["write_mail"] ])
108
+ return val_dict
109
+
110
+
111
+ def to_dataframe(self, display_name = False, type = None):
112
+ """Returns pandas dataframe of all registered values metrics. """
113
+ if type=="mail":
114
+ self.df = pd.DataFrame(self.val_mail(display_name = display_name), index=[self.seqName])
115
+ else:
116
+ self.df = pd.DataFrame(self.val_dict(display_name = display_name), index=[self.seqName])
117
+ def update_values(self, value_dict = None):
118
+ """Updates registered metrics with new values in value_dict. """
119
+ if value_dict:
120
+ for key, value in value_dict.items() :
121
+ if hasattr(self, key):
122
+ self.__setattr__(key, value)
123
+
124
+
125
+ def print_type(self, object = "metrics"):
126
+ """Prints variable type of registered metrics or caches. """
127
+ print( "OBJECT " , object)
128
+ val_dict = self.val_dict(object = object)
129
+ for key, item in val_dict.items() :
130
+ print("%s: %s; Shape: %s" %(key, type(item), np.shape(item)))
131
+
132
+ def print_results(self):
133
+ """Prints metrics. """
134
+ result_dict = self.val_dict()
135
+ for key, item in result_dict.items():
136
+ print(key)
137
+ print("%s: %s" %(key, self.metrics[key]["formatter"](item)))
138
+
139
+
140
+ def save_dict(self, path):
141
+ """Save value dict to path as pickle file."""
142
+ with open(path, 'wb') as handle:
143
+ pickle.dump(self.__dict__, handle, protocol=pickle.HIGHEST_PROTOCOL)
144
+
145
+
146
+ def compute_metrics_per_sequence(self):
147
+ raise NotImplementedError
148
+
149
+
OpenPVSG/models/unitrack/eval/mots/README.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MOTS
2
+ ![MOTS_PIC](https://motchallenge.net/sequenceVideos/MOTS20-11-gt.jpg)
3
+
4
+ ## Requirements
5
+ * Python 3.6.9
6
+ * install [requirements.txt](requirements.txt)
7
+
8
+ ## Usage
9
+ 1) Run
10
+ ```
11
+ python MOTS/evalMOTS.py
12
+ ```
13
+
14
+
15
+
16
+ ## Evaluation
17
+ To run the evaluation for your method please adjust the file ```MOTS/evalMOTS.py``` using the following arguments:
18
+
19
+ ```benchmark_name```: Name of the benchmark, e.g. MOTS
20
+ ```gt_dir```: Directory containing ground truth files in ```<gt_dir>/<sequence>/gt/gt.txt```
21
+ ```res_dir```: The folder containing the tracking results. Each one should be saved in a separate .txt file with the name of the respective sequence (see ./res/data)
22
+ ```save_pkl```: path to output directory for final results (pickle) (default: False)
23
+ ```eval_mode```: Mode of evaluation out of ```["train", "test", "all"]``` (default : "train")
24
+
25
+ ```
26
+ eval.run(
27
+ benchmark_name = benchmark_name,
28
+ seq_file = seq_file,
29
+ gt_dir = gt_dir,
30
+ res_dir = res_dir
31
+ )
32
+ ```
33
+ ## Visualization
34
+ To visualize your results or the annotations run
35
+ <code>
36
+ python MOTS/MOTSVisualization.py
37
+ </code>
38
+
39
+ Inside the script adjust the following values for the ```MOTSVisualizer``` class:
40
+
41
+ ```seqName```: Name of the sequence
42
+ ```FilePath```: Data file
43
+ ```image_dir```: Directory containing images
44
+ ```mode```: Video mode. Options: ```None``` for method results, ```raw``` for data video only, and ```gt``` for annotations
45
+ ```output_dir```: Directory for created video and thumbnail images
46
+
47
+ Additionally, adjust the following values for the ```generateVideo``` function:
48
+
49
+ ```displayTime```: If true, display frame number (default false)
50
+ ```displayName```: Name of the method
51
+ ```showOccluder```: If true, show occluder of gt data
52
+ ```fps```: Frame rate
53
+
54
+ ```
55
+ visualizer = MOTSVisualizer(seqName, FilePath, image_dir, mode, output_dir )
56
+ visualizer.generateVideo(displayTime, displayName, showOccluder, fps )
57
+ ```
58
+
59
+ ## Data Format
60
+
61
+ Each line of an annotation txt file is structured like this (where rle means run-length encoding from COCO):
62
+ ```
63
+ time_frame id class_id img_height img_width rle
64
+ ```
65
+ An example line from a txt file:
66
+ ```
67
+ 52 1005 1 375 1242 WSV:2d;1O10000O10000O1O100O100O1O100O1000000000000000O100O102N5K00O1O1N2O110OO2O001O1NTga3
68
+ ```
69
+ Meaning:
70
+ <br>time frame 52
71
+ <br>object id 1005 (meaning class id is 1, i.e. car and instance id is 5)
72
+ <br>class id 1
73
+ <br>image height 375
74
+ <br>image width 1242
75
+ <br>rle WSV:2d;1O10000O10000O1O100O100O1O100O1000000000000000O100O...1O1N </p>
76
+
77
+ image height, image width, and rle can be used together to decode a mask using [cocotools](https://github.com/cocodataset/cocoapi).
78
+
79
+ ## Citation
80
+ If you work with the code and the benchmark, please cite:
81
+
82
+ ```
83
+ @inproceedings{Voigtlaender19CVPR_MOTS,
84
+ author = {Paul Voigtlaender and Michael Krause and Aljo\u{s}a O\u{s}ep and Jonathon Luiten and Berin Balachandar Gnana Sekar and Andreas Geiger and Bastian Leibe},
85
+ title = {{MOTS}: Multi-Object Tracking and Segmentation},
86
+ booktitle = {CVPR},
87
+ year = {2019},
88
+ }
89
+ ```
90
+
91
+ ## License
92
+ MIT License
93
+
94
+ ## Contact
95
+ If you find a problem in the code, please open an issue.
96
+
97
+ For general questions, please contact Paul Voigtlaender (voigtlaender@vision.rwth-aachen.de) or Michael Krause (michael.krause@rwth-aachen.de)
OpenPVSG/models/unitrack/eval/mots/Visualize.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import cv2
3
+ import numpy as np
4
+ import os, sys
5
+ import glob
6
+ import colorsys
7
+ import traceback
8
+
9
+
10
+ class Visualizer(object):
11
+ def __init__(self,
12
+ seqName = None,
13
+ mode = None,
14
+ FilePath = None,
15
+ output_dir = None,
16
+ image_dir = None,
17
+ metaInfoDir = None
18
+
19
+ ):
20
+
21
+ assert mode in [None, "raw", "gt"], "Not valid mode. Value has to be None, 'raw', or 'gt'"
22
+
23
+ self.seqName = seqName
24
+ self.mode = mode
25
+ self.image_dir= image_dir
26
+ self.output_dir = output_dir
27
+ self.FilePath = FilePath
28
+ self.metaInfoDir = metaInfoDir
29
+
30
+ # adapted from https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/visualize.py
31
+ @property
32
+ def generate_colors(self):
33
+ """
34
+ Generate random colors.
35
+ To get visually distinct colors, generate them in HSV space then
36
+ convert to RGB.
37
+ """
38
+ N = 30
39
+ brightness = 0.7
40
+ hsv = [(i / N, 1, brightness) for i in range(N)]
41
+ colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
42
+ perm = [15, 13, 25, 12, 19, 8, 22, 24, 29, 17, 28, 20, 2, 27, 11, 26, 21, 4, 3, 18, 9, 5, 14, 1, 16, 0, 23, 7, 6, 10]
43
+ colors = [colors[idx] for idx in perm]
44
+ return colors
45
+ def generateVideo(self,
46
+ outputName = None,
47
+ extensions = [],
48
+ displayTime = False,
49
+ displayName = False,
50
+ showOccluder = False,
51
+ fps = 25):
52
+
53
+ self.showOccluder = showOccluder
54
+
55
+ if outputName == None:
56
+ outputName = self.seqName
57
+
58
+
59
+ if not self.mode == "raw":
60
+ #load File
61
+ self.resFile = self.load(self.FilePath)
62
+
63
+ # get images Folder
64
+ # check if image folder exists
65
+ if not os.path.isdir(self.image_dir):
66
+ print ("imgFolder does not exist")
67
+ sys.exit()
68
+
69
+
70
+ imgFile = "000001.jpg"
71
+ img = os.path.join(self.image_dir,imgFile)
72
+ print("image file" , img)
73
+ im = cv2.imread(img,1)
74
+ height, width, c = im.shape
75
+
76
+ self.imScale = 1
77
+ if width > 800:
78
+ self.imScale = .5
79
+ width = int(width*self.imScale)
80
+ height = int(height*self.imScale)
81
+
82
+ # video extension
83
+ extension = ".mp4"
84
+ if self.mode:
85
+ self.outputNameNoExt = os.path.join(self.output_dir, "%s-%s" % (outputName, self.mode))
86
+ else:
87
+ self.outputNameNoExt = os.path.join(self.output_dir, outputName)
88
+ self.outputName = "%s%s" % (self.outputNameNoExt, extension)
89
+
90
+ self.out = cv2.VideoWriter(self.outputName,cv2.VideoWriter_fourcc(*'mp4v'), fps, (width,height))
91
+
92
+ print ("Output name: %s"%self.outputName)
93
+ self.colors = self.generate_colors
94
+ t=0
95
+
96
+ for img in sorted(glob.glob(os.path.join(self.image_dir,"*.jpg"))):
97
+ t+=1
98
+
99
+ im = cv2.imread(img,1)
100
+
101
+ if not self.mode == "raw":
102
+ try:
103
+ im = self.drawResults(im, t)
104
+ except Exception as e:
105
+ print(str(traceback.format_exc()))
106
+ im=cv2.resize(im,(0,0),fx=self.imScale,fy=self.imScale)
107
+
108
+ if displayTime:
109
+ cv2.putText(im,"%d" % t,(25,50),cv2.FONT_HERSHEY_PLAIN,self.imScale*6,[255, 255, 255], thickness = 3)
110
+ if displayName:
111
+ text = "%s: %s" %(self.seqName, displayName)
112
+ cv2.putText(im, text,(25,height - 25 ),cv2.FONT_HERSHEY_DUPLEX,self.imScale* 2,[255, 255, 255], thickness = 2)
113
+
114
+ if t == 1:
115
+ cv2.imwrite("{}.jpg".format(self.outputNameNoExt), im)
116
+ im_mini = cv2.resize(im, (0,0), fx=0.25, fy=0.25)
117
+ cv2.imwrite("{}-mini.jpg".format(self.outputNameNoExt), im_mini)
118
+ self.out.write(im)
119
+ self.out.release()
120
+
121
+ print("Finished: %s"%self.outputName)
122
+ if not len(extensions)==0:
123
+ print("Convert Video to : ", extensions)
124
+ self.convertVideo(extensions)
125
+
126
+ def drawResults(self, image = None):
127
+ NotImplemented
128
+
129
+ def load(self):
130
+ NotImplemented
131
+
132
+ def convertVideo(self, extensions):
133
+
134
+ for ext in extensions:
135
+ print( self.outputName)
136
+ outputNameNewExt = "%s%s" % (self.outputNameNoExt, ext)
137
+ print("Convert Video to: %s" % outputNameNewExt)
138
+ command = "ffmpeg -loglevel warning -y -i %s -c:v libvpx-vp9 -crf 30 -b:v 0 -b:a 128k -c:a libvorbis -cpu-used 8 %s" % (self.outputName, outputNameNewExt)
139
+ os.system(command)
OpenPVSG/models/unitrack/eval/mots/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ import os, sys
2
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
OpenPVSG/models/unitrack/eval/mots/evalMOTS.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys, os
2
+ import pdb
3
+ sys.path.append(os.path.abspath(os.getcwd()))
4
+ import math
5
+ from collections import defaultdict
6
+ from MOTS_metrics import MOTSMetrics
7
+ from Evaluator import Evaluator, run_metrics
8
+
9
+ import multiprocessing as mp
10
+
11
+
12
+
13
+ class MOTSEvaluator(Evaluator):
14
+ def __init__(self):
15
+ self.type = "MOTS"
16
+ def eval(self):
17
+
18
+ arguments = []
19
+ for seq, res, gt in zip(self.sequences, self.tsfiles, self.gtfiles):
20
+ arguments.append({"metricObject": MOTSMetrics(seq),
21
+ "args" : {"gtDataDir": os.path.join( self.datadir,seq),
22
+ "sequence": str(seq) ,
23
+ "pred_file":res,
24
+ "gt_file": gt,
25
+ "benchmark_name": self.benchmark_name}})
26
+
27
+ if self.MULTIPROCESSING:
28
+ p = mp.Pool(self.NR_CORES)
29
+ processes = [p.apply_async(run_metrics, kwds=inp) for inp in arguments]
30
+ self.results = [p.get() for p in processes]
31
+ p.close()
32
+ p.join()
33
+
34
+ else:
35
+ self.results = [run_metrics(**inp) for inp in arguments]
36
+
37
+
38
+ # Sum up results for all sequences
39
+ self.Overall_Results = MOTSMetrics("OVERALL")
40
+ return self.results
41
+
42
+
43
+ if __name__ == "__main__":
44
+ eval = MOTSEvaluator()
45
+ benchmark_name = "MOTS"
46
+ gt_dir = "data/MOTS"
47
+ res_dir = "res/MOTSres"
48
+ eval_mode = "train"
49
+ eval.run(
50
+ benchmark_name = benchmark_name,
51
+ gt_dir = gt_dir,
52
+ res_dir = res_dir,
53
+ eval_mode = eval_mode)
OpenPVSG/models/unitrack/eval/mots/mots_common/images_to_txt.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from mots_common.io import load_sequences, load_seqmap, write_sequences
3
+
4
+
5
+ if __name__ == "__main__":
6
+ if len(sys.argv) != 4:
7
+ print("Usage: python images_to_txt.py gt_img_folder gt_txt_output_folder seqmap")
8
+ sys.exit(1)
9
+
10
+ gt_img_folder = sys.argv[1]
11
+ gt_txt_output_folder = sys.argv[2]
12
+ seqmap_filename = sys.argv[3]
13
+
14
+ seqmap, _ = load_seqmap(seqmap_filename)
15
+ print("Loading ground truth images...")
16
+ gt = load_sequences(gt_img_folder, seqmap)
17
+ print("Writing ground truth txts...")
18
+ write_sequences(gt, gt_txt_output_folder)
OpenPVSG/models/unitrack/eval/mots/mots_common/io.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import PIL.Image as Image
2
+ import numpy as np
3
+ import pycocotools.mask as rletools
4
+ import glob
5
+ import os
6
+
7
+
8
+ class SegmentedObject:
9
+ def __init__(self, mask, class_id, track_id):
10
+ self.mask = mask
11
+ self.class_id = class_id
12
+ self.track_id = track_id
13
+
14
+
15
+ def load_sequences(path, seqmap):
16
+ objects_per_frame_per_sequence = {}
17
+ for seq in seqmap:
18
+ print("Loading sequence", seq)
19
+ seq_path_folder = os.path.join(path, seq)
20
+ seq_path_txt = os.path.join(path, seq + ".txt")
21
+ if os.path.isdir(seq_path_folder):
22
+ objects_per_frame_per_sequence[seq] = load_images_for_folder(seq_path_folder)
23
+ elif os.path.exists(seq_path_txt):
24
+ objects_per_frame_per_sequence[seq] = load_txt(seq_path_txt)
25
+ else:
26
+ raise Exception( "<exc>Can't find data in directory " + path + "<!exc>")
27
+
28
+ return objects_per_frame_per_sequence
29
+
30
+
31
+ def load_txt(path):
32
+ objects_per_frame = {}
33
+ track_ids_per_frame = {} # To check that no frame contains two objects with same id
34
+ combined_mask_per_frame = {} # To check that no frame contains overlapping masks
35
+ with open(path, "r") as f:
36
+ for line in f:
37
+ line = line.strip()
38
+ fields = line.split(" ")
39
+ try:
40
+ frame = int(fields[0])
41
+ except:
42
+ raise Exception("<exc>Error in {} in line: {}<!exc>".format(path.split("/")[-1], line))
43
+ if frame not in objects_per_frame:
44
+ objects_per_frame[frame] = []
45
+ if frame not in track_ids_per_frame:
46
+ track_ids_per_frame[frame] = set()
47
+ if int(fields[1]) in track_ids_per_frame[frame]:
48
+ raise Exception("<exc>Multiple objects with track id " + fields[1] + " in frame " + fields[0] + "<!exc>")
49
+ else:
50
+ track_ids_per_frame[frame].add(int(fields[1]))
51
+
52
+ class_id = int(fields[2])
53
+ if not(class_id == 1 or class_id == 2 or class_id == 10):
54
+ raise Exception( "<exc>Unknown object class " + fields[2] + "<!exc>")
55
+
56
+ mask = {'size': [int(fields[3]), int(fields[4])], 'counts': fields[5].encode(encoding='UTF-8')}
57
+ if frame not in combined_mask_per_frame:
58
+ combined_mask_per_frame[frame] = mask
59
+ elif rletools.area(rletools.merge([combined_mask_per_frame[frame], mask], intersect=True)) > 0.0:
60
+ raise Exception( "<exc>Objects with overlapping masks in frame " + fields[0] + "<!exc>")
61
+ else:
62
+ combined_mask_per_frame[frame] = rletools.merge([combined_mask_per_frame[frame], mask], intersect=False)
63
+ objects_per_frame[frame].append(SegmentedObject(
64
+ mask,
65
+ class_id,
66
+ int(fields[1])
67
+ ))
68
+
69
+ return objects_per_frame
70
+
71
+
72
+ def load_images_for_folder(path):
73
+ files = sorted(glob.glob(os.path.join(path, "*.png")))
74
+
75
+ objects_per_frame = {}
76
+ for file in files:
77
+ objects = load_image(file)
78
+ frame = filename_to_frame_nr(os.path.basename(file))
79
+ objects_per_frame[frame] = objects
80
+
81
+ return objects_per_frame
82
+
83
+
84
+ def filename_to_frame_nr(filename):
85
+ assert len(filename) == 10, "Expect filenames to have format 000000.png, 000001.png, ..."
86
+ return int(filename.split('.')[0])
87
+
88
+
89
+ def load_image(filename, id_divisor=1000):
90
+ img = np.array(Image.open(filename))
91
+ obj_ids = np.unique(img)
92
+
93
+ objects = []
94
+ mask = np.zeros(img.shape, dtype=np.uint8, order="F") # Fortran order needed for pycocos RLE tools
95
+ for idx, obj_id in enumerate(obj_ids):
96
+ if obj_id == 0: # background
97
+ continue
98
+ mask.fill(0)
99
+ pixels_of_elem = np.where(img == obj_id)
100
+ mask[pixels_of_elem] = 1
101
+ objects.append(SegmentedObject(
102
+ rletools.encode(mask),
103
+ obj_id // id_divisor,
104
+ obj_id
105
+ ))
106
+
107
+ return objects
108
+
109
+
110
+ def load_seqmap(seqmap_filename):
111
+ print("Loading seqmap...")
112
+ seqmap = []
113
+ max_frames = {}
114
+ with open(seqmap_filename, "r") as fh:
115
+ for i, l in enumerate(fh):
116
+ fields = l.split(" ")
117
+ seq = "%04d" % int(fields[0])
118
+ seqmap.append(seq)
119
+ max_frames[seq] = int(fields[3])
120
+ return seqmap, max_frames
121
+
122
+
123
+ def write_sequences(gt, output_folder):
124
+ os.makedirs(output_folder, exist_ok=True)
125
+ for seq, seq_frames in gt.items():
126
+ write_sequence(seq_frames, os.path.join(output_folder, seq + ".txt"))
127
+ return
128
+
129
+
130
+ def write_sequence(frames, path):
131
+ with open(path, "w") as f:
132
+ for t, objects in frames.items():
133
+ for obj in objects:
134
+ print(t, obj.track_id, obj.class_id, obj.mask["size"][0], obj.mask["size"][1],
135
+ obj.mask["counts"].decode(encoding='UTF-8'), file=f)
OpenPVSG/models/unitrack/eval/mots/requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cycler==0.10.0
2
+ Cython==0.29.20
3
+ kiwisolver==1.2.0
4
+ matplotlib==3.2.2
5
+ numpy==1.19.0
6
+ opencv-python==4.2.0.34
7
+ pandas==1.0.5
8
+ Pillow==7.1.2
9
+ pycocotools==2.0.1
10
+ pyparsing==2.4.7
11
+ python-dateutil==2.8.1
12
+ pytz==2020.1
13
+ scipy==1.5.0
14
+ six==1.15.0
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/AUTHORS.txt ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The author of "jsonlab" toolbox is Qianqian Fang. Qianqian
2
+ is currently an Assistant Professor in the Department of Bioengineering,
3
+ Northeastern University.
4
+
5
+ Address: Qianqian Fang
6
+ Department of Bioengineering
7
+ Northeastern University
8
+ 212A Lake Hall
9
+ 360 Huntington Ave, Boston, MA 02115, USA
10
+ Office: 503 Holmes Hall
11
+ Phone[O]: 617-373-3829
12
+ URL: http://fanglab.org
13
+ Email: <q.fang at neu.edu> and <fangqq at gmail.com>
14
+
15
+
16
+ The script loadjson.m was built upon previous works by
17
+
18
+ - Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
19
+ date: 2009/11/02
20
+ - François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
21
+ date: 2009/03/22
22
+ - Joel Feenstra: http://www.mathworks.com/matlabcentral/fileexchange/20565
23
+ date: 2008/07/03
24
+
25
+
26
+ This toolbox contains patches submitted by the following contributors:
27
+
28
+ - Blake Johnson <bjohnso at bbn.com>
29
+ part of revision 341
30
+
31
+ - Niclas Borlin <Niclas.Borlin at cs.umu.se>
32
+ various fixes in revision 394, including
33
+ - loadjson crashes for all-zero sparse matrix.
34
+ - loadjson crashes for empty sparse matrix.
35
+ - Non-zero size of 0-by-N and N-by-0 empty matrices is lost after savejson/loadjson.
36
+ - loadjson crashes for sparse real column vector.
37
+ - loadjson crashes for sparse complex column vector.
38
+ - Data is corrupted by savejson for sparse real row vector.
39
+ - savejson crashes for sparse complex row vector.
40
+
41
+ - Yul Kang <yul.kang.on at gmail.com>
42
+ patches for svn revision 415.
43
+ - savejson saves an empty cell array as [] instead of null
44
+ - loadjson differentiates an empty struct from an empty array
45
+
46
+ - Mykhailo Bratukha <bratukha.m at gmail.com>
47
+ (Pull#14) Bug fix: File path is wrongly inerpreted as JSON string
48
+
49
+ - Insik Kim <insik92 at gmail.com>
50
+ (Pull#12) Bug fix: Resolving bug that cell type is converted to json with transposed data
51
+
52
+ - Sertan Senturk
53
+ (Pull#10,#11) Feature: Added matlab object saving to savejson and saveubjson
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/ChangeLog.txt ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ============================================================================
2
+
3
+ JSONlab - a toolbox to encode/decode JSON/UBJSON files in MATLAB/Octave
4
+
5
+ ----------------------------------------------------------------------------
6
+
7
+ JSONlab ChangeLog (key features marked by *):
8
+
9
+ == JSONlab 1.2 (codename: Optimus - Update 2), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
10
+
11
+ 2015/12/16 replacing string concatenation by str cells to gain 2x speed in savejson (Issue#17)
12
+ 2015/12/11 fix FileName option case bug (SVN rev#495)
13
+ 2015/12/11 add SingletCell option, add SingletArray to replace NoRowBracket (Issue#15,#8)
14
+ 2015/11/10 fix bug for inerpreting file names as JSON string - by Mykhailo Bratukha (Pull#14)
15
+ 2015/10/16 fix bug for cell with transposed data - by Insik Kim (Pull#12)
16
+ 2015/09/25 support exporting matlab object to JSON - by Sertan Senturk (Pull#10, #11)
17
+
18
+ == JSONlab 1.1 (codename: Optimus - Update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
19
+
20
+ 2015/05/05 *massively accelerating loadjson for parsing large collection of unstructured small objects
21
+ 2015/05/05 force array bracket in 1x1 struct to maintain depth (Issue#1)
22
+ 2015/05/05 parse logicals in loadjson
23
+ 2015/05/05 make options case insensitive
24
+ 2015/05/01 reading unicode encoded json files (thanks to Sertan Senturk,Issue#3)
25
+ 2015/04/30 allow \uXXXX to represent a unicode in a string (Issue#2)
26
+ 2015/03/30 save a 0x0 solid real empty array as null and handel empty struct array
27
+ 2015/03/30 properly handle escape characters in a string
28
+ 2015/01/24 *implement the UBJSON Draft12 new name format
29
+ 2015/01/13 correct cell array indentation inconsistency
30
+
31
+ == JSONlab 1.0 (codename: Optimus - Final), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
32
+
33
+ 2015/01/02 polish help info for all major functions, update examples, finalize 1.0
34
+ 2014/12/19 fix a bug to strictly respect NoRowBracket in savejson
35
+
36
+ == JSONlab 1.0.0-RC2 (codename: Optimus - RC2), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
37
+
38
+ 2014/11/22 show progress bar in loadjson ('ShowProgress')
39
+ 2014/11/17 *add Compact option in savejson to output compact JSON format ('Compact')
40
+ 2014/11/17 add FastArrayParser in loadjson to specify fast parser applicable levels
41
+ 2014/09/18 *start official github mirror: https://github.com/fangq/jsonlab
42
+
43
+ == JSONlab 1.0.0-RC1 (codename: Optimus - RC1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
44
+
45
+ 2014/09/17 fix several compatibility issues when running on octave versions 3.2-3.8
46
+ 2014/09/17 *support 2D cell and struct arrays in both savejson and saveubjson
47
+ 2014/08/04 escape special characters in a JSON string
48
+ 2014/02/16 fix a bug when saving ubjson files
49
+
50
+ == JSONlab 0.9.9 (codename: Optimus - beta), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
51
+
52
+ 2014/01/22 use binary read and write in saveubjson and loadubjson
53
+
54
+ == JSONlab 0.9.8-1 (codename: Optimus - alpha update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
55
+
56
+ 2013/10/07 better round-trip conservation for empty arrays and structs (patch submitted by Yul Kang)
57
+
58
+ == JSONlab 0.9.8 (codename: Optimus - alpha), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
59
+ 2013/08/23 *universal Binary JSON (UBJSON) support, including both saveubjson and loadubjson
60
+
61
+ == JSONlab 0.9.1 (codename: Rodimus, update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
62
+ 2012/12/18 *handling of various empty and sparse matrices (fixes submitted by Niclas Borlin)
63
+
64
+ == JSONlab 0.9.0 (codename: Rodimus), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
65
+
66
+ 2012/06/17 *new format for an invalid leading char, unpacking hex code in savejson
67
+ 2012/06/01 support JSONP in savejson
68
+ 2012/05/25 fix the empty cell bug (reported by Cyril Davin)
69
+ 2012/04/05 savejson can save to a file (suggested by Patrick Rapin)
70
+
71
+ == JSONlab 0.8.1 (codename: Sentiel, Update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
72
+
73
+ 2012/02/28 loadjson quotation mark escape bug, see http://bit.ly/yyk1nS
74
+ 2012/01/25 patch to handle root-less objects, contributed by Blake Johnson
75
+
76
+ == JSONlab 0.8.0 (codename: Sentiel), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
77
+
78
+ 2012/01/13 *speed up loadjson by 20 fold when parsing large data arrays in matlab
79
+ 2012/01/11 remove row bracket if an array has 1 element, suggested by Mykel Kochenderfer
80
+ 2011/12/22 *accept sequence of 'param',value input in savejson and loadjson
81
+ 2011/11/18 fix struct array bug reported by Mykel Kochenderfer
82
+
83
+ == JSONlab 0.5.1 (codename: Nexus Update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
84
+
85
+ 2011/10/21 fix a bug in loadjson, previous code does not use any of the acceleration
86
+ 2011/10/20 loadjson supports JSON collections - concatenated JSON objects
87
+
88
+ == JSONlab 0.5.0 (codename: Nexus), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
89
+
90
+ 2011/10/16 package and release jsonlab 0.5.0
91
+ 2011/10/15 *add json demo and regression test, support cpx numbers, fix double quote bug
92
+ 2011/10/11 *speed up readjson dramatically, interpret _Array* tags, show data in root level
93
+ 2011/10/10 create jsonlab project, start jsonlab website, add online documentation
94
+ 2011/10/07 *speed up savejson by 25x using sprintf instead of mat2str, add options support
95
+ 2011/10/06 *savejson works for structs, cells and arrays
96
+ 2011/09/09 derive loadjson from JSON parser from MATLAB Central, draft savejson.m
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/LICENSE_BSD.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2011-2015 Qianqian Fang <fangq at nmr.mgh.harvard.edu>. All rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are
4
+ permitted provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this list of
7
+ conditions and the following disclaimer.
8
+
9
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list
10
+ of conditions and the following disclaimer in the documentation and/or other materials
11
+ provided with the distribution.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY EXPRESS OR IMPLIED
14
+ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
15
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
16
+ OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
17
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
18
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
19
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
20
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
21
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22
+
23
+ The views and conclusions contained in the software and documentation are those of the
24
+ authors and should not be interpreted as representing official policies, either expressed
25
+ or implied, of the copyright holders.
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/README.txt ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ===============================================================================
2
+ = JSONLab =
3
+ = An open-source MATLAB/Octave JSON encoder and decoder =
4
+ ===============================================================================
5
+
6
+ *Copyright (C) 2011-2015 Qianqian Fang <fangq at nmr.mgh.harvard.edu>
7
+ *License: BSD License, see License_BSD.txt for details
8
+ *Version: 1.2 (Optimus - Update 2)
9
+
10
+ -------------------------------------------------------------------------------
11
+
12
+ Table of Content:
13
+
14
+ I. Introduction
15
+ II. Installation
16
+ III.Using JSONLab
17
+ IV. Known Issues and TODOs
18
+ V. Contribution and feedback
19
+
20
+ -------------------------------------------------------------------------------
21
+
22
+ I. Introduction
23
+
24
+ JSON ([http://www.json.org/ JavaScript Object Notation]) is a highly portable,
25
+ human-readable and "[http://en.wikipedia.org/wiki/JSON fat-free]" text format
26
+ to represent complex and hierarchical data. It is as powerful as
27
+ [http://en.wikipedia.org/wiki/XML XML], but less verbose. JSON format is widely
28
+ used for data-exchange in applications, and is essential for the wild success
29
+ of [http://en.wikipedia.org/wiki/Ajax_(programming) Ajax] and
30
+ [http://en.wikipedia.org/wiki/Web_2.0 Web2.0].
31
+
32
+ UBJSON (Universal Binary JSON) is a binary JSON format, specifically
33
+ optimized for compact file size and better performance while keeping
34
+ the semantics as simple as the text-based JSON format. Using the UBJSON
35
+ format allows to wrap complex binary data in a flexible and extensible
36
+ structure, making it possible to process complex and large dataset
37
+ without accuracy loss due to text conversions.
38
+
39
+ We envision that both JSON and its binary version will serve as part of
40
+ the mainstream data-exchange formats for scientific research in the future.
41
+ It will provide the flexibility and generality achieved by other popular
42
+ general-purpose file specifications, such as
43
+ [http://www.hdfgroup.org/HDF5/whatishdf5.html HDF5], with significantly
44
+ reduced complexity and enhanced performance.
45
+
46
+ JSONLab is a free and open-source implementation of a JSON/UBJSON encoder
47
+ and a decoder in the native MATLAB language. It can be used to convert a MATLAB
48
+ data structure (array, struct, cell, struct array and cell array) into
49
+ JSON/UBJSON formatted strings, or to decode a JSON/UBJSON file into MATLAB
50
+ data structure. JSONLab supports both MATLAB and
51
+ [http://www.gnu.org/software/octave/ GNU Octave] (a free MATLAB clone).
52
+
53
+ -------------------------------------------------------------------------------
54
+
55
+ II. Installation
56
+
57
+ The installation of JSONLab is no different than any other simple
58
+ MATLAB toolbox. You only need to download/unzip the JSONLab package
59
+ to a folder, and add the folder's path to MATLAB/Octave's path list
60
+ by using the following command:
61
+
62
+ addpath('/path/to/jsonlab');
63
+
64
+ If you want to add this path permanently, you need to type "pathtool",
65
+ browse to the jsonlab root folder and add to the list, then click "Save".
66
+ Then, run "rehash" in MATLAB, and type "which loadjson", if you see an
67
+ output, that means JSONLab is installed for MATLAB/Octave.
68
+
69
+ -------------------------------------------------------------------------------
70
+
71
+ III.Using JSONLab
72
+
73
+ JSONLab provides two functions, loadjson.m -- a MATLAB->JSON decoder,
74
+ and savejson.m -- a MATLAB->JSON encoder, for the text-based JSON, and
75
+ two equivallent functions -- loadubjson and saveubjson for the binary
76
+ JSON. The detailed help info for the four functions can be found below:
77
+
78
+ === loadjson.m ===
79
+ <pre>
80
+ data=loadjson(fname,opt)
81
+ or
82
+ data=loadjson(fname,'param1',value1,'param2',value2,...)
83
+
84
+ parse a JSON (JavaScript Object Notation) file or string
85
+
86
+ authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
87
+ created on 2011/09/09, including previous works from
88
+
89
+ Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
90
+ created on 2009/11/02
91
+ Fran�ois Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
92
+ created on 2009/03/22
93
+ Joel Feenstra:
94
+ http://www.mathworks.com/matlabcentral/fileexchange/20565
95
+ created on 2008/07/03
96
+
97
+ $Id: loadjson.m 487 2015-05-06 18:19:07Z fangq $
98
+
99
+ input:
100
+ fname: input file name, if fname contains "{}" or "[]", fname
101
+ will be interpreted as a JSON string
102
+ opt: a struct to store parsing options, opt can be replaced by
103
+ a list of ('param',value) pairs - the param string is equivallent
104
+ to a field in opt. opt can have the following
105
+ fields (first in [.|.] is the default)
106
+
107
+ opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
108
+ for each element of the JSON data, and group
109
+ arrays based on the cell2mat rules.
110
+ opt.FastArrayParser [1|0 or integer]: if set to 1, use a
111
+ speed-optimized array parser when loading an
112
+ array object. The fast array parser may
113
+ collapse block arrays into a single large
114
+ array similar to rules defined in cell2mat; 0 to
115
+ use a legacy parser; if set to a larger-than-1
116
+ value, this option will specify the minimum
117
+ dimension to enable the fast array parser. For
118
+ example, if the input is a 3D array, setting
119
+ FastArrayParser to 1 will return a 3D array;
120
+ setting to 2 will return a cell array of 2D
121
+ arrays; setting to 3 will return to a 2D cell
122
+ array of 1D vectors; setting to 4 will return a
123
+ 3D cell array.
124
+ opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
125
+
126
+ output:
127
+ dat: a cell array, where {...} blocks are converted into cell arrays,
128
+ and [...] are converted to arrays
129
+
130
+ examples:
131
+ dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
132
+ dat=loadjson(['examples' filesep 'example1.json'])
133
+ dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
134
+ </pre>
135
+
136
+ === savejson.m ===
137
+
138
+ <pre>
139
+ json=savejson(rootname,obj,filename)
140
+ or
141
+ json=savejson(rootname,obj,opt)
142
+ json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
143
+
144
+ convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
145
+ Object Notation) string
146
+
147
+ author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
148
+ created on 2011/09/09
149
+
150
+ $Id: savejson.m 486 2015-05-05 20:37:11Z fangq $
151
+
152
+ input:
153
+ rootname: the name of the root-object, when set to '', the root name
154
+ is ignored, however, when opt.ForceRootName is set to 1 (see below),
155
+ the MATLAB variable name will be used as the root name.
156
+ obj: a MATLAB object (array, cell, cell array, struct, struct array).
157
+ filename: a string for the file name to save the output JSON data.
158
+ opt: a struct for additional options, ignore to use default values.
159
+ opt can have the following fields (first in [.|.] is the default)
160
+
161
+ opt.FileName [''|string]: a file name to save the output JSON data
162
+ opt.FloatFormat ['%.10g'|string]: format to show each numeric element
163
+ of a 1D/2D array;
164
+ opt.ArrayIndent [1|0]: if 1, output explicit data array with
165
+ precedent indentation; if 0, no indentation
166
+ opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
167
+ array in JSON array format; if sets to 1, an
168
+ array will be shown as a struct with fields
169
+ "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
170
+ sparse arrays, the non-zero elements will be
171
+ saved to _ArrayData_ field in triplet-format i.e.
172
+ (ix,iy,val) and "_ArrayIsSparse_" will be added
173
+ with a value of 1; for a complex array, the
174
+ _ArrayData_ array will include two columns
175
+ (4 for sparse) to record the real and imaginary
176
+ parts, and also "_ArrayIsComplex_":1 is added.
177
+ opt.ParseLogical [0|1]: if this is set to 1, logical array elem
178
+ will use true/false rather than 1/0.
179
+ opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
180
+ numerical element will be shown without a square
181
+ bracket, unless it is the root object; if 0, square
182
+ brackets are forced for any numerical arrays.
183
+ opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
184
+ will use the name of the passed obj variable as the
185
+ root object name; if obj is an expression and
186
+ does not have a name, 'root' will be used; if this
187
+ is set to 0 and rootname is empty, the root level
188
+ will be merged down to the lower level.
189
+ opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
190
+ to represent +/-Inf. The matched pattern is '([-+]*)Inf'
191
+ and $1 represents the sign. For those who want to use
192
+ 1e999 to represent Inf, they can set opt.Inf to '$11e999'
193
+ opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
194
+ to represent NaN
195
+ opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
196
+ for example, if opt.JSONP='foo', the JSON data is
197
+ wrapped inside a function call as 'foo(...);'
198
+ opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
199
+ back to the string form
200
+ opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
201
+ opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
202
+
203
+ opt can be replaced by a list of ('param',value) pairs. The param
204
+ string is equivallent to a field in opt and is case sensitive.
205
+ output:
206
+ json: a string in the JSON format (see http://json.org)
207
+
208
+ examples:
209
+ jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
210
+ 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
211
+ 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
212
+ 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
213
+ 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
214
+ 'SpecialData',[nan, inf, -inf]);
215
+ savejson('jmesh',jsonmesh)
216
+ savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
217
+ </pre>
218
+
219
+ === loadubjson.m ===
220
+
221
+ <pre>
222
+ data=loadubjson(fname,opt)
223
+ or
224
+ data=loadubjson(fname,'param1',value1,'param2',value2,...)
225
+
226
+ parse a JSON (JavaScript Object Notation) file or string
227
+
228
+ authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
229
+ created on 2013/08/01
230
+
231
+ $Id: loadubjson.m 487 2015-05-06 18:19:07Z fangq $
232
+
233
+ input:
234
+ fname: input file name, if fname contains "{}" or "[]", fname
235
+ will be interpreted as a UBJSON string
236
+ opt: a struct to store parsing options, opt can be replaced by
237
+ a list of ('param',value) pairs - the param string is equivallent
238
+ to a field in opt. opt can have the following
239
+ fields (first in [.|.] is the default)
240
+
241
+ opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
242
+ for each element of the JSON data, and group
243
+ arrays based on the cell2mat rules.
244
+ opt.IntEndian [B|L]: specify the endianness of the integer fields
245
+ in the UBJSON input data. B - Big-Endian format for
246
+ integers (as required in the UBJSON specification);
247
+ L - input integer fields are in Little-Endian order.
248
+ opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or
249
+ earlier versions (JSONLab 1.0 final or earlier),
250
+ the "name" tag is treated as a string. To load
251
+ these UBJSON data, you need to manually set this
252
+ flag to 1.
253
+
254
+ output:
255
+ dat: a cell array, where {...} blocks are converted into cell arrays,
256
+ and [...] are converted to arrays
257
+
258
+ examples:
259
+ obj=struct('string','value','array',[1 2 3]);
260
+ ubjdata=saveubjson('obj',obj);
261
+ dat=loadubjson(ubjdata)
262
+ dat=loadubjson(['examples' filesep 'example1.ubj'])
263
+ dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
264
+ </pre>
265
+
266
+ === saveubjson.m ===
267
+
268
+ <pre>
269
+ json=saveubjson(rootname,obj,filename)
270
+ or
271
+ json=saveubjson(rootname,obj,opt)
272
+ json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
273
+
274
+ convert a MATLAB object (cell, struct or array) into a Universal
275
+ Binary JSON (UBJSON) binary string
276
+
277
+ author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
278
+ created on 2013/08/17
279
+
280
+ $Id: saveubjson.m 465 2015-01-25 00:46:07Z fangq $
281
+
282
+ input:
283
+ rootname: the name of the root-object, when set to '', the root name
284
+ is ignored, however, when opt.ForceRootName is set to 1 (see below),
285
+ the MATLAB variable name will be used as the root name.
286
+ obj: a MATLAB object (array, cell, cell array, struct, struct array)
287
+ filename: a string for the file name to save the output UBJSON data
288
+ opt: a struct for additional options, ignore to use default values.
289
+ opt can have the following fields (first in [.|.] is the default)
290
+
291
+ opt.FileName [''|string]: a file name to save the output JSON data
292
+ opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
293
+ array in JSON array format; if sets to 1, an
294
+ array will be shown as a struct with fields
295
+ "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
296
+ sparse arrays, the non-zero elements will be
297
+ saved to _ArrayData_ field in triplet-format i.e.
298
+ (ix,iy,val) and "_ArrayIsSparse_" will be added
299
+ with a value of 1; for a complex array, the
300
+ _ArrayData_ array will include two columns
301
+ (4 for sparse) to record the real and imaginary
302
+ parts, and also "_ArrayIsComplex_":1 is added.
303
+ opt.ParseLogical [1|0]: if this is set to 1, logical array elem
304
+ will use true/false rather than 1/0.
305
+ opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
306
+ numerical element will be shown without a square
307
+ bracket, unless it is the root object; if 0, square
308
+ brackets are forced for any numerical arrays.
309
+ opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
310
+ will use the name of the passed obj variable as the
311
+ root object name; if obj is an expression and
312
+ does not have a name, 'root' will be used; if this
313
+ is set to 0 and rootname is empty, the root level
314
+ will be merged down to the lower level.
315
+ opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
316
+ for example, if opt.JSON='foo', the JSON data is
317
+ wrapped inside a function call as 'foo(...);'
318
+ opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
319
+ back to the string form
320
+
321
+ opt can be replaced by a list of ('param',value) pairs. The param
322
+ string is equivallent to a field in opt and is case sensitive.
323
+ output:
324
+ json: a binary string in the UBJSON format (see http://ubjson.org)
325
+
326
+ examples:
327
+ jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
328
+ 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
329
+ 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
330
+ 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
331
+ 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
332
+ 'SpecialData',[nan, inf, -inf]);
333
+ saveubjson('jsonmesh',jsonmesh)
334
+ saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
335
+ </pre>
336
+
337
+
338
+ === examples ===
339
+
340
+ Under the "examples" folder, you can find several scripts to demonstrate the
341
+ basic utilities of JSONLab. Running the "demo_jsonlab_basic.m" script, you
342
+ will see the conversions from MATLAB data structure to JSON text and backward.
343
+ In "jsonlab_selftest.m", we load complex JSON files downloaded from the Internet
344
+ and validate the loadjson/savejson functions for regression testing purposes.
345
+ Similarly, a "demo_ubjson_basic.m" script is provided to test the saveubjson
346
+ and loadubjson functions for various matlab data structures.
347
+
348
+ Please run these examples and understand how JSONLab works before you use
349
+ it to process your data.
350
+
351
+ -------------------------------------------------------------------------------
352
+
353
+ IV. Known Issues and TODOs
354
+
355
+ JSONLab has several known limitations. We are striving to make it more general
356
+ and robust. Hopefully in a few future releases, the limitations become less.
357
+
358
+ Here are the known issues:
359
+
360
+ # 3D or higher dimensional cell/struct-arrays will be converted to 2D arrays;
361
+ # When processing names containing multi-byte characters, Octave and MATLAB \
362
+ can give different field-names; you can use feature('DefaultCharacterSet','latin1') \
363
+ in MATLAB to get consistant results
364
+ # savejson can not handle class and dataset.
365
+ # saveubjson converts a logical array into a uint8 ([U]) array
366
+ # an unofficial N-D array count syntax is implemented in saveubjson. We are \
367
+ actively communicating with the UBJSON spec maintainer to investigate the \
368
+ possibility of making it upstream
369
+ # loadubjson can not parse all UBJSON Specification (Draft 9) compliant \
370
+ files, however, it can parse all UBJSON files produced by saveubjson.
371
+
372
+ -------------------------------------------------------------------------------
373
+
374
+ V. Contribution and feedback
375
+
376
+ JSONLab is an open-source project. This means you can not only use it and modify
377
+ it as you wish, but also you can contribute your changes back to JSONLab so
378
+ that everyone else can enjoy the improvement. For anyone who want to contribute,
379
+ please download JSONLab source code from its source code repositories by using the
380
+ following command:
381
+
382
+ git clone https://github.com/fangq/jsonlab.git jsonlab
383
+
384
+ or browsing the github site at
385
+
386
+ https://github.com/fangq/jsonlab
387
+
388
+ alternatively, if you prefer svn, you can checkout the latest code by using
389
+
390
+ svn checkout svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab jsonlab
391
+
392
+ You can make changes to the files as needed. Once you are satisfied with your
393
+ changes, and ready to share it with others, please cd the root directory of
394
+ JSONLab, and type
395
+
396
+ git diff --no-prefix > yourname_featurename.patch
397
+
398
+ or
399
+
400
+ svn diff > yourname_featurename.patch
401
+
402
+ You then email the .patch file to JSONLab's maintainer, Qianqian Fang, at
403
+ the email address shown in the beginning of this file. Qianqian will review
404
+ the changes and commit it to the subversion if they are satisfactory.
405
+
406
+ We appreciate any suggestions and feedbacks from you. Please use the following
407
+ mailing list to report any questions you may have regarding JSONLab:
408
+
409
+ https://groups.google.com/forum/?hl=en#!forum/jsonlab-users
410
+
411
+ (Subscription to the mailing list is needed in order to post messages).
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/demo_jsonlab_basic.m ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
+ % Demonstration of Basic Utilities of JSONlab
3
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4
+
5
+ rngstate = rand ('state');
6
+ randseed=hex2dec('623F9A9E');
7
+ clear data2json json2data
8
+
9
+ fprintf(1,'\n%%=================================================\n')
10
+ fprintf(1,'%% a simple scalar value \n')
11
+ fprintf(1,'%%=================================================\n\n')
12
+
13
+ data2json=pi
14
+ savejson('',data2json)
15
+ json2data=loadjson(ans)
16
+
17
+ fprintf(1,'\n%%=================================================\n')
18
+ fprintf(1,'%% a complex number\n')
19
+ fprintf(1,'%%=================================================\n\n')
20
+
21
+ clear i;
22
+ data2json=1+2*i
23
+ savejson('',data2json)
24
+ json2data=loadjson(ans)
25
+
26
+ fprintf(1,'\n%%=================================================\n')
27
+ fprintf(1,'%% a complex matrix\n')
28
+ fprintf(1,'%%=================================================\n\n')
29
+
30
+ data2json=magic(6);
31
+ data2json=data2json(:,1:3)+data2json(:,4:6)*i
32
+ savejson('',data2json)
33
+ json2data=loadjson(ans)
34
+
35
+ fprintf(1,'\n%%=================================================\n')
36
+ fprintf(1,'%% MATLAB special constants\n')
37
+ fprintf(1,'%%=================================================\n\n')
38
+
39
+ data2json=[NaN Inf -Inf]
40
+ savejson('specials',data2json)
41
+ json2data=loadjson(ans)
42
+
43
+ fprintf(1,'\n%%=================================================\n')
44
+ fprintf(1,'%% a real sparse matrix\n')
45
+ fprintf(1,'%%=================================================\n\n')
46
+
47
+ data2json=sprand(10,10,0.1)
48
+ savejson('sparse',data2json)
49
+ json2data=loadjson(ans)
50
+
51
+ fprintf(1,'\n%%=================================================\n')
52
+ fprintf(1,'%% a complex sparse matrix\n')
53
+ fprintf(1,'%%=================================================\n\n')
54
+
55
+ data2json=data2json-data2json*i
56
+ savejson('complex_sparse',data2json)
57
+ json2data=loadjson(ans)
58
+
59
+ fprintf(1,'\n%%=================================================\n')
60
+ fprintf(1,'%% an all-zero sparse matrix\n')
61
+ fprintf(1,'%%=================================================\n\n')
62
+
63
+ data2json=sparse(2,3);
64
+ savejson('all_zero_sparse',data2json)
65
+ json2data=loadjson(ans)
66
+
67
+ fprintf(1,'\n%%=================================================\n')
68
+ fprintf(1,'%% an empty sparse matrix\n')
69
+ fprintf(1,'%%=================================================\n\n')
70
+
71
+ data2json=sparse([]);
72
+ savejson('empty_sparse',data2json)
73
+ json2data=loadjson(ans)
74
+
75
+ fprintf(1,'\n%%=================================================\n')
76
+ fprintf(1,'%% an empty 0-by-0 real matrix\n')
77
+ fprintf(1,'%%=================================================\n\n')
78
+
79
+ data2json=[];
80
+ savejson('empty_0by0_real',data2json)
81
+ json2data=loadjson(ans)
82
+
83
+ fprintf(1,'\n%%=================================================\n')
84
+ fprintf(1,'%% an empty 0-by-3 real matrix\n')
85
+ fprintf(1,'%%=================================================\n\n')
86
+
87
+ data2json=zeros(0,3);
88
+ savejson('empty_0by3_real',data2json)
89
+ json2data=loadjson(ans)
90
+
91
+ fprintf(1,'\n%%=================================================\n')
92
+ fprintf(1,'%% a sparse real column vector\n')
93
+ fprintf(1,'%%=================================================\n\n')
94
+
95
+ data2json=sparse([0,3,0,1,4]');
96
+ savejson('sparse_column_vector',data2json)
97
+ json2data=loadjson(ans)
98
+
99
+ fprintf(1,'\n%%=================================================\n')
100
+ fprintf(1,'%% a sparse complex column vector\n')
101
+ fprintf(1,'%%=================================================\n\n')
102
+
103
+ data2json=data2json-1i*data2json;
104
+ savejson('complex_sparse_column_vector',data2json)
105
+ json2data=loadjson(ans)
106
+
107
+ fprintf(1,'\n%%=================================================\n')
108
+ fprintf(1,'%% a sparse real row vector\n')
109
+ fprintf(1,'%%=================================================\n\n')
110
+
111
+ data2json=sparse([0,3,0,1,4]);
112
+ savejson('sparse_row_vector',data2json)
113
+ json2data=loadjson(ans)
114
+
115
+ fprintf(1,'\n%%=================================================\n')
116
+ fprintf(1,'%% a sparse complex row vector\n')
117
+ fprintf(1,'%%=================================================\n\n')
118
+
119
+ data2json=data2json-1i*data2json;
120
+ savejson('complex_sparse_row_vector',data2json)
121
+ json2data=loadjson(ans)
122
+
123
+ fprintf(1,'\n%%=================================================\n')
124
+ fprintf(1,'%% a structure\n')
125
+ fprintf(1,'%%=================================================\n\n')
126
+
127
+ data2json=struct('name','Think Different','year',1997,'magic',magic(3),...
128
+ 'misfits',[Inf,NaN],'embedded',struct('left',true,'right',false))
129
+ savejson('astruct',data2json,struct('ParseLogical',1))
130
+ json2data=loadjson(ans)
131
+ class(json2data.astruct.embedded.left)
132
+
133
+ fprintf(1,'\n%%=================================================\n')
134
+ fprintf(1,'%% a structure array\n')
135
+ fprintf(1,'%%=================================================\n\n')
136
+
137
+ data2json=struct('name','Nexus Prime','rank',9);
138
+ data2json(2)=struct('name','Sentinel Prime','rank',9);
139
+ data2json(3)=struct('name','Optimus Prime','rank',9);
140
+ savejson('Supreme Commander',data2json)
141
+ json2data=loadjson(ans)
142
+
143
+ fprintf(1,'\n%%=================================================\n')
144
+ fprintf(1,'%% a cell array\n')
145
+ fprintf(1,'%%=================================================\n\n')
146
+
147
+ data2json=cell(3,1);
148
+ data2json{1}=struct('buzz',1.1,'rex',1.2,'bo',1.3,'hamm',2.0,'slink',2.1,'potato',2.2,...
149
+ 'woody',3.0,'sarge',3.1,'etch',4.0,'lenny',5.0,'squeeze',6.0,'wheezy',7.0);
150
+ data2json{2}=struct('Ubuntu',['Kubuntu';'Xubuntu';'Lubuntu']);
151
+ data2json{3}=[10.04,10.10,11.04,11.10]
152
+ savejson('debian',data2json,struct('FloatFormat','%.2f'))
153
+ json2data=loadjson(ans)
154
+
155
+ fprintf(1,'\n%%=================================================\n')
156
+ fprintf(1,'%% invalid field-name handling\n')
157
+ fprintf(1,'%%=================================================\n\n')
158
+
159
+ json2data=loadjson('{"ValidName":1, "_InvalidName":2, ":Field:":3, "项目":"绝密"}')
160
+
161
+ fprintf(1,'\n%%=================================================\n')
162
+ fprintf(1,'%% a 2D cell array\n')
163
+ fprintf(1,'%%=================================================\n\n')
164
+
165
+ data2json={{1,{2,3}},{4,5},{6};{7},{8,9},{10}};
166
+ savejson('data2json',data2json)
167
+ json2data=loadjson(ans) % only savejson works for cell arrays, loadjson has issues
168
+
169
+ fprintf(1,'\n%%=================================================\n')
170
+ fprintf(1,'%% a 2D struct array\n')
171
+ fprintf(1,'%%=================================================\n\n')
172
+
173
+ data2json=repmat(struct('idx',0,'data','structs'),[2,3])
174
+ for i=1:6
175
+ data2json(i).idx=i;
176
+ end
177
+ savejson('data2json',data2json)
178
+ json2data=loadjson(ans)
179
+
180
+ rand ('state',rngstate);
181
+
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/demo_ubjson_basic.m ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
+ % Demonstration of Basic Utilities of JSONlab
3
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4
+
5
+ rngstate = rand ('state');
6
+ randseed=hex2dec('623F9A9E');
7
+ clear data2json json2data
8
+
9
+ fprintf(1,'\n%%=================================================\n')
10
+ fprintf(1,'%% a simple scalar value \n')
11
+ fprintf(1,'%%=================================================\n\n')
12
+
13
+ data2json=pi
14
+ saveubjson('',data2json)
15
+ json2data=loadubjson(ans)
16
+
17
+ fprintf(1,'\n%%=================================================\n')
18
+ fprintf(1,'%% a complex number\n')
19
+ fprintf(1,'%%=================================================\n\n')
20
+
21
+ clear i;
22
+ data2json=1+2*i
23
+ saveubjson('',data2json)
24
+ json2data=loadubjson(ans)
25
+
26
+ fprintf(1,'\n%%=================================================\n')
27
+ fprintf(1,'%% a complex matrix\n')
28
+ fprintf(1,'%%=================================================\n\n')
29
+
30
+ data2json=magic(6);
31
+ data2json=data2json(:,1:3)+data2json(:,4:6)*i
32
+ saveubjson('',data2json)
33
+ json2data=loadubjson(ans)
34
+
35
+ fprintf(1,'\n%%=================================================\n')
36
+ fprintf(1,'%% MATLAB special constants\n')
37
+ fprintf(1,'%%=================================================\n\n')
38
+
39
+ data2json=[NaN Inf -Inf]
40
+ saveubjson('specials',data2json)
41
+ json2data=loadubjson(ans)
42
+
43
+ fprintf(1,'\n%%=================================================\n')
44
+ fprintf(1,'%% a real sparse matrix\n')
45
+ fprintf(1,'%%=================================================\n\n')
46
+
47
+ data2json=sprand(10,10,0.1)
48
+ saveubjson('sparse',data2json)
49
+ json2data=loadubjson(ans)
50
+
51
+ fprintf(1,'\n%%=================================================\n')
52
+ fprintf(1,'%% a complex sparse matrix\n')
53
+ fprintf(1,'%%=================================================\n\n')
54
+
55
+ data2json=data2json-data2json*i
56
+ saveubjson('complex_sparse',data2json)
57
+ json2data=loadubjson(ans)
58
+
59
+ fprintf(1,'\n%%=================================================\n')
60
+ fprintf(1,'%% an all-zero sparse matrix\n')
61
+ fprintf(1,'%%=================================================\n\n')
62
+
63
+ data2json=sparse(2,3);
64
+ saveubjson('all_zero_sparse',data2json)
65
+ json2data=loadubjson(ans)
66
+
67
+ fprintf(1,'\n%%=================================================\n')
68
+ fprintf(1,'%% an empty sparse matrix\n')
69
+ fprintf(1,'%%=================================================\n\n')
70
+
71
+ data2json=sparse([]);
72
+ saveubjson('empty_sparse',data2json)
73
+ json2data=loadubjson(ans)
74
+
75
+ fprintf(1,'\n%%=================================================\n')
76
+ fprintf(1,'%% an empty 0-by-0 real matrix\n')
77
+ fprintf(1,'%%=================================================\n\n')
78
+
79
+ data2json=[];
80
+ saveubjson('empty_0by0_real',data2json)
81
+ json2data=loadubjson(ans)
82
+
83
+ fprintf(1,'\n%%=================================================\n')
84
+ fprintf(1,'%% an empty 0-by-3 real matrix\n')
85
+ fprintf(1,'%%=================================================\n\n')
86
+
87
+ data2json=zeros(0,3);
88
+ saveubjson('empty_0by3_real',data2json)
89
+ json2data=loadubjson(ans)
90
+
91
+ fprintf(1,'\n%%=================================================\n')
92
+ fprintf(1,'%% a sparse real column vector\n')
93
+ fprintf(1,'%%=================================================\n\n')
94
+
95
+ data2json=sparse([0,3,0,1,4]');
96
+ saveubjson('sparse_column_vector',data2json)
97
+ json2data=loadubjson(ans)
98
+
99
+ fprintf(1,'\n%%=================================================\n')
100
+ fprintf(1,'%% a sparse complex column vector\n')
101
+ fprintf(1,'%%=================================================\n\n')
102
+
103
+ data2json=data2json-1i*data2json;
104
+ saveubjson('complex_sparse_column_vector',data2json)
105
+ json2data=loadubjson(ans)
106
+
107
+ fprintf(1,'\n%%=================================================\n')
108
+ fprintf(1,'%% a sparse real row vector\n')
109
+ fprintf(1,'%%=================================================\n\n')
110
+
111
+ data2json=sparse([0,3,0,1,4]);
112
+ saveubjson('sparse_row_vector',data2json)
113
+ json2data=loadubjson(ans)
114
+
115
+ fprintf(1,'\n%%=================================================\n')
116
+ fprintf(1,'%% a sparse complex row vector\n')
117
+ fprintf(1,'%%=================================================\n\n')
118
+
119
+ data2json=data2json-1i*data2json;
120
+ saveubjson('complex_sparse_row_vector',data2json)
121
+ json2data=loadubjson(ans)
122
+
123
+ fprintf(1,'\n%%=================================================\n')
124
+ fprintf(1,'%% a structure\n')
125
+ fprintf(1,'%%=================================================\n\n')
126
+
127
+ data2json=struct('name','Think Different','year',1997,'magic',magic(3),...
128
+ 'misfits',[Inf,NaN],'embedded',struct('left',true,'right',false))
129
+ saveubjson('astruct',data2json,struct('ParseLogical',1))
130
+ json2data=loadubjson(ans)
131
+
132
+ fprintf(1,'\n%%=================================================\n')
133
+ fprintf(1,'%% a structure array\n')
134
+ fprintf(1,'%%=================================================\n\n')
135
+
136
+ data2json=struct('name','Nexus Prime','rank',9);
137
+ data2json(2)=struct('name','Sentinel Prime','rank',9);
138
+ data2json(3)=struct('name','Optimus Prime','rank',9);
139
+ saveubjson('Supreme Commander',data2json)
140
+ json2data=loadubjson(ans)
141
+
142
+ fprintf(1,'\n%%=================================================\n')
143
+ fprintf(1,'%% a cell array\n')
144
+ fprintf(1,'%%=================================================\n\n')
145
+
146
+ data2json=cell(3,1);
147
+ data2json{1}=struct('buzz',1.1,'rex',1.2,'bo',1.3,'hamm',2.0,'slink',2.1,'potato',2.2,...
148
+ 'woody',3.0,'sarge',3.1,'etch',4.0,'lenny',5.0,'squeeze',6.0,'wheezy',7.0);
149
+ data2json{2}=struct('Ubuntu',['Kubuntu';'Xubuntu';'Lubuntu']);
150
+ data2json{3}=[10.04,10.10,11.04,11.10]
151
+ saveubjson('debian',data2json,struct('FloatFormat','%.2f'))
152
+ json2data=loadubjson(ans)
153
+
154
+ fprintf(1,'\n%%=================================================\n')
155
+ fprintf(1,'%% invalid field-name handling\n')
156
+ fprintf(1,'%%=================================================\n\n')
157
+
158
+ json2data=loadubjson(saveubjson('',loadjson('{"ValidName":1, "_InvalidName":2, ":Field:":3, "项目":"绝密"}')))
159
+
160
+ fprintf(1,'\n%%=================================================\n')
161
+ fprintf(1,'%% a 2D cell array\n')
162
+ fprintf(1,'%%=================================================\n\n')
163
+
164
+ data2json={{1,{2,3}},{4,5},{6};{7},{8,9},{10}};
165
+ saveubjson('data2json',data2json)
166
+ json2data=loadubjson(ans) % only savejson works for cell arrays, loadjson has issues
167
+
168
+ fprintf(1,'\n%%=================================================\n')
169
+ fprintf(1,'%% a 2D struct array\n')
170
+ fprintf(1,'%%=================================================\n\n')
171
+
172
+ data2json=repmat(struct('idx',0,'data','structs'),[2,3])
173
+ for i=1:6
174
+ data2json(i).idx=i;
175
+ end
176
+ saveubjson('data2json',data2json)
177
+ json2data=loadubjson(ans)
178
+
179
+ rand ('state',rngstate);
180
+
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_basictest.matlab ADDED
@@ -0,0 +1,671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ < M A T L A B (R) >
3
+ Copyright 1984-2010 The MathWorks, Inc.
4
+ Version 7.11.0.584 (R2010b) 64-bit (glnxa64)
5
+ August 16, 2010
6
+
7
+
8
+ To get started, type one of these: helpwin, helpdesk, or demo.
9
+ For product information, visit www.mathworks.com.
10
+
11
+ >> >> >> >> >> >> >> >> >>
12
+ %=================================================
13
+ >> % a simple scalar value
14
+ >> %=================================================
15
+
16
+ >> >>
17
+ data2json =
18
+
19
+ 3.1416
20
+
21
+ >>
22
+ ans =
23
+
24
+ [3.141592654]
25
+
26
+
27
+ >>
28
+ json2data =
29
+
30
+ 3.1416
31
+
32
+ >> >>
33
+ %=================================================
34
+ >> % a complex number
35
+ >> %=================================================
36
+
37
+ >> >> >>
38
+ data2json =
39
+
40
+ 1.0000 + 2.0000i
41
+
42
+ >>
43
+ ans =
44
+
45
+ {
46
+ "_ArrayType_": "double",
47
+ "_ArraySize_": [1,1],
48
+ "_ArrayIsComplex_": 1,
49
+ "_ArrayData_": [1,2]
50
+ }
51
+
52
+
53
+ >>
54
+ json2data =
55
+
56
+ 1.0000 + 2.0000i
57
+
58
+ >> >>
59
+ %=================================================
60
+ >> % a complex matrix
61
+ >> %=================================================
62
+
63
+ >> >> >>
64
+ data2json =
65
+
66
+ 35.0000 +26.0000i 1.0000 +19.0000i 6.0000 +24.0000i
67
+ 3.0000 +21.0000i 32.0000 +23.0000i 7.0000 +25.0000i
68
+ 31.0000 +22.0000i 9.0000 +27.0000i 2.0000 +20.0000i
69
+ 8.0000 +17.0000i 28.0000 +10.0000i 33.0000 +15.0000i
70
+ 30.0000 +12.0000i 5.0000 +14.0000i 34.0000 +16.0000i
71
+ 4.0000 +13.0000i 36.0000 +18.0000i 29.0000 +11.0000i
72
+
73
+ >>
74
+ ans =
75
+
76
+ {
77
+ "_ArrayType_": "double",
78
+ "_ArraySize_": [6,3],
79
+ "_ArrayIsComplex_": 1,
80
+ "_ArrayData_": [
81
+ [35,26],
82
+ [3,21],
83
+ [31,22],
84
+ [8,17],
85
+ [30,12],
86
+ [4,13],
87
+ [1,19],
88
+ [32,23],
89
+ [9,27],
90
+ [28,10],
91
+ [5,14],
92
+ [36,18],
93
+ [6,24],
94
+ [7,25],
95
+ [2,20],
96
+ [33,15],
97
+ [34,16],
98
+ [29,11]
99
+ ]
100
+ }
101
+
102
+
103
+ >>
104
+ json2data =
105
+
106
+ 35.0000 +26.0000i 1.0000 +19.0000i 6.0000 +24.0000i
107
+ 3.0000 +21.0000i 32.0000 +23.0000i 7.0000 +25.0000i
108
+ 31.0000 +22.0000i 9.0000 +27.0000i 2.0000 +20.0000i
109
+ 8.0000 +17.0000i 28.0000 +10.0000i 33.0000 +15.0000i
110
+ 30.0000 +12.0000i 5.0000 +14.0000i 34.0000 +16.0000i
111
+ 4.0000 +13.0000i 36.0000 +18.0000i 29.0000 +11.0000i
112
+
113
+ >> >>
114
+ %=================================================
115
+ >> % MATLAB special constants
116
+ >> %=================================================
117
+
118
+ >> >>
119
+ data2json =
120
+
121
+ NaN Inf -Inf
122
+
123
+ >>
124
+ ans =
125
+
126
+ {
127
+ "specials": ["_NaN_","_Inf_","-_Inf_"]
128
+ }
129
+
130
+
131
+ >>
132
+ json2data =
133
+
134
+ specials: [NaN Inf -Inf]
135
+
136
+ >> >>
137
+ %=================================================
138
+ >> % a real sparse matrix
139
+ >> %=================================================
140
+
141
+ >> >>
142
+ data2json =
143
+
144
+ (1,2) 0.6557
145
+ (9,2) 0.7577
146
+ (3,5) 0.8491
147
+ (10,5) 0.7431
148
+ (10,8) 0.3922
149
+ (7,9) 0.6787
150
+ (2,10) 0.0357
151
+ (6,10) 0.9340
152
+ (10,10) 0.6555
153
+
154
+ >>
155
+ ans =
156
+
157
+ {
158
+ "sparse": {
159
+ "_ArrayType_": "double",
160
+ "_ArraySize_": [10,10],
161
+ "_ArrayIsSparse_": 1,
162
+ "_ArrayData_": [
163
+ [1,2,0.6557406992],
164
+ [9,2,0.7577401306],
165
+ [3,5,0.8491293059],
166
+ [10,5,0.7431324681],
167
+ [10,8,0.3922270195],
168
+ [7,9,0.6787351549],
169
+ [2,10,0.03571167857],
170
+ [6,10,0.9339932478],
171
+ [10,10,0.6554778902]
172
+ ]
173
+ }
174
+ }
175
+
176
+
177
+ >>
178
+ json2data =
179
+
180
+ sparse: [10x10 double]
181
+
182
+ >> >>
183
+ %=================================================
184
+ >> % a complex sparse matrix
185
+ >> %=================================================
186
+
187
+ >> >>
188
+ data2json =
189
+
190
+ (1,2) 0.6557 - 0.6557i
191
+ (9,2) 0.7577 - 0.7577i
192
+ (3,5) 0.8491 - 0.8491i
193
+ (10,5) 0.7431 - 0.7431i
194
+ (10,8) 0.3922 - 0.3922i
195
+ (7,9) 0.6787 - 0.6787i
196
+ (2,10) 0.0357 - 0.0357i
197
+ (6,10) 0.9340 - 0.9340i
198
+ (10,10) 0.6555 - 0.6555i
199
+
200
+ >>
201
+ ans =
202
+
203
+ {
204
+ "complex_sparse": {
205
+ "_ArrayType_": "double",
206
+ "_ArraySize_": [10,10],
207
+ "_ArrayIsComplex_": 1,
208
+ "_ArrayIsSparse_": 1,
209
+ "_ArrayData_": [
210
+ [1,2,0.6557406992,-0.6557406992],
211
+ [9,2,0.7577401306,-0.7577401306],
212
+ [3,5,0.8491293059,-0.8491293059],
213
+ [10,5,0.7431324681,-0.7431324681],
214
+ [10,8,0.3922270195,-0.3922270195],
215
+ [7,9,0.6787351549,-0.6787351549],
216
+ [2,10,0.03571167857,-0.03571167857],
217
+ [6,10,0.9339932478,-0.9339932478],
218
+ [10,10,0.6554778902,-0.6554778902]
219
+ ]
220
+ }
221
+ }
222
+
223
+
224
+ >>
225
+ json2data =
226
+
227
+ complex_sparse: [10x10 double]
228
+
229
+ >> >>
230
+ %=================================================
231
+ >> % an all-zero sparse matrix
232
+ >> %=================================================
233
+
234
+ >> >> >>
235
+ ans =
236
+
237
+ {
238
+ "all_zero_sparse": {
239
+ "_ArrayType_": "double",
240
+ "_ArraySize_": [2,3],
241
+ "_ArrayIsSparse_": 1,
242
+ "_ArrayData_": null
243
+ }
244
+ }
245
+
246
+
247
+ >>
248
+ json2data =
249
+
250
+ all_zero_sparse: [2x3 double]
251
+
252
+ >> >>
253
+ %=================================================
254
+ >> % an empty sparse matrix
255
+ >> %=================================================
256
+
257
+ >> >> >>
258
+ ans =
259
+
260
+ {
261
+ "empty_sparse": {
262
+ "_ArrayType_": "double",
263
+ "_ArraySize_": [0,0],
264
+ "_ArrayIsSparse_": 1,
265
+ "_ArrayData_": null
266
+ }
267
+ }
268
+
269
+
270
+ >>
271
+ json2data =
272
+
273
+ empty_sparse: []
274
+
275
+ >> >>
276
+ %=================================================
277
+ >> % an empty 0-by-0 real matrix
278
+ >> %=================================================
279
+
280
+ >> >> >>
281
+ ans =
282
+
283
+ {
284
+ "empty_0by0_real": null
285
+ }
286
+
287
+
288
+ >>
289
+ json2data =
290
+
291
+ empty_0by0_real: []
292
+
293
+ >> >>
294
+ %=================================================
295
+ >> % an empty 0-by-3 real matrix
296
+ >> %=================================================
297
+
298
+ >> >> >>
299
+ ans =
300
+
301
+ {
302
+ "empty_0by3_real": {
303
+ "_ArrayType_": "double",
304
+ "_ArraySize_": [0,3],
305
+ "_ArrayData_": null
306
+ }
307
+ }
308
+
309
+
310
+ >>
311
+ json2data =
312
+
313
+ empty_0by3_real: [0x3 double]
314
+
315
+ >> >>
316
+ %=================================================
317
+ >> % a sparse real column vector
318
+ >> %=================================================
319
+
320
+ >> >> >>
321
+ ans =
322
+
323
+ {
324
+ "sparse_column_vector": {
325
+ "_ArrayType_": "double",
326
+ "_ArraySize_": [5,1],
327
+ "_ArrayIsSparse_": 1,
328
+ "_ArrayData_": [
329
+ [2,3],
330
+ [4,1],
331
+ [5,4]
332
+ ]
333
+ }
334
+ }
335
+
336
+
337
+ >>
338
+ json2data =
339
+
340
+ sparse_column_vector: [5x1 double]
341
+
342
+ >> >>
343
+ %=================================================
344
+ >> % a sparse complex column vector
345
+ >> %=================================================
346
+
347
+ >> >> >>
348
+ ans =
349
+
350
+ {
351
+ "complex_sparse_column_vector": {
352
+ "_ArrayType_": "double",
353
+ "_ArraySize_": [5,1],
354
+ "_ArrayIsComplex_": 1,
355
+ "_ArrayIsSparse_": 1,
356
+ "_ArrayData_": [
357
+ [2,3,-3],
358
+ [4,1,-1],
359
+ [5,4,-4]
360
+ ]
361
+ }
362
+ }
363
+
364
+
365
+ >>
366
+ json2data =
367
+
368
+ complex_sparse_column_vector: [5x1 double]
369
+
370
+ >> >>
371
+ %=================================================
372
+ >> % a sparse real row vector
373
+ >> %=================================================
374
+
375
+ >> >> >>
376
+ ans =
377
+
378
+ {
379
+ "sparse_row_vector": {
380
+ "_ArrayType_": "double",
381
+ "_ArraySize_": [1,5],
382
+ "_ArrayIsSparse_": 1,
383
+ "_ArrayData_": [
384
+ [2,3],
385
+ [4,1],
386
+ [5,4]
387
+ ]
388
+ }
389
+ }
390
+
391
+
392
+ >>
393
+ json2data =
394
+
395
+ sparse_row_vector: [0 3 0 1 4]
396
+
397
+ >> >>
398
+ %=================================================
399
+ >> % a sparse complex row vector
400
+ >> %=================================================
401
+
402
+ >> >> >>
403
+ ans =
404
+
405
+ {
406
+ "complex_sparse_row_vector": {
407
+ "_ArrayType_": "double",
408
+ "_ArraySize_": [1,5],
409
+ "_ArrayIsComplex_": 1,
410
+ "_ArrayIsSparse_": 1,
411
+ "_ArrayData_": [
412
+ [2,3,-3],
413
+ [4,1,-1],
414
+ [5,4,-4]
415
+ ]
416
+ }
417
+ }
418
+
419
+
420
+ >>
421
+ json2data =
422
+
423
+ complex_sparse_row_vector: [1x5 double]
424
+
425
+ >> >>
426
+ %=================================================
427
+ >> % a structure
428
+ >> %=================================================
429
+
430
+ >> >>
431
+ data2json =
432
+
433
+ name: 'Think Different'
434
+ year: 1997
435
+ magic: [3x3 double]
436
+ misfits: [Inf NaN]
437
+ embedded: [1x1 struct]
438
+
439
+ >>
440
+ ans =
441
+
442
+ {
443
+ "astruct": {
444
+ "name": "Think Different",
445
+ "year": 1997,
446
+ "magic": [
447
+ [8,1,6],
448
+ [3,5,7],
449
+ [4,9,2]
450
+ ],
451
+ "misfits": ["_Inf_","_NaN_"],
452
+ "embedded": {
453
+ "left": true,
454
+ "right": false
455
+ }
456
+ }
457
+ }
458
+
459
+
460
+ >>
461
+ json2data =
462
+
463
+ astruct: [1x1 struct]
464
+
465
+ >>
466
+ ans =
467
+
468
+ logical
469
+
470
+ >> >>
471
+ %=================================================
472
+ >> % a structure array
473
+ >> %=================================================
474
+
475
+ >> >> >> >> >>
476
+ ans =
477
+
478
+ {
479
+ "Supreme Commander": [
480
+ {
481
+ "name": "Nexus Prime",
482
+ "rank": 9
483
+ },
484
+ {
485
+ "name": "Sentinel Prime",
486
+ "rank": 9
487
+ },
488
+ {
489
+ "name": "Optimus Prime",
490
+ "rank": 9
491
+ }
492
+ ]
493
+ }
494
+
495
+
496
+ >>
497
+ json2data =
498
+
499
+ Supreme_0x20_Commander: {[1x1 struct] [1x1 struct] [1x1 struct]}
500
+
501
+ >> >>
502
+ %=================================================
503
+ >> % a cell array
504
+ >> %=================================================
505
+
506
+ >> >> >> >> >>
507
+ data2json =
508
+
509
+ [1x1 struct]
510
+ [1x1 struct]
511
+ [1x4 double]
512
+
513
+ >>
514
+ ans =
515
+
516
+ {
517
+ "debian": [
518
+ [
519
+ {
520
+ "buzz": 1.10,
521
+ "rex": 1.20,
522
+ "bo": 1.30,
523
+ "hamm": 2.00,
524
+ "slink": 2.10,
525
+ "potato": 2.20,
526
+ "woody": 3.00,
527
+ "sarge": 3.10,
528
+ "etch": 4.00,
529
+ "lenny": 5.00,
530
+ "squeeze": 6.00,
531
+ "wheezy": 7.00
532
+ }
533
+ ],
534
+ [
535
+ {
536
+ "Ubuntu": [
537
+ "Kubuntu",
538
+ "Xubuntu",
539
+ "Lubuntu"
540
+ ]
541
+ }
542
+ ],
543
+ [
544
+ [10.04,10.10,11.04,11.10]
545
+ ]
546
+ ]
547
+ }
548
+
549
+
550
+ >>
551
+ json2data =
552
+
553
+ debian: {{1x1 cell} {1x1 cell} [10.0400 10.1000 11.0400 11.1000]}
554
+
555
+ >> >>
556
+ %=================================================
557
+ >> % invalid field-name handling
558
+ >> %=================================================
559
+
560
+ >> >>
561
+ json2data =
562
+
563
+ ValidName: 1
564
+ x0x5F_InvalidName: 2
565
+ x0x3A_Field_0x3A_: 3
566
+ x0xE9A1B9__0xE79BAE_: '绝密'
567
+
568
+ >> >>
569
+ %=================================================
570
+ >> % a 2D cell array
571
+ >> %=================================================
572
+
573
+ >> >> >>
574
+ ans =
575
+
576
+ {
577
+ "data2json": [
578
+ [
579
+ [
580
+ 1,
581
+ [
582
+ 2,
583
+ 3
584
+ ]
585
+ ],
586
+ [
587
+ 4,
588
+ 5
589
+ ],
590
+ [
591
+ 6
592
+ ]
593
+ ],
594
+ [
595
+ [
596
+ 7
597
+ ],
598
+ [
599
+ 8,
600
+ 9
601
+ ],
602
+ [
603
+ 10
604
+ ]
605
+ ]
606
+ ]
607
+ }
608
+
609
+
610
+ >>
611
+ json2data =
612
+
613
+ data2json: {{1x3 cell} {1x3 cell}}
614
+
615
+ >> >>
616
+ %=================================================
617
+ >> % a 2D struct array
618
+ >> %=================================================
619
+
620
+ >> >>
621
+ data2json =
622
+
623
+ 2x3 struct array with fields:
624
+ idx
625
+ data
626
+
627
+ >> >>
628
+ ans =
629
+
630
+ {
631
+ "data2json": [
632
+ [
633
+ {
634
+ "idx": 1,
635
+ "data": "structs"
636
+ },
637
+ {
638
+ "idx": 2,
639
+ "data": "structs"
640
+ }
641
+ ],
642
+ [
643
+ {
644
+ "idx": 3,
645
+ "data": "structs"
646
+ },
647
+ {
648
+ "idx": 4,
649
+ "data": "structs"
650
+ }
651
+ ],
652
+ [
653
+ {
654
+ "idx": 5,
655
+ "data": "structs"
656
+ },
657
+ {
658
+ "idx": 6,
659
+ "data": "structs"
660
+ }
661
+ ]
662
+ ]
663
+ }
664
+
665
+
666
+ >>
667
+ json2data =
668
+
669
+ data2json: {{1x2 cell} {1x2 cell} {1x2 cell}}
670
+
671
+ >> >> >> >>
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_selftest.m ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
+ % Regression Test Unit of loadjson and savejson
3
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4
+
5
+ for i=1:4
6
+ fname=sprintf('example%d.json',i);
7
+ if(exist(fname,'file')==0) break; end
8
+ fprintf(1,'===============================================\n>> %s\n',fname);
9
+ json=savejson('data',loadjson(fname));
10
+ fprintf(1,'%s\n',json);
11
+ fprintf(1,'%s\n',savejson('data',loadjson(fname),'Compact',1));
12
+ data=loadjson(json);
13
+ savejson('data',data,'selftest.json');
14
+ data=loadjson('selftest.json');
15
+ end
16
+
17
+ for i=1:4
18
+ fname=sprintf('example%d.json',i);
19
+ if(exist(fname,'file')==0) break; end
20
+ fprintf(1,'===============================================\n>> %s\n',fname);
21
+ json=saveubjson('data',loadjson(fname));
22
+ fprintf(1,'%s\n',json);
23
+ data=loadubjson(json);
24
+ savejson('',data);
25
+ saveubjson('data',data,'selftest.ubj');
26
+ data=loadubjson('selftest.ubj');
27
+ end
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_selftest.matlab ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ < M A T L A B (R) >
3
+ Copyright 1984-2010 The MathWorks, Inc.
4
+ Version 7.11.0.584 (R2010b) 64-bit (glnxa64)
5
+ August 16, 2010
6
+
7
+
8
+ To get started, type one of these: helpwin, helpdesk, or demo.
9
+ For product information, visit www.mathworks.com.
10
+
11
+ >> >> >> >> >> ===============================================
12
+ >> example1.json
13
+ {
14
+ "data": {
15
+ "firstName": "John",
16
+ "lastName": "Smith",
17
+ "age": 25,
18
+ "address": {
19
+ "streetAddress": "21 2nd Street",
20
+ "city": "New York",
21
+ "state": "NY",
22
+ "postalCode": "10021"
23
+ },
24
+ "phoneNumber": [
25
+ {
26
+ "type": "home",
27
+ "number": "212 555-1234"
28
+ },
29
+ {
30
+ "type": "fax",
31
+ "number": "646 555-4567"
32
+ }
33
+ ]
34
+ }
35
+ }
36
+
37
+ {"data": {"firstName": "John","lastName": "Smith","age": 25,"address": {"streetAddress": "21 2nd Street","city": "New York","state": "NY","postalCode": "10021"},"phoneNumber": [{"type": "home","number": "212 555-1234"},{"type": "fax","number": "646 555-4567"}]}}
38
+
39
+ ===============================================
40
+ >> example2.json
41
+ {
42
+ "data": {
43
+ "glossary": {
44
+ "title": "example glossary",
45
+ "GlossDiv": {
46
+ "title": "S",
47
+ "GlossList": {
48
+ "GlossEntry": {
49
+ "ID": "SGML",
50
+ "SortAs": "SGML",
51
+ "GlossTerm": "Standard Generalized Markup Language",
52
+ "Acronym": "SGML",
53
+ "Abbrev": "ISO 8879:1986",
54
+ "GlossDef": {
55
+ "para": "A meta-markup language, used to create markup languages such as DocBook.",
56
+ "GlossSeeAlso": [
57
+ "GML",
58
+ "XML"
59
+ ]
60
+ },
61
+ "GlossSee": "markup"
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+ }
68
+
69
+ {"data": {"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML","XML"]},"GlossSee": "markup"}}}}}}
70
+
71
+ ===============================================
72
+ >> example3.json
73
+ {
74
+ "data": {
75
+ "menu": {
76
+ "id": "file",
77
+ "value": "_&File",
78
+ "popup": {
79
+ "menuitem": [
80
+ {
81
+ "value": "_&New",
82
+ "onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")"
83
+ },
84
+ {
85
+ "value": "_&Open",
86
+ "onclick": "OpenDoc()"
87
+ },
88
+ {
89
+ "value": "_&Close",
90
+ "onclick": "CloseDoc()"
91
+ }
92
+ ]
93
+ }
94
+ }
95
+ }
96
+ }
97
+
98
+ {"data": {"menu": {"id": "file","value": "_&File","popup": {"menuitem": [{"value": "_&New","onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")"},{"value": "_&Open","onclick": "OpenDoc()"},{"value": "_&Close","onclick": "CloseDoc()"}]}}}}
99
+
100
+ ===============================================
101
+ >> example4.json
102
+ {
103
+ "data": [
104
+ {
105
+ "sample": {
106
+ "rho": 1
107
+ }
108
+ },
109
+ {
110
+ "sample": {
111
+ "rho": 2
112
+ }
113
+ },
114
+ [
115
+ [1,0],
116
+ [1,1],
117
+ [1,2]
118
+ ],
119
+ [
120
+ "Paper",
121
+ "Scissors",
122
+ "Stone"
123
+ ],
124
+ [
125
+ "a",
126
+ "b\\",
127
+ "c\"",
128
+ "d\\\"",
129
+ "e\"[",
130
+ "f\\\"[",
131
+ "g[\\",
132
+ "h[\\\""
133
+ ]
134
+ ]
135
+ }
136
+
137
+ {"data": [{"sample": {"rho": 1}},{"sample": {"rho": 2}},[[1,0],[1,1],[1,2]],["Paper","Scissors","Stone"],["a","b\\","c\"","d\\\"","e\"[","f\\\"[","g[\\","h[\\\""]]}
138
+
139
+ >> >> ===============================================
140
+ >> example1.json
141
+ {Udata{U firstNameSUJohnUlastNameSUSmithUageiUaddress{U
142
+ postalCodeSU10021}U phoneNumber[{UtypeSUhomeUnumberSU 212 555-1234}{UtypeSUfaxUnumberSU 646 555-4567}]}}
143
+ ===============================================
144
+ >> example2.json
145
+ {Udata{Uglossary{UtitleSUexample glossaryUGlossDiv{UtitleCSU GlossList{U
146
+ GlossEntry{UIDSUSGMLUSortAsSUSGMLU GlossTermSU$Standard Generalized Markup LanguageUAcronymSUSGMLUAbbrevSU
147
+ ===============================================
148
+ >> example3.json
149
+ {Udata{Umenu{UidSUfileUvalueSU_&FileUpopup{Umenuitem[{UvalueSU_&NewUonclickSUCreateNewDoc("'\"Untitled\"'")}{UvalueSU_&OpenUonclickSU OpenDoc()}{UvalueSU_&CloseUonclickSU
150
+ CloseDoc()}]}}}}
151
+ ===============================================
152
+ >> example4.json
153
+ {Udata[{Usample{Urhoi}}{Usample{Urhoi}}[[$i#U[$i#U[$i#U][SUPaperSUScissorsSUStone][CaSUb\SUc"SUd\"SUe"[SUf\"[SUg[\SUh[\"]]}
154
+ >>
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/examples/jsonlab_speedtest.m ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
+ % Benchmarking processing speed of savejson and loadjson
3
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4
+
5
+ datalen=[1e3 1e4 1e5 1e6];
6
+ len=length(datalen);
7
+ tsave=zeros(len,1);
8
+ tload=zeros(len,1);
9
+ for i=1:len
10
+ tic;
11
+ json=savejson('data',struct('d1',rand(datalen(i),3),'d2',rand(datalen(i),3)>0.5));
12
+ tsave(i)=toc;
13
+ data=loadjson(json);
14
+ tload(i)=toc-tsave(i);
15
+ fprintf(1,'matrix size: %d\n',datalen(i));
16
+ end
17
+
18
+ loglog(datalen,tsave,'o-',datalen,tload,'r*-');
19
+ legend('savejson runtime (s)','loadjson runtime (s)');
20
+ xlabel('array size');
21
+ ylabel('running time (s)');
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/jsonopt.m ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function val=jsonopt(key,default,varargin)
2
+ %
3
+ % val=jsonopt(key,default,optstruct)
4
+ %
5
+ % setting options based on a struct. The struct can be produced
6
+ % by varargin2struct from a list of 'param','value' pairs
7
+ %
8
+ % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
9
+ %
10
+ % $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $
11
+ %
12
+ % input:
13
+ % key: a string with which one look up a value from a struct
14
+ % default: if the key does not exist, return default
15
+ % optstruct: a struct where each sub-field is a key
16
+ %
17
+ % output:
18
+ % val: if key exists, val=optstruct.key; otherwise val=default
19
+ %
20
+ % license:
21
+ % BSD License, see LICENSE_BSD.txt files for details
22
+ %
23
+ % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
24
+ %
25
+
26
+ val=default;
27
+ if(nargin<=2) return; end
28
+ opt=varargin{1};
29
+ if(isstruct(opt))
30
+ if(isfield(opt,key))
31
+ val=getfield(opt,key);
32
+ elseif(isfield(opt,lower(key)))
33
+ val=getfield(opt,lower(key));
34
+ end
35
+ end
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/loadjson.m ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function data = loadjson(fname,varargin)
2
+ %
3
+ % data=loadjson(fname,opt)
4
+ % or
5
+ % data=loadjson(fname,'param1',value1,'param2',value2,...)
6
+ %
7
+ % parse a JSON (JavaScript Object Notation) file or string
8
+ %
9
+ % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
10
+ % created on 2011/09/09, including previous works from
11
+ %
12
+ % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
13
+ % created on 2009/11/02
14
+ % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
15
+ % created on 2009/03/22
16
+ % Joel Feenstra:
17
+ % http://www.mathworks.com/matlabcentral/fileexchange/20565
18
+ % created on 2008/07/03
19
+ %
20
+ % $Id$
21
+ %
22
+ % input:
23
+ % fname: input file name, if fname contains "{}" or "[]", fname
24
+ % will be interpreted as a JSON string
25
+ % opt: a struct to store parsing options, opt can be replaced by
26
+ % a list of ('param',value) pairs - the param string is equivallent
27
+ % to a field in opt. opt can have the following
28
+ % fields (first in [.|.] is the default)
29
+ %
30
+ % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
31
+ % for each element of the JSON data, and group
32
+ % arrays based on the cell2mat rules.
33
+ % opt.FastArrayParser [1|0 or integer]: if set to 1, use a
34
+ % speed-optimized array parser when loading an
35
+ % array object. The fast array parser may
36
+ % collapse block arrays into a single large
37
+ % array similar to rules defined in cell2mat; 0 to
38
+ % use a legacy parser; if set to a larger-than-1
39
+ % value, this option will specify the minimum
40
+ % dimension to enable the fast array parser. For
41
+ % example, if the input is a 3D array, setting
42
+ % FastArrayParser to 1 will return a 3D array;
43
+ % setting to 2 will return a cell array of 2D
44
+ % arrays; setting to 3 will return to a 2D cell
45
+ % array of 1D vectors; setting to 4 will return a
46
+ % 3D cell array.
47
+ % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
48
+ %
49
+ % output:
50
+ % dat: a cell array, where {...} blocks are converted into cell arrays,
51
+ % and [...] are converted to arrays
52
+ %
53
+ % examples:
54
+ % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
55
+ % dat=loadjson(['examples' filesep 'example1.json'])
56
+ % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
57
+ %
58
+ % license:
59
+ % BSD License, see LICENSE_BSD.txt files for details
60
+ %
61
+ % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
62
+ %
63
+
64
+ global pos inStr len esc index_esc len_esc isoct arraytoken
65
+
66
+ if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once'))
67
+ string=fname;
68
+ elseif(exist(fname,'file'))
69
+ try
70
+ string = fileread(fname);
71
+ catch
72
+ try
73
+ string = urlread(['file://',fname]);
74
+ catch
75
+ string = urlread(['file://',fullfile(pwd,fname)]);
76
+ end
77
+ end
78
+ else
79
+ error('input file does not exist');
80
+ end
81
+
82
+ pos = 1; len = length(string); inStr = string;
83
+ isoct=exist('OCTAVE_VERSION','builtin');
84
+ arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
85
+ jstr=regexprep(inStr,'\\\\',' ');
86
+ escquote=regexp(jstr,'\\"');
87
+ arraytoken=sort([arraytoken escquote]);
88
+
89
+ % String delimiters and escape chars identified to improve speed:
90
+ esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
91
+ index_esc = 1; len_esc = length(esc);
92
+
93
+ opt=varargin2struct(varargin{:});
94
+
95
+ if(jsonopt('ShowProgress',0,opt)==1)
96
+ opt.progressbar_=waitbar(0,'loading ...');
97
+ end
98
+ jsoncount=1;
99
+ while pos <= len
100
+ switch(next_char)
101
+ case '{'
102
+ data{jsoncount} = parse_object(opt);
103
+ case '['
104
+ data{jsoncount} = parse_array(opt);
105
+ otherwise
106
+ error_pos('Outer level structure must be an object or an array');
107
+ end
108
+ jsoncount=jsoncount+1;
109
+ end % while
110
+
111
+ jsoncount=length(data);
112
+ if(jsoncount==1 && iscell(data))
113
+ data=data{1};
114
+ end
115
+
116
+ if(isfield(opt,'progressbar_'))
117
+ close(opt.progressbar_);
118
+ end
119
+
120
+ %%-------------------------------------------------------------------------
121
+ function object = parse_object(varargin)
122
+ parse_char('{');
123
+ object = [];
124
+ if next_char ~= '}'
125
+ while 1
126
+ str = parseStr(varargin{:});
127
+ if isempty(str)
128
+ error_pos('Name of value at position %d cannot be empty');
129
+ end
130
+ parse_char(':');
131
+ val = parse_value(varargin{:});
132
+ object.(valid_field(str))=val;
133
+ if next_char == '}'
134
+ break;
135
+ end
136
+ parse_char(',');
137
+ end
138
+ end
139
+ parse_char('}');
140
+ if(isstruct(object))
141
+ object=struct2jdata(object);
142
+ end
143
+
144
+ %%-------------------------------------------------------------------------
145
+
146
+ function object = parse_array(varargin) % JSON array is written in row-major order
147
+ global pos inStr isoct
148
+ parse_char('[');
149
+ object = cell(0, 1);
150
+ dim2=[];
151
+ arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
152
+ pbar=-1;
153
+ if(isfield(varargin{1},'progressbar_'))
154
+ pbar=varargin{1}.progressbar_;
155
+ end
156
+
157
+ if next_char ~= ']'
158
+ if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
159
+ [endpos, e1l, e1r]=matching_bracket(inStr,pos);
160
+ arraystr=['[' inStr(pos:endpos)];
161
+ arraystr=regexprep(arraystr,'"_NaN_"','NaN');
162
+ arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
163
+ arraystr(arraystr==sprintf('\n'))=[];
164
+ arraystr(arraystr==sprintf('\r'))=[];
165
+ %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
166
+ if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
167
+ astr=inStr((e1l+1):(e1r-1));
168
+ astr=regexprep(astr,'"_NaN_"','NaN');
169
+ astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
170
+ astr(astr==sprintf('\n'))=[];
171
+ astr(astr==sprintf('\r'))=[];
172
+ astr(astr==' ')='';
173
+ if(isempty(find(astr=='[', 1))) % array is 2D
174
+ dim2=length(sscanf(astr,'%f,',[1 inf]));
175
+ end
176
+ else % array is 1D
177
+ astr=arraystr(2:end-1);
178
+ astr(astr==' ')='';
179
+ [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
180
+ if(nextidx>=length(astr)-1)
181
+ object=obj;
182
+ pos=endpos;
183
+ parse_char(']');
184
+ return;
185
+ end
186
+ end
187
+ if(~isempty(dim2))
188
+ astr=arraystr;
189
+ astr(astr=='[')='';
190
+ astr(astr==']')='';
191
+ astr(astr==' ')='';
192
+ [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
193
+ if(nextidx>=length(astr)-1)
194
+ object=reshape(obj,dim2,numel(obj)/dim2)';
195
+ pos=endpos;
196
+ parse_char(']');
197
+ if(pbar>0)
198
+ waitbar(pos/length(inStr),pbar,'loading ...');
199
+ end
200
+ return;
201
+ end
202
+ end
203
+ arraystr=regexprep(arraystr,'\]\s*,','];');
204
+ else
205
+ arraystr='[';
206
+ end
207
+ try
208
+ if(isoct && regexp(arraystr,'"','once'))
209
+ error('Octave eval can produce empty cells for JSON-like input');
210
+ end
211
+ object=eval(arraystr);
212
+ pos=endpos;
213
+ catch
214
+ while 1
215
+ newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
216
+ val = parse_value(newopt);
217
+ object{end+1} = val;
218
+ if next_char == ']'
219
+ break;
220
+ end
221
+ parse_char(',');
222
+ end
223
+ end
224
+ end
225
+ if(jsonopt('SimplifyCell',0,varargin{:})==1)
226
+ try
227
+ oldobj=object;
228
+ object=cell2mat(object')';
229
+ if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
230
+ object=oldobj;
231
+ elseif(size(object,1)>1 && ismatrix(object))
232
+ object=object';
233
+ end
234
+ catch
235
+ end
236
+ end
237
+ parse_char(']');
238
+
239
+ if(pbar>0)
240
+ waitbar(pos/length(inStr),pbar,'loading ...');
241
+ end
242
+ %%-------------------------------------------------------------------------
243
+
244
+ function parse_char(c)
245
+ global pos inStr len
246
+ pos=skip_whitespace(pos,inStr,len);
247
+ if pos > len || inStr(pos) ~= c
248
+ error_pos(sprintf('Expected %c at position %%d', c));
249
+ else
250
+ pos = pos + 1;
251
+ pos=skip_whitespace(pos,inStr,len);
252
+ end
253
+
254
+ %%-------------------------------------------------------------------------
255
+
256
+ function c = next_char
257
+ global pos inStr len
258
+ pos=skip_whitespace(pos,inStr,len);
259
+ if pos > len
260
+ c = [];
261
+ else
262
+ c = inStr(pos);
263
+ end
264
+
265
+ %%-------------------------------------------------------------------------
266
+
267
+ function newpos=skip_whitespace(pos,inStr,len)
268
+ newpos=pos;
269
+ while newpos <= len && isspace(inStr(newpos))
270
+ newpos = newpos + 1;
271
+ end
272
+
273
+ %%-------------------------------------------------------------------------
274
+ function str = parseStr(varargin)
275
+ global pos inStr len esc index_esc len_esc
276
+ % len, ns = length(inStr), keyboard
277
+ if inStr(pos) ~= '"'
278
+ error_pos('String starting with " expected at position %d');
279
+ else
280
+ pos = pos + 1;
281
+ end
282
+ str = '';
283
+ while pos <= len
284
+ while index_esc <= len_esc && esc(index_esc) < pos
285
+ index_esc = index_esc + 1;
286
+ end
287
+ if index_esc > len_esc
288
+ str = [str inStr(pos:len)];
289
+ pos = len + 1;
290
+ break;
291
+ else
292
+ str = [str inStr(pos:esc(index_esc)-1)];
293
+ pos = esc(index_esc);
294
+ end
295
+ nstr = length(str);
296
+ switch inStr(pos)
297
+ case '"'
298
+ pos = pos + 1;
299
+ if(~isempty(str))
300
+ if(strcmp(str,'_Inf_'))
301
+ str=Inf;
302
+ elseif(strcmp(str,'-_Inf_'))
303
+ str=-Inf;
304
+ elseif(strcmp(str,'_NaN_'))
305
+ str=NaN;
306
+ end
307
+ end
308
+ return;
309
+ case '\'
310
+ if pos+1 > len
311
+ error_pos('End of file reached right after escape character');
312
+ end
313
+ pos = pos + 1;
314
+ switch inStr(pos)
315
+ case {'"' '\' '/'}
316
+ str(nstr+1) = inStr(pos);
317
+ pos = pos + 1;
318
+ case {'b' 'f' 'n' 'r' 't'}
319
+ str(nstr+1) = sprintf(['\' inStr(pos)]);
320
+ pos = pos + 1;
321
+ case 'u'
322
+ if pos+4 > len
323
+ error_pos('End of file reached in escaped unicode character');
324
+ end
325
+ str(nstr+(1:6)) = inStr(pos-1:pos+4);
326
+ pos = pos + 5;
327
+ end
328
+ otherwise % should never happen
329
+ str(nstr+1) = inStr(pos);
330
+ keyboard;
331
+ pos = pos + 1;
332
+ end
333
+ end
334
+ error_pos('End of file while expecting end of inStr');
335
+
336
+ %%-------------------------------------------------------------------------
337
+
338
+ function num = parse_number(varargin)
339
+ global pos inStr isoct
340
+ currstr=inStr(pos:min(pos+30,end));
341
+ if(isoct~=0)
342
+ numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
343
+ [num] = sscanf(currstr, '%f', 1);
344
+ delta=numstr+1;
345
+ else
346
+ [num, one, err, delta] = sscanf(currstr, '%f', 1);
347
+ if ~isempty(err)
348
+ error_pos('Error reading number at position %d');
349
+ end
350
+ end
351
+ pos = pos + delta-1;
352
+
353
+ %%-------------------------------------------------------------------------
354
+
355
+ function val = parse_value(varargin)
356
+ global pos inStr len
357
+
358
+ if(isfield(varargin{1},'progressbar_'))
359
+ waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
360
+ end
361
+
362
+ switch(inStr(pos))
363
+ case '"'
364
+ val = parseStr(varargin{:});
365
+ return;
366
+ case '['
367
+ val = parse_array(varargin{:});
368
+ return;
369
+ case '{'
370
+ val = parse_object(varargin{:});
371
+ return;
372
+ case {'-','0','1','2','3','4','5','6','7','8','9'}
373
+ val = parse_number(varargin{:});
374
+ return;
375
+ case 't'
376
+ if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
377
+ val = true;
378
+ pos = pos + 4;
379
+ return;
380
+ end
381
+ case 'f'
382
+ if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
383
+ val = false;
384
+ pos = pos + 5;
385
+ return;
386
+ end
387
+ case 'n'
388
+ if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
389
+ val = [];
390
+ pos = pos + 4;
391
+ return;
392
+ end
393
+ end
394
+ error_pos('Value expected at position %d');
395
+ %%-------------------------------------------------------------------------
396
+
397
+ function error_pos(msg)
398
+ global pos inStr len
399
+ poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
400
+ if poShow(3) == poShow(2)
401
+ poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
402
+ end
403
+ msg = [sprintf(msg, pos) ': ' ...
404
+ inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
405
+ error( ['JSONparser:invalidFormat: ' msg] );
406
+
407
+ %%-------------------------------------------------------------------------
408
+
409
+ function str = valid_field(str)
410
+ global isoct
411
+ % From MATLAB doc: field names must begin with a letter, which may be
412
+ % followed by any combination of letters, digits, and underscores.
413
+ % Invalid characters will be converted to underscores, and the prefix
414
+ % "x0x[Hex code]_" will be added if the first character is not a letter.
415
+ pos=regexp(str,'^[^A-Za-z]','once');
416
+ if(~isempty(pos))
417
+ if(~isoct)
418
+ str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
419
+ else
420
+ str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
421
+ end
422
+ end
423
+ if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
424
+ return;
425
+ end
426
+ if(~isoct)
427
+ str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
428
+ else
429
+ pos=regexp(str,'[^0-9A-Za-z_]');
430
+ if(isempty(pos))
431
+ return;
432
+ end
433
+ str0=str;
434
+ pos0=[0 pos(:)' length(str)];
435
+ str='';
436
+ for i=1:length(pos)
437
+ str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
438
+ end
439
+ if(pos(end)~=length(str))
440
+ str=[str str0(pos0(end-1)+1:pos0(end))];
441
+ end
442
+ end
443
+ %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
444
+
445
+ %%-------------------------------------------------------------------------
446
+ function endpos = matching_quote(str,pos)
447
+ len=length(str);
448
+ while(pos<len)
449
+ if(str(pos)=='"')
450
+ if(~(pos>1 && str(pos-1)=='\'))
451
+ endpos=pos;
452
+ return;
453
+ end
454
+ end
455
+ pos=pos+1;
456
+ end
457
+ error('unmatched quotation mark');
458
+ %%-------------------------------------------------------------------------
459
+ function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
460
+ global arraytoken
461
+ level=1;
462
+ maxlevel=level;
463
+ endpos=0;
464
+ bpos=arraytoken(arraytoken>=pos);
465
+ tokens=str(bpos);
466
+ len=length(tokens);
467
+ pos=1;
468
+ e1l=[];
469
+ e1r=[];
470
+ while(pos<=len)
471
+ c=tokens(pos);
472
+ if(c==']')
473
+ level=level-1;
474
+ if(isempty(e1r))
475
+ e1r=bpos(pos);
476
+ end
477
+ if(level==0)
478
+ endpos=bpos(pos);
479
+ return
480
+ end
481
+ end
482
+ if(c=='[')
483
+ if(isempty(e1l))
484
+ e1l=bpos(pos);
485
+ end
486
+ level=level+1;
487
+ maxlevel=max(maxlevel,level);
488
+ end
489
+ if(c=='"')
490
+ pos=matching_quote(tokens,pos+1);
491
+ end
492
+ pos=pos+1;
493
+ end
494
+ if(endpos==0)
495
+ error('unmatched "]"');
496
+ end
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/loadubjson.m ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function data = loadubjson(fname,varargin)
2
+ %
3
+ % data=loadubjson(fname,opt)
4
+ % or
5
+ % data=loadubjson(fname,'param1',value1,'param2',value2,...)
6
+ %
7
+ % parse a JSON (JavaScript Object Notation) file or string
8
+ %
9
+ % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
10
+ % created on 2013/08/01
11
+ %
12
+ % $Id$
13
+ %
14
+ % input:
15
+ % fname: input file name, if fname contains "{}" or "[]", fname
16
+ % will be interpreted as a UBJSON string
17
+ % opt: a struct to store parsing options, opt can be replaced by
18
+ % a list of ('param',value) pairs - the param string is equivallent
19
+ % to a field in opt. opt can have the following
20
+ % fields (first in [.|.] is the default)
21
+ %
22
+ % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
23
+ % for each element of the JSON data, and group
24
+ % arrays based on the cell2mat rules.
25
+ % opt.IntEndian [B|L]: specify the endianness of the integer fields
26
+ % in the UBJSON input data. B - Big-Endian format for
27
+ % integers (as required in the UBJSON specification);
28
+ % L - input integer fields are in Little-Endian order.
29
+ % opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or
30
+ % earlier versions (JSONLab 1.0 final or earlier),
31
+ % the "name" tag is treated as a string. To load
32
+ % these UBJSON data, you need to manually set this
33
+ % flag to 1.
34
+ %
35
+ % output:
36
+ % dat: a cell array, where {...} blocks are converted into cell arrays,
37
+ % and [...] are converted to arrays
38
+ %
39
+ % examples:
40
+ % obj=struct('string','value','array',[1 2 3]);
41
+ % ubjdata=saveubjson('obj',obj);
42
+ % dat=loadubjson(ubjdata)
43
+ % dat=loadubjson(['examples' filesep 'example1.ubj'])
44
+ % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
45
+ %
46
+ % license:
47
+ % BSD License, see LICENSE_BSD.txt files for details
48
+ %
49
+ % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
50
+ %
51
+
52
+ global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
53
+
54
+ if(regexp(fname,'[\{\}\]\[]','once'))
55
+ string=fname;
56
+ elseif(exist(fname,'file'))
57
+ fid = fopen(fname,'rb');
58
+ string = fread(fid,inf,'uint8=>char')';
59
+ fclose(fid);
60
+ else
61
+ error('input file does not exist');
62
+ end
63
+
64
+ pos = 1; len = length(string); inStr = string;
65
+ isoct=exist('OCTAVE_VERSION','builtin');
66
+ arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
67
+ jstr=regexprep(inStr,'\\\\',' ');
68
+ escquote=regexp(jstr,'\\"');
69
+ arraytoken=sort([arraytoken escquote]);
70
+
71
+ % String delimiters and escape chars identified to improve speed:
72
+ esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
73
+ index_esc = 1; len_esc = length(esc);
74
+
75
+ opt=varargin2struct(varargin{:});
76
+ fileendian=upper(jsonopt('IntEndian','B',opt));
77
+ [os,maxelem,systemendian]=computer;
78
+
79
+ jsoncount=1;
80
+ while pos <= len
81
+ switch(next_char)
82
+ case '{'
83
+ data{jsoncount} = parse_object(opt);
84
+ case '['
85
+ data{jsoncount} = parse_array(opt);
86
+ otherwise
87
+ error_pos('Outer level structure must be an object or an array');
88
+ end
89
+ jsoncount=jsoncount+1;
90
+ end % while
91
+
92
+ jsoncount=length(data);
93
+ if(jsoncount==1 && iscell(data))
94
+ data=data{1};
95
+ end
96
+
97
+ %%-------------------------------------------------------------------------
98
+ function object = parse_object(varargin)
99
+ parse_char('{');
100
+ object = [];
101
+ type='';
102
+ count=-1;
103
+ if(next_char == '$')
104
+ type=inStr(pos+1); % TODO
105
+ pos=pos+2;
106
+ end
107
+ if(next_char == '#')
108
+ pos=pos+1;
109
+ count=double(parse_number());
110
+ end
111
+ if next_char ~= '}'
112
+ num=0;
113
+ while 1
114
+ if(jsonopt('NameIsString',0,varargin{:}))
115
+ str = parseStr(varargin{:});
116
+ else
117
+ str = parse_name(varargin{:});
118
+ end
119
+ if isempty(str)
120
+ error_pos('Name of value at position %d cannot be empty');
121
+ end
122
+ %parse_char(':');
123
+ val = parse_value(varargin{:});
124
+ num=num+1;
125
+ object.(valid_field(str))=val;
126
+ if next_char == '}' || (count>=0 && num>=count)
127
+ break;
128
+ end
129
+ %parse_char(',');
130
+ end
131
+ end
132
+ if(count==-1)
133
+ parse_char('}');
134
+ end
135
+ if(isstruct(object))
136
+ object=struct2jdata(object);
137
+ end
138
+
139
+ %%-------------------------------------------------------------------------
140
+ function [cid,len]=elem_info(type)
141
+ id=strfind('iUIlLdD',type);
142
+ dataclass={'int8','uint8','int16','int32','int64','single','double'};
143
+ bytelen=[1,1,2,4,8,4,8];
144
+ if(id>0)
145
+ cid=dataclass{id};
146
+ len=bytelen(id);
147
+ else
148
+ error_pos('unsupported type at position %d');
149
+ end
150
+ %%-------------------------------------------------------------------------
151
+
152
+
153
+ function [data, adv]=parse_block(type,count,varargin)
154
+ global pos inStr isoct fileendian systemendian
155
+ [cid,len]=elem_info(type);
156
+ datastr=inStr(pos:pos+len*count-1);
157
+ if(isoct)
158
+ newdata=int8(datastr);
159
+ else
160
+ newdata=uint8(datastr);
161
+ end
162
+ id=strfind('iUIlLdD',type);
163
+ if(id<=5 && fileendian~=systemendian)
164
+ newdata=swapbytes(typecast(newdata,cid));
165
+ end
166
+ data=typecast(newdata,cid);
167
+ adv=double(len*count);
168
+
169
+ %%-------------------------------------------------------------------------
170
+
171
+
172
+ function object = parse_array(varargin) % JSON array is written in row-major order
173
+ global pos inStr
174
+ parse_char('[');
175
+ object = cell(0, 1);
176
+ dim=[];
177
+ type='';
178
+ count=-1;
179
+ if(next_char == '$')
180
+ type=inStr(pos+1);
181
+ pos=pos+2;
182
+ end
183
+ if(next_char == '#')
184
+ pos=pos+1;
185
+ if(next_char=='[')
186
+ dim=parse_array(varargin{:});
187
+ count=prod(double(dim));
188
+ else
189
+ count=double(parse_number());
190
+ end
191
+ end
192
+ if(~isempty(type))
193
+ if(count>=0)
194
+ [object, adv]=parse_block(type,count,varargin{:});
195
+ if(~isempty(dim))
196
+ object=reshape(object,dim);
197
+ end
198
+ pos=pos+adv;
199
+ return;
200
+ else
201
+ endpos=matching_bracket(inStr,pos);
202
+ [cid,len]=elem_info(type);
203
+ count=(endpos-pos)/len;
204
+ [object, adv]=parse_block(type,count,varargin{:});
205
+ pos=pos+adv;
206
+ parse_char(']');
207
+ return;
208
+ end
209
+ end
210
+ if next_char ~= ']'
211
+ while 1
212
+ val = parse_value(varargin{:});
213
+ object{end+1} = val;
214
+ if next_char == ']'
215
+ break;
216
+ end
217
+ %parse_char(',');
218
+ end
219
+ end
220
+ if(jsonopt('SimplifyCell',0,varargin{:})==1)
221
+ try
222
+ oldobj=object;
223
+ object=cell2mat(object')';
224
+ if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
225
+ object=oldobj;
226
+ elseif(size(object,1)>1 && ismatrix(object))
227
+ object=object';
228
+ end
229
+ catch
230
+ end
231
+ end
232
+ if(count==-1)
233
+ parse_char(']');
234
+ end
235
+
236
+ %%-------------------------------------------------------------------------
237
+
238
+ function parse_char(c)
239
+ global pos inStr len
240
+ skip_whitespace;
241
+ if pos > len || inStr(pos) ~= c
242
+ error_pos(sprintf('Expected %c at position %%d', c));
243
+ else
244
+ pos = pos + 1;
245
+ skip_whitespace;
246
+ end
247
+
248
+ %%-------------------------------------------------------------------------
249
+
250
+ function c = next_char
251
+ global pos inStr len
252
+ skip_whitespace;
253
+ if pos > len
254
+ c = [];
255
+ else
256
+ c = inStr(pos);
257
+ end
258
+
259
+ %%-------------------------------------------------------------------------
260
+
261
+ function skip_whitespace
262
+ global pos inStr len
263
+ while pos <= len && isspace(inStr(pos))
264
+ pos = pos + 1;
265
+ end
266
+
267
+ %%-------------------------------------------------------------------------
268
+ function str = parse_name(varargin)
269
+ global pos inStr
270
+ bytelen=double(parse_number());
271
+ if(length(inStr)>=pos+bytelen-1)
272
+ str=inStr(pos:pos+bytelen-1);
273
+ pos=pos+bytelen;
274
+ else
275
+ error_pos('End of file while expecting end of name');
276
+ end
277
+ %%-------------------------------------------------------------------------
278
+
279
+ function str = parseStr(varargin)
280
+ global pos inStr
281
+ % len, ns = length(inStr), keyboard
282
+ type=inStr(pos);
283
+ if type ~= 'S' && type ~= 'C' && type ~= 'H'
284
+ error_pos('String starting with S expected at position %d');
285
+ else
286
+ pos = pos + 1;
287
+ end
288
+ if(type == 'C')
289
+ str=inStr(pos);
290
+ pos=pos+1;
291
+ return;
292
+ end
293
+ bytelen=double(parse_number());
294
+ if(length(inStr)>=pos+bytelen-1)
295
+ str=inStr(pos:pos+bytelen-1);
296
+ pos=pos+bytelen;
297
+ else
298
+ error_pos('End of file while expecting end of inStr');
299
+ end
300
+
301
+ %%-------------------------------------------------------------------------
302
+
303
+ function num = parse_number(varargin)
304
+ global pos inStr isoct fileendian systemendian
305
+ id=strfind('iUIlLdD',inStr(pos));
306
+ if(isempty(id))
307
+ error_pos('expecting a number at position %d');
308
+ end
309
+ type={'int8','uint8','int16','int32','int64','single','double'};
310
+ bytelen=[1,1,2,4,8,4,8];
311
+ datastr=inStr(pos+1:pos+bytelen(id));
312
+ if(isoct)
313
+ newdata=int8(datastr);
314
+ else
315
+ newdata=uint8(datastr);
316
+ end
317
+ if(id<=5 && fileendian~=systemendian)
318
+ newdata=swapbytes(typecast(newdata,type{id}));
319
+ end
320
+ num=typecast(newdata,type{id});
321
+ pos = pos + bytelen(id)+1;
322
+
323
+ %%-------------------------------------------------------------------------
324
+
325
+ function val = parse_value(varargin)
326
+ global pos inStr
327
+
328
+ switch(inStr(pos))
329
+ case {'S','C','H'}
330
+ val = parseStr(varargin{:});
331
+ return;
332
+ case '['
333
+ val = parse_array(varargin{:});
334
+ return;
335
+ case '{'
336
+ val = parse_object(varargin{:});
337
+ return;
338
+ case {'i','U','I','l','L','d','D'}
339
+ val = parse_number(varargin{:});
340
+ return;
341
+ case 'T'
342
+ val = true;
343
+ pos = pos + 1;
344
+ return;
345
+ case 'F'
346
+ val = false;
347
+ pos = pos + 1;
348
+ return;
349
+ case {'Z','N'}
350
+ val = [];
351
+ pos = pos + 1;
352
+ return;
353
+ end
354
+ error_pos('Value expected at position %d');
355
+ %%-------------------------------------------------------------------------
356
+
357
+ function error_pos(msg)
358
+ global pos inStr len
359
+ poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
360
+ if poShow(3) == poShow(2)
361
+ poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
362
+ end
363
+ msg = [sprintf(msg, pos) ': ' ...
364
+ inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
365
+ error( ['JSONparser:invalidFormat: ' msg] );
366
+
367
+ %%-------------------------------------------------------------------------
368
+
369
+ function str = valid_field(str)
370
+ global isoct
371
+ % From MATLAB doc: field names must begin with a letter, which may be
372
+ % followed by any combination of letters, digits, and underscores.
373
+ % Invalid characters will be converted to underscores, and the prefix
374
+ % "x0x[Hex code]_" will be added if the first character is not a letter.
375
+ pos=regexp(str,'^[^A-Za-z]','once');
376
+ if(~isempty(pos))
377
+ if(~isoct)
378
+ str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
379
+ else
380
+ str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
381
+ end
382
+ end
383
+ if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
384
+ return;
385
+ end
386
+ if(~isoct)
387
+ str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
388
+ else
389
+ pos=regexp(str,'[^0-9A-Za-z_]');
390
+ if(isempty(pos))
391
+ return;
392
+ end
393
+ str0=str;
394
+ pos0=[0 pos(:)' length(str)];
395
+ str='';
396
+ for i=1:length(pos)
397
+ str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
398
+ end
399
+ if(pos(end)~=length(str))
400
+ str=[str str0(pos0(end-1)+1:pos0(end))];
401
+ end
402
+ end
403
+ %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
404
+
405
+ %%-------------------------------------------------------------------------
406
+ function endpos = matching_quote(str,pos)
407
+ len=length(str);
408
+ while(pos<len)
409
+ if(str(pos)=='"')
410
+ if(~(pos>1 && str(pos-1)=='\'))
411
+ endpos=pos;
412
+ return;
413
+ end
414
+ end
415
+ pos=pos+1;
416
+ end
417
+ error('unmatched quotation mark');
418
+ %%-------------------------------------------------------------------------
419
+ function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
420
+ global arraytoken
421
+ level=1;
422
+ maxlevel=level;
423
+ endpos=0;
424
+ bpos=arraytoken(arraytoken>=pos);
425
+ tokens=str(bpos);
426
+ len=length(tokens);
427
+ pos=1;
428
+ e1l=[];
429
+ e1r=[];
430
+ while(pos<=len)
431
+ c=tokens(pos);
432
+ if(c==']')
433
+ level=level-1;
434
+ if(isempty(e1r))
435
+ e1r=bpos(pos);
436
+ end
437
+ if(level==0)
438
+ endpos=bpos(pos);
439
+ return
440
+ end
441
+ end
442
+ if(c=='[')
443
+ if(isempty(e1l))
444
+ e1l=bpos(pos);
445
+ end
446
+ level=level+1;
447
+ maxlevel=max(maxlevel,level);
448
+ end
449
+ if(c=='"')
450
+ pos=matching_quote(tokens,pos+1);
451
+ end
452
+ pos=pos+1;
453
+ end
454
+ if(endpos==0)
455
+ error('unmatched "]"');
456
+ end
457
+
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/mergestruct.m ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function s=mergestruct(s1,s2)
2
+ %
3
+ % s=mergestruct(s1,s2)
4
+ %
5
+ % merge two struct objects into one
6
+ %
7
+ % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
8
+ % date: 2012/12/22
9
+ %
10
+ % input:
11
+ % s1,s2: a struct object, s1 and s2 can not be arrays
12
+ %
13
+ % output:
14
+ % s: the merged struct object. fields in s1 and s2 will be combined in s.
15
+ %
16
+ % license:
17
+ % BSD License, see LICENSE_BSD.txt files for details
18
+ %
19
+ % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
20
+ %
21
+
22
+ if(~isstruct(s1) || ~isstruct(s2))
23
+ error('input parameters contain non-struct');
24
+ end
25
+ if(length(s1)>1 || length(s2)>1)
26
+ error('can not merge struct arrays');
27
+ end
28
+ fn=fieldnames(s2);
29
+ s=s1;
30
+ for i=1:length(fn)
31
+ s=setfield(s,fn{i},getfield(s2,fn{i}));
32
+ end
33
+
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/savejson.m ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function json=savejson(rootname,obj,varargin)
2
+ %
3
+ % json=savejson(rootname,obj,filename)
4
+ % or
5
+ % json=savejson(rootname,obj,opt)
6
+ % json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
7
+ %
8
+ % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
9
+ % Object Notation) string
10
+ %
11
+ % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
12
+ % created on 2011/09/09
13
+ %
14
+ % $Id$
15
+ %
16
+ % input:
17
+ % rootname: the name of the root-object, when set to '', the root name
18
+ % is ignored, however, when opt.ForceRootName is set to 1 (see below),
19
+ % the MATLAB variable name will be used as the root name.
20
+ % obj: a MATLAB object (array, cell, cell array, struct, struct array,
21
+ % class instance).
22
+ % filename: a string for the file name to save the output JSON data.
23
+ % opt: a struct for additional options, ignore to use default values.
24
+ % opt can have the following fields (first in [.|.] is the default)
25
+ %
26
+ % opt.FileName [''|string]: a file name to save the output JSON data
27
+ % opt.FloatFormat ['%.10g'|string]: format to show each numeric element
28
+ % of a 1D/2D array;
29
+ % opt.ArrayIndent [1|0]: if 1, output explicit data array with
30
+ % precedent indentation; if 0, no indentation
31
+ % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
32
+ % array in JSON array format; if sets to 1, an
33
+ % array will be shown as a struct with fields
34
+ % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
35
+ % sparse arrays, the non-zero elements will be
36
+ % saved to _ArrayData_ field in triplet-format i.e.
37
+ % (ix,iy,val) and "_ArrayIsSparse_" will be added
38
+ % with a value of 1; for a complex array, the
39
+ % _ArrayData_ array will include two columns
40
+ % (4 for sparse) to record the real and imaginary
41
+ % parts, and also "_ArrayIsComplex_":1 is added.
42
+ % opt.ParseLogical [0|1]: if this is set to 1, logical array elem
43
+ % will use true/false rather than 1/0.
44
+ % opt.SingletArray [0|1]: if this is set to 1, arrays with a single
45
+ % numerical element will be shown without a square
46
+ % bracket, unless it is the root object; if 0, square
47
+ % brackets are forced for any numerical arrays.
48
+ % opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
49
+ % even it has only one element; if 0, brackets
50
+ % are ignored when a cell has only 1 element.
51
+ % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
52
+ % will use the name of the passed obj variable as the
53
+ % root object name; if obj is an expression and
54
+ % does not have a name, 'root' will be used; if this
55
+ % is set to 0 and rootname is empty, the root level
56
+ % will be merged down to the lower level.
57
+ % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
58
+ % to represent +/-Inf. The matched pattern is '([-+]*)Inf'
59
+ % and $1 represents the sign. For those who want to use
60
+ % 1e999 to represent Inf, they can set opt.Inf to '$11e999'
61
+ % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
62
+ % to represent NaN
63
+ % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
64
+ % for example, if opt.JSONP='foo', the JSON data is
65
+ % wrapped inside a function call as 'foo(...);'
66
+ % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
67
+ % back to the string form
68
+ % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
69
+ % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
70
+ %
71
+ % opt can be replaced by a list of ('param',value) pairs. The param
72
+ % string is equivallent to a field in opt and is case sensitive.
73
+ % output:
74
+ % json: a string in the JSON format (see http://json.org)
75
+ %
76
+ % examples:
77
+ % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
78
+ % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
79
+ % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
80
+ % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
81
+ % 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
82
+ % 'SpecialData',[nan, inf, -inf]);
83
+ % savejson('jmesh',jsonmesh)
84
+ % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
85
+ %
86
+ % license:
87
+ % BSD License, see LICENSE_BSD.txt files for details
88
+ %
89
+ % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
90
+ %
91
+
92
+ if(nargin==1)
93
+ varname=inputname(1);
94
+ obj=rootname;
95
+ if(isempty(varname))
96
+ varname='root';
97
+ end
98
+ rootname=varname;
99
+ else
100
+ varname=inputname(2);
101
+ end
102
+ if(length(varargin)==1 && ischar(varargin{1}))
103
+ opt=struct('filename',varargin{1});
104
+ else
105
+ opt=varargin2struct(varargin{:});
106
+ end
107
+ opt.IsOctave=exist('OCTAVE_VERSION','builtin');
108
+ if(isfield(opt,'norowbracket'))
109
+ warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
110
+ if(~isfield(opt,'singletarray'))
111
+ opt.singletarray=not(opt.norowbracket);
112
+ end
113
+ end
114
+ rootisarray=0;
115
+ rootlevel=1;
116
+ forceroot=jsonopt('ForceRootName',0,opt);
117
+ if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
118
+ iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
119
+ rootisarray=1;
120
+ rootlevel=0;
121
+ else
122
+ if(isempty(rootname))
123
+ rootname=varname;
124
+ end
125
+ end
126
+ if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
127
+ rootname='root';
128
+ end
129
+
130
+ whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
131
+ if(jsonopt('Compact',0,opt)==1)
132
+ whitespaces=struct('tab','','newline','','sep',',');
133
+ end
134
+ if(~isfield(opt,'whitespaces_'))
135
+ opt.whitespaces_=whitespaces;
136
+ end
137
+
138
+ nl=whitespaces.newline;
139
+
140
+ json=obj2json(rootname,obj,rootlevel,opt);
141
+ if(rootisarray)
142
+ json=sprintf('%s%s',json,nl);
143
+ else
144
+ json=sprintf('{%s%s%s}\n',nl,json,nl);
145
+ end
146
+
147
+ jsonp=jsonopt('JSONP','',opt);
148
+ if(~isempty(jsonp))
149
+ json=sprintf('%s(%s);%s',jsonp,json,nl);
150
+ end
151
+
152
+ % save to a file if FileName is set, suggested by Patrick Rapin
153
+ filename=jsonopt('FileName','',opt);
154
+ if(~isempty(filename))
155
+ if(jsonopt('SaveBinary',0,opt)==1)
156
+ fid = fopen(filename, 'wb');
157
+ fwrite(fid,json);
158
+ else
159
+ fid = fopen(filename, 'wt');
160
+ fwrite(fid,json,'char');
161
+ end
162
+ fclose(fid);
163
+ end
164
+
165
+ %%-------------------------------------------------------------------------
166
+ function txt=obj2json(name,item,level,varargin)
167
+
168
+ if(iscell(item))
169
+ txt=cell2json(name,item,level,varargin{:});
170
+ elseif(isstruct(item))
171
+ txt=struct2json(name,item,level,varargin{:});
172
+ elseif(ischar(item))
173
+ txt=str2json(name,item,level,varargin{:});
174
+ elseif(isobject(item))
175
+ txt=matlabobject2json(name,item,level,varargin{:});
176
+ else
177
+ txt=mat2json(name,item,level,varargin{:});
178
+ end
179
+
180
+ %%-------------------------------------------------------------------------
181
+ function txt=cell2json(name,item,level,varargin)
182
+ txt={};
183
+ if(~iscell(item))
184
+ error('input is not a cell');
185
+ end
186
+
187
+ dim=size(item);
188
+ if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
189
+ item=reshape(item,dim(1),numel(item)/dim(1));
190
+ dim=size(item);
191
+ end
192
+ len=numel(item);
193
+ ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
194
+ padding0=repmat(ws.tab,1,level);
195
+ padding2=repmat(ws.tab,1,level+1);
196
+ nl=ws.newline;
197
+ bracketlevel=~jsonopt('singletcell',1,varargin{:});
198
+ if(len>bracketlevel)
199
+ if(~isempty(name))
200
+ txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; name='';
201
+ else
202
+ txt={padding0, '[', nl};
203
+ end
204
+ elseif(len==0)
205
+ if(~isempty(name))
206
+ txt={padding0, '"' checkname(name,varargin{:}) '": []'}; name='';
207
+ else
208
+ txt={padding0, '[]'};
209
+ end
210
+ end
211
+ for i=1:dim(1)
212
+ if(dim(1)>1)
213
+ txt(end+1:end+3)={padding2,'[',nl};
214
+ end
215
+ for j=1:dim(2)
216
+ txt{end+1}=obj2json(name,item{i,j},level+(dim(1)>1)+(len>bracketlevel),varargin{:});
217
+ if(j<dim(2))
218
+ txt(end+1:end+2)={',' nl};
219
+ end
220
+ end
221
+ if(dim(1)>1)
222
+ txt(end+1:end+3)={nl,padding2,']'};
223
+ end
224
+ if(i<dim(1))
225
+ txt(end+1:end+2)={',' nl};
226
+ end
227
+ %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
228
+ end
229
+ if(len>bracketlevel)
230
+ txt(end+1:end+3)={nl,padding0,']'};
231
+ end
232
+ txt = sprintf('%s',txt{:});
233
+
234
+ %%-------------------------------------------------------------------------
235
+ function txt=struct2json(name,item,level,varargin)
236
+ txt={};
237
+ if(~isstruct(item))
238
+ error('input is not a struct');
239
+ end
240
+ dim=size(item);
241
+ if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
242
+ item=reshape(item,dim(1),numel(item)/dim(1));
243
+ dim=size(item);
244
+ end
245
+ len=numel(item);
246
+ forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
247
+ ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
248
+ ws=jsonopt('whitespaces_',ws,varargin{:});
249
+ padding0=repmat(ws.tab,1,level);
250
+ padding2=repmat(ws.tab,1,level+1);
251
+ padding1=repmat(ws.tab,1,level+(dim(1)>1)+forcearray);
252
+ nl=ws.newline;
253
+
254
+ if(isempty(item))
255
+ if(~isempty(name))
256
+ txt={padding0, '"', checkname(name,varargin{:}),'": []'};
257
+ else
258
+ txt={padding0, '[]'};
259
+ end
260
+ return;
261
+ end
262
+ if(~isempty(name))
263
+ if(forcearray)
264
+ txt={padding0, '"', checkname(name,varargin{:}),'": [', nl};
265
+ end
266
+ else
267
+ if(forcearray)
268
+ txt={padding0, '[', nl};
269
+ end
270
+ end
271
+ for j=1:dim(2)
272
+ if(dim(1)>1)
273
+ txt(end+1:end+3)={padding2,'[',nl};
274
+ end
275
+ for i=1:dim(1)
276
+ names = fieldnames(item(i,j));
277
+ if(~isempty(name) && len==1 && ~forcearray)
278
+ txt(end+1:end+5)={padding1, '"', checkname(name,varargin{:}),'": {', nl};
279
+ else
280
+ txt(end+1:end+3)={padding1, '{', nl};
281
+ end
282
+ if(~isempty(names))
283
+ for e=1:length(names)
284
+ txt{end+1}=obj2json(names{e},item(i,j).(names{e}),...
285
+ level+(dim(1)>1)+1+forcearray,varargin{:});
286
+ if(e<length(names))
287
+ txt{end+1}=',';
288
+ end
289
+ txt{end+1}=nl;
290
+ end
291
+ end
292
+ txt(end+1:end+2)={padding1,'}'};
293
+ if(i<dim(1))
294
+ txt(end+1:end+2)={',' nl};
295
+ end
296
+ end
297
+ if(dim(1)>1)
298
+ txt(end+1:end+3)={nl,padding2,']'};
299
+ end
300
+ if(j<dim(2))
301
+ txt(end+1:end+2)={',' nl};
302
+ end
303
+ end
304
+ if(forcearray)
305
+ txt(end+1:end+3)={nl,padding0,']'};
306
+ end
307
+ txt = sprintf('%s',txt{:});
308
+
309
+ %%-------------------------------------------------------------------------
310
+ function txt=str2json(name,item,level,varargin)
311
+ txt={};
312
+ if(~ischar(item))
313
+ error('input is not a string');
314
+ end
315
+ item=reshape(item, max(size(item),[1 0]));
316
+ len=size(item,1);
317
+ ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
318
+ ws=jsonopt('whitespaces_',ws,varargin{:});
319
+ padding1=repmat(ws.tab,1,level);
320
+ padding0=repmat(ws.tab,1,level+1);
321
+ nl=ws.newline;
322
+ sep=ws.sep;
323
+
324
+ if(~isempty(name))
325
+ if(len>1)
326
+ txt={padding1, '"', checkname(name,varargin{:}),'": [', nl};
327
+ end
328
+ else
329
+ if(len>1)
330
+ txt={padding1, '[', nl};
331
+ end
332
+ end
333
+ for e=1:len
334
+ val=escapejsonstring(item(e,:));
335
+ if(len==1)
336
+ obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
337
+ if(isempty(name))
338
+ obj=['"',val,'"'];
339
+ end
340
+ txt(end+1:end+2)={padding1, obj};
341
+ else
342
+ txt(end+1:end+4)={padding0,'"',val,'"'};
343
+ end
344
+ if(e==len)
345
+ sep='';
346
+ end
347
+ txt{end+1}=sep;
348
+ end
349
+ if(len>1)
350
+ txt(end+1:end+3)={nl,padding1,']'};
351
+ end
352
+ txt = sprintf('%s',txt{:});
353
+
354
+ %%-------------------------------------------------------------------------
355
+ function txt=mat2json(name,item,level,varargin)
356
+ if(~isnumeric(item) && ~islogical(item))
357
+ error('input is not an array');
358
+ end
359
+ ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
360
+ ws=jsonopt('whitespaces_',ws,varargin{:});
361
+ padding1=repmat(ws.tab,1,level);
362
+ padding0=repmat(ws.tab,1,level+1);
363
+ nl=ws.newline;
364
+ sep=ws.sep;
365
+
366
+ if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
367
+ (isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
368
+ if(isempty(name))
369
+ txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
370
+ padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
371
+ else
372
+ txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
373
+ padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
374
+ end
375
+ else
376
+ if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0 && level>0)
377
+ numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
378
+ else
379
+ numtxt=matdata2json(item,level+1,varargin{:});
380
+ end
381
+ if(isempty(name))
382
+ txt=sprintf('%s%s',padding1,numtxt);
383
+ else
384
+ if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
385
+ txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
386
+ else
387
+ txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
388
+ end
389
+ end
390
+ return;
391
+ end
392
+ dataformat='%s%s%s%s%s';
393
+
394
+ if(issparse(item))
395
+ [ix,iy]=find(item);
396
+ data=full(item(find(item)));
397
+ if(~isreal(item))
398
+ data=[real(data(:)),imag(data(:))];
399
+ if(size(item,1)==1)
400
+ % Kludge to have data's 'transposedness' match item's.
401
+ % (Necessary for complex row vector handling below.)
402
+ data=data';
403
+ end
404
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
405
+ end
406
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
407
+ if(size(item,1)==1)
408
+ % Row vector, store only column indices.
409
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
410
+ matdata2json([iy(:),data'],level+2,varargin{:}), nl);
411
+ elseif(size(item,2)==1)
412
+ % Column vector, store only row indices.
413
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
414
+ matdata2json([ix,data],level+2,varargin{:}), nl);
415
+ else
416
+ % General case, store row and column indices.
417
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
418
+ matdata2json([ix,iy,data],level+2,varargin{:}), nl);
419
+ end
420
+ else
421
+ if(isreal(item))
422
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
423
+ matdata2json(item(:)',level+2,varargin{:}), nl);
424
+ else
425
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
426
+ txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
427
+ matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
428
+ end
429
+ end
430
+ txt=sprintf('%s%s%s',txt,padding1,'}');
431
+
432
+ %%-------------------------------------------------------------------------
433
+ function txt=matlabobject2json(name,item,level,varargin)
434
+ if numel(item) == 0 %empty object
435
+ st = struct();
436
+ else
437
+ % "st = struct(item);" would produce an inmutable warning, because it
438
+ % make the protected and private properties visible. Instead we get the
439
+ % visible properties
440
+ propertynames = properties(item);
441
+ for p = 1:numel(propertynames)
442
+ for o = numel(item):-1:1 % aray of objects
443
+ st(o).(propertynames{p}) = item(o).(propertynames{p});
444
+ end
445
+ end
446
+ end
447
+ txt=struct2json(name,st,level,varargin{:});
448
+
449
+ %%-------------------------------------------------------------------------
450
+ function txt=matdata2json(mat,level,varargin)
451
+
452
+ ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
453
+ ws=jsonopt('whitespaces_',ws,varargin{:});
454
+ tab=ws.tab;
455
+ nl=ws.newline;
456
+
457
+ if(size(mat,1)==1)
458
+ pre='';
459
+ post='';
460
+ level=level-1;
461
+ else
462
+ pre=sprintf('[%s',nl);
463
+ post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
464
+ end
465
+
466
+ if(isempty(mat))
467
+ txt='[]';
468
+ return;
469
+ end
470
+ floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
471
+ %if(numel(mat)>1)
472
+ formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
473
+ %else
474
+ % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
475
+ %end
476
+
477
+ if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
478
+ formatstr=[repmat(tab,1,level) formatstr];
479
+ end
480
+
481
+ txt=sprintf(formatstr,mat');
482
+ txt(end-length(nl):end)=[];
483
+ if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
484
+ txt=regexprep(txt,'1','true');
485
+ txt=regexprep(txt,'0','false');
486
+ end
487
+ %txt=regexprep(mat2str(mat),'\s+',',');
488
+ %txt=regexprep(txt,';',sprintf('],\n['));
489
+ % if(nargin>=2 && size(mat,1)>1)
490
+ % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
491
+ % end
492
+ txt=[pre txt post];
493
+ if(any(isinf(mat(:))))
494
+ txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
495
+ end
496
+ if(any(isnan(mat(:))))
497
+ txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
498
+ end
499
+
500
+ %%-------------------------------------------------------------------------
501
+ function newname=checkname(name,varargin)
502
+ isunpack=jsonopt('UnpackHex',1,varargin{:});
503
+ newname=name;
504
+ if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
505
+ return
506
+ end
507
+ if(isunpack)
508
+ isoct=jsonopt('IsOctave',0,varargin{:});
509
+ if(~isoct)
510
+ newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
511
+ else
512
+ pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
513
+ pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
514
+ if(isempty(pos))
515
+ return;
516
+ end
517
+ str0=name;
518
+ pos0=[0 pend(:)' length(name)];
519
+ newname='';
520
+ for i=1:length(pos)
521
+ newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
522
+ end
523
+ if(pos(end)~=length(name))
524
+ newname=[newname str0(pos0(end-1)+1:pos0(end))];
525
+ end
526
+ end
527
+ end
528
+
529
+ %%-------------------------------------------------------------------------
530
+ function newstr=escapejsonstring(str)
531
+ newstr=str;
532
+ isoct=exist('OCTAVE_VERSION','builtin');
533
+ if(isoct)
534
+ vv=sscanf(OCTAVE_VERSION,'%f');
535
+ if(vv(1)>=3.8)
536
+ isoct=0;
537
+ end
538
+ end
539
+ if(isoct)
540
+ escapechars={'\\','\"','\/','\a','\f','\n','\r','\t','\v'};
541
+ for i=1:length(escapechars);
542
+ newstr=regexprep(newstr,escapechars{i},escapechars{i});
543
+ end
544
+ newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\$1');
545
+ else
546
+ escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'};
547
+ for i=1:length(escapechars);
548
+ newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
549
+ end
550
+ newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\\$1');
551
+ end
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/saveubjson.m ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function json=saveubjson(rootname,obj,varargin)
2
+ %
3
+ % json=saveubjson(rootname,obj,filename)
4
+ % or
5
+ % json=saveubjson(rootname,obj,opt)
6
+ % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
7
+ %
8
+ % convert a MATLAB object (cell, struct or array) into a Universal
9
+ % Binary JSON (UBJSON) binary string
10
+ %
11
+ % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
12
+ % created on 2013/08/17
13
+ %
14
+ % $Id$
15
+ %
16
+ % input:
17
+ % rootname: the name of the root-object, when set to '', the root name
18
+ % is ignored, however, when opt.ForceRootName is set to 1 (see below),
19
+ % the MATLAB variable name will be used as the root name.
20
+ % obj: a MATLAB object (array, cell, cell array, struct, struct array,
21
+ % class instance)
22
+ % filename: a string for the file name to save the output UBJSON data
23
+ % opt: a struct for additional options, ignore to use default values.
24
+ % opt can have the following fields (first in [.|.] is the default)
25
+ %
26
+ % opt.FileName [''|string]: a file name to save the output JSON data
27
+ % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
28
+ % array in JSON array format; if sets to 1, an
29
+ % array will be shown as a struct with fields
30
+ % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
31
+ % sparse arrays, the non-zero elements will be
32
+ % saved to _ArrayData_ field in triplet-format i.e.
33
+ % (ix,iy,val) and "_ArrayIsSparse_" will be added
34
+ % with a value of 1; for a complex array, the
35
+ % _ArrayData_ array will include two columns
36
+ % (4 for sparse) to record the real and imaginary
37
+ % parts, and also "_ArrayIsComplex_":1 is added.
38
+ % opt.ParseLogical [1|0]: if this is set to 1, logical array elem
39
+ % will use true/false rather than 1/0.
40
+ % opt.SingletArray [0|1]: if this is set to 1, arrays with a single
41
+ % numerical element will be shown without a square
42
+ % bracket, unless it is the root object; if 0, square
43
+ % brackets are forced for any numerical arrays.
44
+ % opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
45
+ % even it has only one element; if 0, brackets
46
+ % are ignored when a cell has only 1 element.
47
+ % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
48
+ % will use the name of the passed obj variable as the
49
+ % root object name; if obj is an expression and
50
+ % does not have a name, 'root' will be used; if this
51
+ % is set to 0 and rootname is empty, the root level
52
+ % will be merged down to the lower level.
53
+ % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
54
+ % for example, if opt.JSON='foo', the JSON data is
55
+ % wrapped inside a function call as 'foo(...);'
56
+ % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
57
+ % back to the string form
58
+ %
59
+ % opt can be replaced by a list of ('param',value) pairs. The param
60
+ % string is equivallent to a field in opt and is case sensitive.
61
+ % output:
62
+ % json: a binary string in the UBJSON format (see http://ubjson.org)
63
+ %
64
+ % examples:
65
+ % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
66
+ % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
67
+ % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
68
+ % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
69
+ % 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
70
+ % 'SpecialData',[nan, inf, -inf]);
71
+ % saveubjson('jsonmesh',jsonmesh)
72
+ % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
73
+ %
74
+ % license:
75
+ % BSD License, see LICENSE_BSD.txt files for details
76
+ %
77
+ % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
78
+ %
79
+
80
+ if(nargin==1)
81
+ varname=inputname(1);
82
+ obj=rootname;
83
+ if(isempty(varname))
84
+ varname='root';
85
+ end
86
+ rootname=varname;
87
+ else
88
+ varname=inputname(2);
89
+ end
90
+ if(length(varargin)==1 && ischar(varargin{1}))
91
+ opt=struct('filename',varargin{1});
92
+ else
93
+ opt=varargin2struct(varargin{:});
94
+ end
95
+ opt.IsOctave=exist('OCTAVE_VERSION','builtin');
96
+ if(isfield(opt,'norowbracket'))
97
+ warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
98
+ if(~isfield(opt,'singletarray'))
99
+ opt.singletarray=not(opt.norowbracket);
100
+ end
101
+ end
102
+ rootisarray=0;
103
+ rootlevel=1;
104
+ forceroot=jsonopt('ForceRootName',0,opt);
105
+ if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
106
+ iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
107
+ rootisarray=1;
108
+ rootlevel=0;
109
+ else
110
+ if(isempty(rootname))
111
+ rootname=varname;
112
+ end
113
+ end
114
+ if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
115
+ rootname='root';
116
+ end
117
+ json=obj2ubjson(rootname,obj,rootlevel,opt);
118
+ if(~rootisarray)
119
+ json=['{' json '}'];
120
+ end
121
+
122
+ jsonp=jsonopt('JSONP','',opt);
123
+ if(~isempty(jsonp))
124
+ json=[jsonp '(' json ')'];
125
+ end
126
+
127
+ % save to a file if FileName is set, suggested by Patrick Rapin
128
+ filename=jsonopt('FileName','',opt);
129
+ if(~isempty(filename))
130
+ fid = fopen(filename, 'wb');
131
+ fwrite(fid,json);
132
+ fclose(fid);
133
+ end
134
+
135
+ %%-------------------------------------------------------------------------
136
+ function txt=obj2ubjson(name,item,level,varargin)
137
+
138
+ if(iscell(item))
139
+ txt=cell2ubjson(name,item,level,varargin{:});
140
+ elseif(isstruct(item))
141
+ txt=struct2ubjson(name,item,level,varargin{:});
142
+ elseif(ischar(item))
143
+ txt=str2ubjson(name,item,level,varargin{:});
144
+ elseif(isobject(item))
145
+ txt=matlabobject2ubjson(name,item,level,varargin{:});
146
+ else
147
+ txt=mat2ubjson(name,item,level,varargin{:});
148
+ end
149
+
150
+ %%-------------------------------------------------------------------------
151
+ function txt=cell2ubjson(name,item,level,varargin)
152
+ txt='';
153
+ if(~iscell(item))
154
+ error('input is not a cell');
155
+ end
156
+
157
+ dim=size(item);
158
+ if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
159
+ item=reshape(item,dim(1),numel(item)/dim(1));
160
+ dim=size(item);
161
+ end
162
+ bracketlevel=~jsonopt('singletcell',1,varargin{:});
163
+ len=numel(item); % let's handle 1D cell first
164
+ if(len>bracketlevel)
165
+ if(~isempty(name))
166
+ txt=[N_(checkname(name,varargin{:})) '[']; name='';
167
+ else
168
+ txt='[';
169
+ end
170
+ elseif(len==0)
171
+ if(~isempty(name))
172
+ txt=[N_(checkname(name,varargin{:})) 'Z']; name='';
173
+ else
174
+ txt='Z';
175
+ end
176
+ end
177
+ for j=1:dim(2)
178
+ if(dim(1)>1)
179
+ txt=[txt '['];
180
+ end
181
+ for i=1:dim(1)
182
+ txt=[txt obj2ubjson(name,item{i,j},level+(len>bracketlevel),varargin{:})];
183
+ end
184
+ if(dim(1)>1)
185
+ txt=[txt ']'];
186
+ end
187
+ end
188
+ if(len>bracketlevel)
189
+ txt=[txt ']'];
190
+ end
191
+
192
+ %%-------------------------------------------------------------------------
193
+ function txt=struct2ubjson(name,item,level,varargin)
194
+ txt='';
195
+ if(~isstruct(item))
196
+ error('input is not a struct');
197
+ end
198
+ dim=size(item);
199
+ if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
200
+ item=reshape(item,dim(1),numel(item)/dim(1));
201
+ dim=size(item);
202
+ end
203
+ len=numel(item);
204
+ forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
205
+
206
+ if(~isempty(name))
207
+ if(forcearray)
208
+ txt=[N_(checkname(name,varargin{:})) '['];
209
+ end
210
+ else
211
+ if(forcearray)
212
+ txt='[';
213
+ end
214
+ end
215
+ for j=1:dim(2)
216
+ if(dim(1)>1)
217
+ txt=[txt '['];
218
+ end
219
+ for i=1:dim(1)
220
+ names = fieldnames(item(i,j));
221
+ if(~isempty(name) && len==1 && ~forcearray)
222
+ txt=[txt N_(checkname(name,varargin{:})) '{'];
223
+ else
224
+ txt=[txt '{'];
225
+ end
226
+ if(~isempty(names))
227
+ for e=1:length(names)
228
+ txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),...
229
+ level+(dim(1)>1)+1+forcearray,varargin{:})];
230
+ end
231
+ end
232
+ txt=[txt '}'];
233
+ end
234
+ if(dim(1)>1)
235
+ txt=[txt ']'];
236
+ end
237
+ end
238
+ if(forcearray)
239
+ txt=[txt ']'];
240
+ end
241
+
242
+ %%-------------------------------------------------------------------------
243
+ function txt=str2ubjson(name,item,level,varargin)
244
+ txt='';
245
+ if(~ischar(item))
246
+ error('input is not a string');
247
+ end
248
+ item=reshape(item, max(size(item),[1 0]));
249
+ len=size(item,1);
250
+
251
+ if(~isempty(name))
252
+ if(len>1)
253
+ txt=[N_(checkname(name,varargin{:})) '['];
254
+ end
255
+ else
256
+ if(len>1)
257
+ txt='[';
258
+ end
259
+ end
260
+ for e=1:len
261
+ val=item(e,:);
262
+ if(len==1)
263
+ obj=[N_(checkname(name,varargin{:})) '' '',S_(val),''];
264
+ if(isempty(name))
265
+ obj=['',S_(val),''];
266
+ end
267
+ txt=[txt,'',obj];
268
+ else
269
+ txt=[txt,'',['',S_(val),'']];
270
+ end
271
+ end
272
+ if(len>1)
273
+ txt=[txt ']'];
274
+ end
275
+
276
+ %%-------------------------------------------------------------------------
277
+ function txt=mat2ubjson(name,item,level,varargin)
278
+ if(~isnumeric(item) && ~islogical(item))
279
+ error('input is not an array');
280
+ end
281
+
282
+ if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
283
+ (isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
284
+ cid=I_(uint32(max(size(item))));
285
+ if(isempty(name))
286
+ txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ];
287
+ else
288
+ if(isempty(item))
289
+ txt=[N_(checkname(name,varargin{:})),'Z'];
290
+ return;
291
+ else
292
+ txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1))];
293
+ end
294
+ end
295
+ else
296
+ if(isempty(name))
297
+ txt=matdata2ubjson(item,level+1,varargin{:});
298
+ else
299
+ if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
300
+ numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
301
+ txt=[N_(checkname(name,varargin{:})) numtxt];
302
+ else
303
+ txt=[N_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
304
+ end
305
+ end
306
+ return;
307
+ end
308
+ if(issparse(item))
309
+ [ix,iy]=find(item);
310
+ data=full(item(find(item)));
311
+ if(~isreal(item))
312
+ data=[real(data(:)),imag(data(:))];
313
+ if(size(item,1)==1)
314
+ % Kludge to have data's 'transposedness' match item's.
315
+ % (Necessary for complex row vector handling below.)
316
+ data=data';
317
+ end
318
+ txt=[txt,N_('_ArrayIsComplex_'),'T'];
319
+ end
320
+ txt=[txt,N_('_ArrayIsSparse_'),'T'];
321
+ if(size(item,1)==1)
322
+ % Row vector, store only column indices.
323
+ txt=[txt,N_('_ArrayData_'),...
324
+ matdata2ubjson([iy(:),data'],level+2,varargin{:})];
325
+ elseif(size(item,2)==1)
326
+ % Column vector, store only row indices.
327
+ txt=[txt,N_('_ArrayData_'),...
328
+ matdata2ubjson([ix,data],level+2,varargin{:})];
329
+ else
330
+ % General case, store row and column indices.
331
+ txt=[txt,N_('_ArrayData_'),...
332
+ matdata2ubjson([ix,iy,data],level+2,varargin{:})];
333
+ end
334
+ else
335
+ if(isreal(item))
336
+ txt=[txt,N_('_ArrayData_'),...
337
+ matdata2ubjson(item(:)',level+2,varargin{:})];
338
+ else
339
+ txt=[txt,N_('_ArrayIsComplex_'),'T'];
340
+ txt=[txt,N_('_ArrayData_'),...
341
+ matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
342
+ end
343
+ end
344
+ txt=[txt,'}'];
345
+
346
+ %%-------------------------------------------------------------------------
347
+ function txt=matlabobject2ubjson(name,item,level,varargin)
348
+ if numel(item) == 0 %empty object
349
+ st = struct();
350
+ else
351
+ % "st = struct(item);" would produce an inmutable warning, because it
352
+ % make the protected and private properties visible. Instead we get the
353
+ % visible properties
354
+ propertynames = properties(item);
355
+ for p = 1:numel(propertynames)
356
+ for o = numel(item):-1:1 % aray of objects
357
+ st(o).(propertynames{p}) = item(o).(propertynames{p});
358
+ end
359
+ end
360
+ end
361
+ txt=struct2ubjson(name,st,level,varargin{:});
362
+
363
+ %%-------------------------------------------------------------------------
364
+ function txt=matdata2ubjson(mat,level,varargin)
365
+ if(isempty(mat))
366
+ txt='Z';
367
+ return;
368
+ end
369
+ type='';
370
+ hasnegtive=(mat<0);
371
+ if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
372
+ if(isempty(hasnegtive))
373
+ if(max(mat(:))<=2^8)
374
+ type='U';
375
+ end
376
+ end
377
+ if(isempty(type))
378
+ % todo - need to consider negative ones separately
379
+ id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
380
+ if(isempty(id~=0))
381
+ error('high-precision data is not yet supported');
382
+ end
383
+ key='iIlL';
384
+ type=key(id~=0);
385
+ end
386
+ txt=[I_a(mat(:),type,size(mat))];
387
+ elseif(islogical(mat))
388
+ logicalval='FT';
389
+ if(numel(mat)==1)
390
+ txt=logicalval(mat+1);
391
+ else
392
+ txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
393
+ end
394
+ else
395
+ if(numel(mat)==1)
396
+ txt=['[' D_(mat) ']'];
397
+ else
398
+ txt=D_a(mat(:),'D',size(mat));
399
+ end
400
+ end
401
+
402
+ %txt=regexprep(mat2str(mat),'\s+',',');
403
+ %txt=regexprep(txt,';',sprintf('],['));
404
+ % if(nargin>=2 && size(mat,1)>1)
405
+ % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
406
+ % end
407
+ if(any(isinf(mat(:))))
408
+ txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
409
+ end
410
+ if(any(isnan(mat(:))))
411
+ txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
412
+ end
413
+
414
+ %%-------------------------------------------------------------------------
415
+ function newname=checkname(name,varargin)
416
+ isunpack=jsonopt('UnpackHex',1,varargin{:});
417
+ newname=name;
418
+ if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
419
+ return
420
+ end
421
+ if(isunpack)
422
+ isoct=jsonopt('IsOctave',0,varargin{:});
423
+ if(~isoct)
424
+ newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
425
+ else
426
+ pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
427
+ pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
428
+ if(isempty(pos))
429
+ return;
430
+ end
431
+ str0=name;
432
+ pos0=[0 pend(:)' length(name)];
433
+ newname='';
434
+ for i=1:length(pos)
435
+ newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
436
+ end
437
+ if(pos(end)~=length(name))
438
+ newname=[newname str0(pos0(end-1)+1:pos0(end))];
439
+ end
440
+ end
441
+ end
442
+ %%-------------------------------------------------------------------------
443
+ function val=N_(str)
444
+ val=[I_(int32(length(str))) str];
445
+ %%-------------------------------------------------------------------------
446
+ function val=S_(str)
447
+ if(length(str)==1)
448
+ val=['C' str];
449
+ else
450
+ val=['S' I_(int32(length(str))) str];
451
+ end
452
+ %%-------------------------------------------------------------------------
453
+ function val=I_(num)
454
+ if(~isinteger(num))
455
+ error('input is not an integer');
456
+ end
457
+ if(num>=0 && num<255)
458
+ val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
459
+ return;
460
+ end
461
+ key='iIlL';
462
+ cid={'int8','int16','int32','int64'};
463
+ for i=1:4
464
+ if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
465
+ val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
466
+ return;
467
+ end
468
+ end
469
+ error('unsupported integer');
470
+
471
+ %%-------------------------------------------------------------------------
472
+ function val=D_(num)
473
+ if(~isfloat(num))
474
+ error('input is not a float');
475
+ end
476
+
477
+ if(isa(num,'single'))
478
+ val=['d' data2byte(num,'uint8')];
479
+ else
480
+ val=['D' data2byte(num,'uint8')];
481
+ end
482
+ %%-------------------------------------------------------------------------
483
+ function data=I_a(num,type,dim,format)
484
+ id=find(ismember('iUIlL',type));
485
+
486
+ if(id==0)
487
+ error('unsupported integer array');
488
+ end
489
+
490
+ % based on UBJSON specs, all integer types are stored in big endian format
491
+
492
+ if(id==1)
493
+ data=data2byte(swapbytes(int8(num)),'uint8');
494
+ blen=1;
495
+ elseif(id==2)
496
+ data=data2byte(swapbytes(uint8(num)),'uint8');
497
+ blen=1;
498
+ elseif(id==3)
499
+ data=data2byte(swapbytes(int16(num)),'uint8');
500
+ blen=2;
501
+ elseif(id==4)
502
+ data=data2byte(swapbytes(int32(num)),'uint8');
503
+ blen=4;
504
+ elseif(id==5)
505
+ data=data2byte(swapbytes(int64(num)),'uint8');
506
+ blen=8;
507
+ end
508
+
509
+ if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
510
+ format='opt';
511
+ end
512
+ if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
513
+ if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
514
+ cid=I_(uint32(max(dim)));
515
+ data=['$' type '#' I_a(dim,cid(1)) data(:)'];
516
+ else
517
+ data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
518
+ end
519
+ data=['[' data(:)'];
520
+ else
521
+ data=reshape(data,blen,numel(data)/blen);
522
+ data(2:blen+1,:)=data;
523
+ data(1,:)=type;
524
+ data=data(:)';
525
+ data=['[' data(:)' ']'];
526
+ end
527
+ %%-------------------------------------------------------------------------
528
+ function data=D_a(num,type,dim,format)
529
+ id=find(ismember('dD',type));
530
+
531
+ if(id==0)
532
+ error('unsupported float array');
533
+ end
534
+
535
+ if(id==1)
536
+ data=data2byte(single(num),'uint8');
537
+ elseif(id==2)
538
+ data=data2byte(double(num),'uint8');
539
+ end
540
+
541
+ if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
542
+ format='opt';
543
+ end
544
+ if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
545
+ if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
546
+ cid=I_(uint32(max(dim)));
547
+ data=['$' type '#' I_a(dim,cid(1)) data(:)'];
548
+ else
549
+ data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
550
+ end
551
+ data=['[' data];
552
+ else
553
+ data=reshape(data,(id*4),length(data)/(id*4));
554
+ data(2:(id*4+1),:)=data;
555
+ data(1,:)=type;
556
+ data=data(:)';
557
+ data=['[' data(:)' ']'];
558
+ end
559
+ %%-------------------------------------------------------------------------
560
+ function bytes=data2byte(varargin)
561
+ bytes=typecast(varargin{:});
562
+ bytes=bytes(:)';
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/struct2jdata.m ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function newdata=struct2jdata(data,varargin)
2
+ %
3
+ % newdata=struct2jdata(data,opt,...)
4
+ %
5
+ % convert a JData object (in the form of a struct array) into an array
6
+ %
7
+ % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
8
+ %
9
+ % input:
10
+ % data: a struct array. If data contains JData keywords in the first
11
+ % level children, these fields are parsed and regrouped into a
12
+ % data object (arrays, trees, graphs etc) based on JData
13
+ % specification. The JData keywords are
14
+ % "_ArrayType_", "_ArraySize_", "_ArrayData_"
15
+ % "_ArrayIsSparse_", "_ArrayIsComplex_"
16
+ % opt: (optional) a list of 'Param',value pairs for additional options
17
+ % The supported options include
18
+ % 'Recursive', if set to 1, will apply the conversion to
19
+ % every child; 0 to disable
20
+ %
21
+ % output:
22
+ % newdata: the covnerted data if the input data does contain a JData
23
+ % structure; otherwise, the same as the input.
24
+ %
25
+ % examples:
26
+ % obj=struct('_ArrayType_','double','_ArraySize_',[2 3],
27
+ % '_ArrayIsSparse_',1 ,'_ArrayData_',null);
28
+ % ubjdata=struct2jdata(obj);
29
+ %
30
+ % license:
31
+ % BSD License, see LICENSE_BSD.txt files for details
32
+ %
33
+ % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
34
+ %
35
+
36
+ fn=fieldnames(data);
37
+ newdata=data;
38
+ len=length(data);
39
+ if(jsonopt('Recursive',0,varargin{:})==1)
40
+ for i=1:length(fn) % depth-first
41
+ for j=1:len
42
+ if(isstruct(getfield(data(j),fn{i})))
43
+ newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
44
+ end
45
+ end
46
+ end
47
+ end
48
+ if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
49
+ newdata=cell(len,1);
50
+ for j=1:len
51
+ ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
52
+ iscpx=0;
53
+ if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
54
+ if(data(j).x0x5F_ArrayIsComplex_)
55
+ iscpx=1;
56
+ end
57
+ end
58
+ if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
59
+ if(data(j).x0x5F_ArrayIsSparse_)
60
+ if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
61
+ dim=double(data(j).x0x5F_ArraySize_);
62
+ if(iscpx && size(ndata,2)==4-any(dim==1))
63
+ ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
64
+ end
65
+ if isempty(ndata)
66
+ % All-zeros sparse
67
+ ndata=sparse(dim(1),prod(dim(2:end)));
68
+ elseif dim(1)==1
69
+ % Sparse row vector
70
+ ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
71
+ elseif dim(2)==1
72
+ % Sparse column vector
73
+ ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
74
+ else
75
+ % Generic sparse array.
76
+ ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
77
+ end
78
+ else
79
+ if(iscpx && size(ndata,2)==4)
80
+ ndata(:,3)=complex(ndata(:,3),ndata(:,4));
81
+ end
82
+ ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
83
+ end
84
+ end
85
+ elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
86
+ if(iscpx && size(ndata,2)==2)
87
+ ndata=complex(ndata(:,1),ndata(:,2));
88
+ end
89
+ ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
90
+ end
91
+ newdata{j}=ndata;
92
+ end
93
+ if(len==1)
94
+ newdata=newdata{1};
95
+ end
96
+ end
OpenPVSG/models/unitrack/eval/poseval/matlab/external/jsonlab/varargin2struct.m ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function opt=varargin2struct(varargin)
2
+ %
3
+ % opt=varargin2struct('param1',value1,'param2',value2,...)
4
+ % or
5
+ % opt=varargin2struct(...,optstruct,...)
6
+ %
7
+ % convert a series of input parameters into a structure
8
+ %
9
+ % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
10
+ % date: 2012/12/22
11
+ %
12
+ % input:
13
+ % 'param', value: the input parameters should be pairs of a string and a value
14
+ % optstruct: if a parameter is a struct, the fields will be merged to the output struct
15
+ %
16
+ % output:
17
+ % opt: a struct where opt.param1=value1, opt.param2=value2 ...
18
+ %
19
+ % license:
20
+ % BSD License, see LICENSE_BSD.txt files for details
21
+ %
22
+ % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
23
+ %
24
+
25
+ len=length(varargin);
26
+ opt=struct;
27
+ if(len==0) return; end
28
+ i=1;
29
+ while(i<=len)
30
+ if(isstruct(varargin{i}))
31
+ opt=mergestruct(opt,varargin{i});
32
+ elseif(ischar(varargin{i}) && i<len)
33
+ opt=setfield(opt,lower(varargin{i}),varargin{i+1});
34
+ i=i+1;
35
+ else
36
+ error('input must be in the form of ...,''name'',value,... pairs or structs');
37
+ end
38
+ i=i+1;
39
+ end
40
+
OpenPVSG/models/unitrack/eval/poseval/matlab/mat2json.m ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function mat2json(dataDir)
2
+ % The function is part of PoseTrack dataset.
3
+ %
4
+ % It converts labels from matlab structure loaded from a *mat file to pytohn dictionary and saves in a *json file
5
+ %
6
+ % dataDir (string): directory containing labels in *mat files
7
+ % Usage:
8
+ % mat2json(dataDir)
9
+ %
10
+ % Example:
11
+ % mat2json('../../../posetrack_data/annotations/val/')
12
+ %
13
+
14
+ files = dir([dataDir '/*mat']);
15
+ fprintf('convert mat to json\n');
16
+ for i = 1:length(files)
17
+ fprintf('%d/%d %s\n',i,length(files),files(i).name);
18
+ filename = [dataDir '/' files(i).name];
19
+ [p,n,~] = fileparts(filename);
20
+ labels = load(filename);
21
+ savejson('',labels,'FileName',[p '/' n '.json'],'SingletArray',1,'NaN','nan','Inf','inf');
22
+ end
OpenPVSG/models/unitrack/eval/trackeval/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .eval import Evaluator
2
+ from . import datasets
3
+ from . import metrics
4
+ from . import plotting
5
+ from . import utils
OpenPVSG/models/unitrack/eval/trackeval/_timing.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ from time import perf_counter
3
+ import inspect
4
+
5
+ DO_TIMING = False
6
+ DISPLAY_LESS_PROGRESS = False
7
+ timer_dict = {}
8
+
9
+
10
+ def time(f):
11
+ @wraps(f)
12
+ def wrap(*args, **kw):
13
+ if DO_TIMING:
14
+ # Run function with timing
15
+ ts = perf_counter()
16
+ result = f(*args, **kw)
17
+ te = perf_counter()
18
+ tt = te-ts
19
+
20
+ # Get function name
21
+ arg_names = inspect.getfullargspec(f)[0]
22
+ if arg_names[0] == 'self' and DISPLAY_LESS_PROGRESS:
23
+ return result
24
+ elif arg_names[0] == 'self':
25
+ method_name = type(args[0]).__name__ + '.' + f.__name__
26
+ else:
27
+ method_name = f.__name__
28
+
29
+ # Record accumulative time in each function for analysis
30
+ if method_name in timer_dict.keys():
31
+ timer_dict[method_name] += tt
32
+ else:
33
+ timer_dict[method_name] = tt
34
+
35
+ # If code is finished, display timing summary
36
+ if method_name == "Evaluator.evaluate":
37
+ print("")
38
+ print("Timing analysis:")
39
+ for key, value in timer_dict.items():
40
+ print('%-70s %2.4f sec' % (key, value))
41
+ else:
42
+ # Get function argument values for printing special arguments of interest
43
+ arg_titles = ['tracker', 'seq', 'cls']
44
+ arg_vals = []
45
+ for i, a in enumerate(arg_names):
46
+ if a in arg_titles:
47
+ arg_vals.append(args[i])
48
+ arg_text = '(' + ', '.join(arg_vals) + ')'
49
+
50
+ # Display methods and functions with different indentation.
51
+ if arg_names[0] == 'self':
52
+ print('%-74s %2.4f sec' % (' '*4 + method_name + arg_text, tt))
53
+ else:
54
+ print('%-70s %2.4f sec' % (method_name + arg_text, tt))
55
+
56
+ return result
57
+ else:
58
+ # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing.
59
+ return f(*args, **kw)
60
+ return wrap