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

import numpy as np
import pycocotools.mask as rletools
import torch
from PIL import Image


class MOTObjDetect(torch.utils.data.Dataset):
    """ Data class for the Multiple Object Tracking Dataset
    """

    def __init__(self, root, transforms=None, vis_threshold=0.25,
                 split_seqs=None, frame_range_start=0.0, frame_range_end=1.0):
        self.root = root
        self.transforms = transforms
        self._vis_threshold = vis_threshold
        self._classes = ('background', 'pedestrian')
        self._img_paths = []
        self._split_seqs = split_seqs

        self.mots_gts = {}
        for f in sorted(os.listdir(root)):
            path = os.path.join(root, f)

            if not os.path.isdir(path):
                continue

            if split_seqs is not None and f not in split_seqs:
                continue

            config_file = os.path.join(path, 'seqinfo.ini')

            assert os.path.exists(config_file), \
                'Path does not exist: {}'.format(config_file)

            config = configparser.ConfigParser()
            config.read(config_file)
            seq_len = int(config['Sequence']['seqLength'])
            im_ext = config['Sequence']['imExt']
            im_dir = config['Sequence']['imDir']

            img_dir = os.path.join(path, im_dir)

            start_frame = int(frame_range_start * seq_len)
            end_frame = int(frame_range_end * seq_len)

            # for i in range(seq_len):
            for i in range(start_frame, end_frame):
                img_path = os.path.join(img_dir, f"{i + 1:06d}{im_ext}")
                assert os.path.exists(
                    img_path), f'Path does not exist: {img_path}'
                self._img_paths.append(img_path)

            # print(len(self._img_paths))

            if self.has_masks:
                gt_file = os.path.join(
                    os.path.dirname(img_dir), 'gt', 'gt.txt')
                self.mots_gts[gt_file] = load_mots_gt(gt_file)

    def __str__(self):
        if self._split_seqs is None:
            return self.root
        return f"{self.root}/{self._split_seqs}"

    @property
    def num_classes(self):
        return len(self._classes)

    def _get_annotation(self, idx):
        """
        """

        if 'test' in self.root:
            num_objs = 0
            boxes = torch.zeros((num_objs, 4), dtype=torch.float32)

            return {'boxes': boxes,
                    'labels': torch.ones((num_objs,), dtype=torch.int64),
                    'image_id': torch.tensor([idx]),
                    'area': (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]),
                    'iscrowd': torch.zeros((num_objs,), dtype=torch.int64),
                    'visibilities': torch.zeros((num_objs), dtype=torch.float32)}

        img_path = self._img_paths[idx]
        file_index = int(os.path.basename(img_path).split('.')[0])

        gt_file = os.path.join(os.path.dirname(
            os.path.dirname(img_path)), 'gt', 'gt.txt')

        assert os.path.exists(gt_file), \
            'GT file does not exist: {}'.format(gt_file)

        bounding_boxes = []

        if self.has_masks:
            mask_objects_per_frame = self.mots_gts[gt_file][file_index]
            masks = []
            for mask_object in mask_objects_per_frame:
                # class_id = 1 is car
                # class_id = 2 is pedestrian
                # class_id = 10 IGNORE
                if mask_object.class_id in [1, 10] or not rletools.area(mask_object.mask):
                    continue

                bbox = rletools.toBbox(mask_object.mask)
                x1, y1, w, h = [int(c) for c in bbox]

                bb = {}
                bb['bb_left'] = x1
                bb['bb_top'] = y1
                bb['bb_width'] = w
                bb['bb_height'] = h

                # print(bb, rletools.area(mask_object.mask))

                bb['visibility'] = 1.0
                bb['track_id'] = mask_object.track_id

                masks.append(rletools.decode(mask_object.mask))
                bounding_boxes.append(bb)
        else:
            with open(gt_file, "r") as inf:
                reader = csv.reader(inf, delimiter=',')
                for row in reader:
                    visibility = float(row[8])

                    if int(row[0]) == file_index and int(row[6]) == 1 and int(row[7]) == 1 and visibility and visibility >= self._vis_threshold:
                        bb = {}
                        bb['bb_left'] = int(row[2])
                        bb['bb_top'] = int(row[3])
                        bb['bb_width'] = int(row[4])
                        bb['bb_height'] = int(row[5])
                        bb['visibility'] = float(row[8])
                        bb['track_id'] = int(row[1])

                        bounding_boxes.append(bb)

        num_objs = len(bounding_boxes)

        boxes = torch.zeros((num_objs, 4), dtype=torch.float32)
        visibilities = torch.zeros((num_objs), dtype=torch.float32)
        track_ids = torch.zeros((num_objs), dtype=torch.long)

        for i, bb in enumerate(bounding_boxes):
            # Make pixel indexes 0-based, should already be 0-based (or not)
            x1 = bb['bb_left']  # - 1
            y1 = bb['bb_top']  # - 1
            # This -1 accounts for the width (width of 1 x1=x2)
            x2 = x1 + bb['bb_width']  # - 1
            y2 = y1 + bb['bb_height']  # - 1

            boxes[i, 0] = x1
            boxes[i, 1] = y1
            boxes[i, 2] = x2
            boxes[i, 3] = y2
            visibilities[i] = bb['visibility']
            track_ids[i] = bb['track_id']

        annos = {'boxes': boxes,
                 'labels': torch.ones((num_objs,), dtype=torch.int64),
                 'image_id': torch.tensor([idx]),
                 'area': (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]),
                 'iscrowd': torch.zeros((num_objs,), dtype=torch.int64),
                 'visibilities': visibilities,
                 'track_ids': track_ids, }

        if self.has_masks:
            # annos['masks'] = torch.tensor(masks, dtype=torch.uint8)
            annos['masks'] = torch.from_numpy(np.stack(masks))
        return annos

    @property
    def has_masks(self):
        return '/MOTS20/' in self.root

    def __getitem__(self, idx):
        # load images ad masks
        img_path = self._img_paths[idx]
        # mask_path = os.path.join(self.root, "PedMasks", self.masks[idx])
        img = Image.open(img_path).convert("RGB")

        target = self._get_annotation(idx)

        if self.transforms is not None:
            img, target = self.transforms(img, target)

        return img, target

    def __len__(self):
        return len(self._img_paths)

    def write_results_files(self, results, output_dir):
        """Write the detections in the format for MOT17Det sumbission

        all_boxes[image] = N x 5 array of detections in (x1, y1, x2, y2, score)

        Each file contains these lines:
        <frame>, <id>, <bb_left>, <bb_top>, <bb_width>, <bb_height>, <conf>, <x>, <y>, <z>

        Files to sumbit:
        ./MOT17-01.txt
        ./MOT17-02.txt
        ./MOT17-03.txt
        ./MOT17-04.txt
        ./MOT17-05.txt
        ./MOT17-06.txt
        ./MOT17-07.txt
        ./MOT17-08.txt
        ./MOT17-09.txt
        ./MOT17-10.txt
        ./MOT17-11.txt
        ./MOT17-12.txt
        ./MOT17-13.txt
        ./MOT17-14.txt
        """

        #format_str = "{}, -1, {}, {}, {}, {}, {}, -1, -1, -1"

        files = {}
        for image_id, res in results.items():
            path = self._img_paths[image_id]
            img1, name = osp.split(path)
            # get image number out of name
            frame = int(name.split('.')[0])
            # smth like /train/MOT17-09-FRCNN or /train/MOT17-09
            tmp = osp.dirname(img1)
            # get the folder name of the sequence and split it
            tmp = osp.basename(tmp).split('-')
            # Now get the output name of the file
            out = tmp[0]+'-'+tmp[1]+'.txt'
            outfile = osp.join(output_dir, out)

            # check if out in keys and create empty list if not
            if outfile not in files.keys():
                files[outfile] = []

            if 'masks' in res:
                delimiter = ' '
                # print(torch.unique(res['masks'][0]))
                # > 0.5 #res['masks'].bool()
                masks = res['masks'].squeeze(dim=1)

                index_map = torch.arange(masks.size(0))[:, None, None]
                index_map = index_map.expand_as(masks)

                masks = torch.logical_and(
                    # remove background
                    masks > 0.5,
                    # remove overlapp by largest probablity
                    index_map == masks.argmax(dim=0)
                )
                for res_i in range(len(masks)):
                    track_id = -1
                    if 'track_ids' in res:
                        track_id = res['track_ids'][res_i].item()
                    mask = masks[res_i]
                    mask = np.asfortranarray(mask)

                    rle_mask = rletools.encode(mask)

                    files[outfile].append(
                        [frame,
                         track_id,
                         2,  # class pedestrian
                         mask.shape[0],
                         mask.shape[1],
                         rle_mask['counts'].decode(encoding='UTF-8')])
            else:
                delimiter = ','
                for res_i in range(len(res['boxes'])):
                    track_id = -1
                    if 'track_ids' in res:
                        track_id = res['track_ids'][res_i].item()
                    box = res['boxes'][res_i]
                    score = res['scores'][res_i]

                    x1 = box[0].item()
                    y1 = box[1].item()
                    x2 = box[2].item()
                    y2 = box[3].item()

                    out = [frame, track_id, x1, y1, x2 - x1,
                           y2 - y1, score.item(), -1, -1, -1]

                    if 'keypoints' in res:
                        out.extend(res['keypoints'][res_i]
                                   [:, :2].flatten().tolist())
                        out.extend(res['keypoints_scores']
                                   [res_i].flatten().tolist())

                    files[outfile].append(out)

        for k, v in files.items():
            with open(k, "w") as of:
                writer = csv.writer(of, delimiter=delimiter)
                for d in v:
                    writer.writerow(d)


