-
Notifications
You must be signed in to change notification settings - Fork 96
/
ytvos.py
191 lines (172 loc) · 6.68 KB
/
ytvos.py
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
"""
YoutubeVIS data loader
"""
from pathlib import Path
import torch
import torch.utils.data
import torchvision
from pycocotools.ytvos import YTVOS
from pycocotools.ytvoseval import YTVOSeval
import datasets.transforms as T
from pycocotools import mask as coco_mask
import os
from PIL import Image
from random import randint
import cv2
import random
class YTVOSDataset:
def __init__(self, img_folder, ann_file, transforms, return_masks, num_frames):
self.img_folder = img_folder
self.ann_file = ann_file
self._transforms = transforms
self.return_masks = return_masks
self.num_frames = num_frames
self.prepare = ConvertCocoPolysToMask(return_masks)
self.ytvos = YTVOS(ann_file)
self.cat_ids = self.ytvos.getCatIds()
self.vid_ids = self.ytvos.getVidIds()
self.vid_infos = []
for i in self.vid_ids:
info = self.ytvos.loadVids([i])[0]
info['filenames'] = info['file_names']
self.vid_infos.append(info)
self.img_ids = []
for idx, vid_info in enumerate(self.vid_infos):
for frame_id in range(len(vid_info['filenames'])):
self.img_ids.append((idx, frame_id))
def __len__(self):
return len(self.img_ids)
def __getitem__(self, idx):
vid, frame_id = self.img_ids[idx]
vid_id = self.vid_infos[vid]['id']
img = []
vid_len = len(self.vid_infos[vid]['file_names'])
inds = list(range(self.num_frames))
inds = [i%vid_len for i in inds][::-1]
# if random
# random.shuffle(inds)
for j in range(self.num_frames):
img_path = os.path.join(str(self.img_folder), self.vid_infos[vid]['file_names'][frame_id-inds[j]])
img.append(Image.open(img_path).convert('RGB'))
ann_ids = self.ytvos.getAnnIds(vidIds=[vid_id])
target = self.ytvos.loadAnns(ann_ids)
target = {'image_id': idx, 'video_id': vid, 'frame_id': frame_id, 'annotations': target}
target = self.prepare(img[0], target, inds, self.num_frames)
if self._transforms is not None:
img, target = self._transforms(img, target)
return torch.cat(img,dim=0), target
def convert_coco_poly_to_mask(segmentations, height, width):
masks = []
for polygons in segmentations:
if not polygons:
mask = torch.zeros((height,width), dtype=torch.uint8)
else:
rles = coco_mask.frPyObjects(polygons, height, width)
mask = coco_mask.decode(rles)
if len(mask.shape) < 3:
mask = mask[..., None]
mask = torch.as_tensor(mask, dtype=torch.uint8)
mask = mask.any(dim=2)
masks.append(mask)
if masks:
masks = torch.stack(masks, dim=0)
else:
masks = torch.zeros((0, height, width), dtype=torch.uint8)
return masks
class ConvertCocoPolysToMask(object):
def __init__(self, return_masks=False):
self.return_masks = return_masks
def __call__(self, image, target, inds, num_frames):
w, h = image.size
image_id = target["image_id"]
frame_id = target['frame_id']
image_id = torch.tensor([image_id])
anno = target["annotations"]
anno = [obj for obj in anno if 'iscrowd' not in obj or obj['iscrowd'] == 0]
boxes = []
classes = []
segmentations = []
area = []
iscrowd = []
valid = []
# add valid flag for bboxes
for i, ann in enumerate(anno):
for j in range(num_frames):
bbox = ann['bboxes'][frame_id-inds[j]]
areas = ann['areas'][frame_id-inds[j]]
segm = ann['segmentations'][frame_id-inds[j]]
clas = ann["category_id"]
# for empty boxes
if bbox is None:
bbox = [0,0,0,0]
areas = 0
valid.append(0)
clas = 0
else:
valid.append(1)
crowd = ann["iscrowd"] if "iscrowd" in ann else 0
boxes.append(bbox)
area.append(areas)
segmentations.append(segm)
classes.append(clas)
iscrowd.append(crowd)
# guard against no boxes via resizing
boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4)
boxes[:, 2:] += boxes[:, :2]
boxes[:, 0::2].clamp_(min=0, max=w)
boxes[:, 1::2].clamp_(min=0, max=h)
classes = torch.tensor(classes, dtype=torch.int64)
if self.return_masks:
masks = convert_coco_poly_to_mask(segmentations, h, w)
target = {}
target["boxes"] = boxes
target["labels"] = classes
if self.return_masks:
target["masks"] = masks
target["image_id"] = image_id
# for conversion to coco api
area = torch.tensor(area)
iscrowd = torch.tensor(iscrowd)
target["valid"] = torch.tensor(valid)
target["area"] = area
target["iscrowd"] = iscrowd
target["orig_size"] = torch.as_tensor([int(h), int(w)])
target["size"] = torch.as_tensor([int(h), int(w)])
return target
def make_coco_transforms(image_set):
normalize = T.Compose([
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768]
if image_set == 'train':
return T.Compose([
T.RandomHorizontalFlip(),
T.RandomResize(scales, max_size=800),
T.PhotometricDistort(),
T.Compose([
T.RandomResize([400, 500, 600]),
T.RandomSizeCrop(384, 600),
# To suit the GPU memory the scale might be different
T.RandomResize([300], max_size=540),#for r50
#T.RandomResize([280], max_size=504),#for r101
]),
normalize,
])
if image_set == 'val':
return T.Compose([
T.RandomResize([360], max_size=640),
normalize,
])
raise ValueError(f'unknown {image_set}')
def build(image_set, args):
root = Path(args.ytvos_path)
assert root.exists(), f'provided YTVOS path {root} does not exist'
mode = 'instances'
PATHS = {
"train": (root / "train/JPEGImages", root / "annotations" / f'{mode}_train_sub.json'),
"val": (root / "valid/JPEGImages", root / "annotations" / f'{mode}_val_sub.json'),
}
img_folder, ann_file = PATHS[image_set]
dataset = YTVOSDataset(img_folder, ann_file, transforms=make_coco_transforms(image_set), return_masks=args.masks, num_frames = args.num_frames)
return dataset