Datasets:
Tasks:
Object Detection
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
1K - 10K
License:
Michael Gruner
commited on
Commit
·
a705542
1
Parent(s):
d5fea8c
Upload helper script
Browse files- coco2citw.py +62 -0
coco2citw.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
from pycocotools.coco import COCO
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# MODIFY ME!
|
| 10 |
+
# ---------------------------------
|
| 11 |
+
coco_dataset='/opt/datasets/coco/'
|
| 12 |
+
year='2017'
|
| 13 |
+
splits=['train', 'val']
|
| 14 |
+
dst_dir='citw'
|
| 15 |
+
metadata='metadata.jsonl'
|
| 16 |
+
# ---------------------------------
|
| 17 |
+
|
| 18 |
+
def process_split(coco_dataset, year, split, dst_dir, metadata):
|
| 19 |
+
annotations=f'{coco_dataset}/annotations/instances_{split}{year}.json'
|
| 20 |
+
coco=COCO(annotations)
|
| 21 |
+
cats =coco.loadCats(coco.getCatIds())
|
| 22 |
+
|
| 23 |
+
target_name='cell phone'
|
| 24 |
+
target_id=coco.getCatIds(catNms=[target_name])[0];
|
| 25 |
+
|
| 26 |
+
print(f'Found "{target_name}" id: {target_id}')
|
| 27 |
+
|
| 28 |
+
image_ids=coco.getImgIds(catIds=[target_id]);
|
| 29 |
+
images=coco.loadImgs(image_ids)
|
| 30 |
+
|
| 31 |
+
print(f'Found {len(images)} images containing a "{target_name}"')
|
| 32 |
+
|
| 33 |
+
image_dir=f'{coco_dataset}/{split}{year}/'
|
| 34 |
+
image_dst_dir=f'{dst_dir}/{split}/'
|
| 35 |
+
|
| 36 |
+
os.makedirs(image_dst_dir, exist_ok=True)
|
| 37 |
+
|
| 38 |
+
dst_metadata=f'{image_dst_dir}/{metadata}'
|
| 39 |
+
with open(dst_metadata, 'w') as f:
|
| 40 |
+
for image in images:
|
| 41 |
+
ann_ids = coco.getAnnIds(imgIds=image['id'], catIds=target_id, iscrowd=None)
|
| 42 |
+
anns = coco.loadAnns(ann_ids)
|
| 43 |
+
|
| 44 |
+
src_image=f'{image_dir}/{image["file_name"]}'
|
| 45 |
+
shutil.copy(src_image, image_dst_dir)
|
| 46 |
+
|
| 47 |
+
entry={}
|
| 48 |
+
entry['file_name']=image["file_name"]
|
| 49 |
+
boxes=[ann['bbox'] for ann in anns]
|
| 50 |
+
cats=[0]*len(boxes)
|
| 51 |
+
entry['objects']={
|
| 52 |
+
'bbox': boxes,
|
| 53 |
+
'categories': cats
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
f.write(f'{json.dumps(entry)}\n')
|
| 57 |
+
|
| 58 |
+
print(f'Done processing the "{split}" split!')
|
| 59 |
+
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
for split in splits:
|
| 62 |
+
process_split(coco_dataset, year, split, dst_dir, metadata)
|