@@ -151,18 +151,26 @@ def convert_to_coco_api(ds):
151
151
for img_idx in range (len (ds )):
152
152
# find better way to get target
153
153
# targets = ds.get_annotations(img_idx)
154
- _ , targets = ds [img_idx ]
154
+ img , targets = ds [img_idx ]
155
155
image_id = targets ["image_id" ].item ()
156
156
img_dict = {}
157
157
img_dict ['id' ] = image_id
158
+ img_dict ['height' ] = img .shape [- 2 ]
159
+ img_dict ['width' ] = img .shape [- 1 ]
158
160
dataset ['images' ].append (img_dict )
159
161
bboxes = targets ["boxes" ]
160
162
bboxes [:, 2 :] -= bboxes [:, :2 ]
161
163
bboxes = bboxes .tolist ()
162
164
labels = targets ['labels' ].tolist ()
163
165
areas = targets ['area' ].tolist ()
164
166
iscrowd = targets ['iscrowd' ].tolist ()
165
- # TODO need to add masks as well
167
+ if 'masks' in targets :
168
+ masks = targets ['masks' ]
169
+ # make masks Fortran contiguous for coco_mask
170
+ masks = masks .permute (0 , 2 , 1 ).contiguous ().permute (0 , 2 , 1 )
171
+ if 'keypoints' in targets :
172
+ keypoints = targets ['keypoints' ]
173
+ keypoints = keypoints .reshape (keypoints .shape [0 ], - 1 ).tolist ()
166
174
num_objs = len (bboxes )
167
175
for i in range (num_objs ):
168
176
ann = {}
@@ -173,6 +181,11 @@ def convert_to_coco_api(ds):
173
181
ann ['area' ] = areas [i ]
174
182
ann ['iscrowd' ] = iscrowd [i ]
175
183
ann ['id' ] = ann_id
184
+ if 'masks' in targets :
185
+ ann ["segmentation" ] = coco_mask .encode (masks [i ].numpy ())
186
+ if 'keypoints' in targets :
187
+ ann ['keypoints' ] = keypoints [i ]
188
+ ann ['num_keypoints' ] = sum (k != 0 for k in keypoints [i ][2 ::3 ])
176
189
dataset ['annotations' ].append (ann )
177
190
ann_id += 1
178
191
dataset ['categories' ] = [{'id' : i } for i in sorted (categories )]
0 commit comments