class SegmentedObject:
    """
    Helper class for segmentation objects.
    """

    def __init__(self, mask: dict, class_id: int, track_id: int, full_bbox=None) -> None:
        self.mask = mask
        self.class_id = class_id
        self.track_id = track_id
        self.full_bbox = full_bbox


def load_mots_gt(path: str) -> dict:
    """Load MOTS ground truth from path."""
    objects_per_frame = {}
    track_ids_per_frame = {}  # Check that no frame contains two objects with same id
    combined_mask_per_frame = {}  # Check that no frame contains overlapping masks

    with open(path, "r") as gt_file:
        for line in gt_file:
            line = line.strip()
            fields = line.split(" ")

            frame = int(fields[0])
            if frame not in objects_per_frame:
                objects_per_frame[frame] = []
            # if frame not in track_ids_per_frame:
            #     track_ids_per_frame[frame] = set()
            # if int(fields[1]) in track_ids_per_frame[frame]:
            #     assert False, f"Multiple objects with track id {fields[1]} in frame {fields[0]}"
            # else:
            #     track_ids_per_frame[frame].add(int(fields[1]))

            class_id = int(fields[2])
            if not (class_id == 1 or class_id == 2 or class_id == 10):
                assert False, "Unknown object class " + fields[2]

            mask = {
                'size': [int(fields[3]), int(fields[4])],
                'counts': fields[5].encode(encoding='UTF-8')}
            if frame not in combined_mask_per_frame:
                combined_mask_per_frame[frame] = mask
            elif rletools.area(rletools.merge([
                    combined_mask_per_frame[frame], mask],
                    intersect=True)):
                assert False, "Objects with overlapping masks in frame " + \
                    fields[0]
            else:
                combined_mask_per_frame[frame] = rletools.merge(
                    [combined_mask_per_frame[frame], mask],
                    intersect=False)

            full_bbox = None
            if len(fields) == 10:
                full_bbox = [int(fields[6]), int(fields[7]),
                             int(fields[8]), int(fields[9])]

            objects_per_frame[frame].append(SegmentedObject(
                mask,
                class_id,
                int(fields[1]),
                full_bbox
            ))

    return objects_per_frame