-
Notifications
You must be signed in to change notification settings - Fork 57
/
coco_gt.py
151 lines (106 loc) · 4.01 KB
/
coco_gt.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
# coding=utf-8
# from detectron2_proposal_maxnms import collate_fn, extract, NUM_OBJECTS, DIM
from detectron2_given_box_maxnms import extract, DIM
from torch.utils.data import Dataset, DataLoader
import cv2
from tqdm import tqdm
from pathlib import Path
import argparse
from pycocotools.coco import COCO
import json
import numpy as np
class COCODataset(Dataset):
def __init__(self, image_dir, box_ann_path, split='val2014'):
self.image_dir = image_dir
box_ann_path = str(box_ann_path)
self.coco = COCO(box_ann_path)
self.split = split
with open(box_ann_path) as f:
box_ann = json.load(f)
id2name = {}
for cat2name in box_ann['categories']:
id2name[cat2name['id']] = cat2name['name']
self.id2name = id2name
img_ids = []
boxes = []
captions = []
for img_id, anns in self.coco.imgToAnns.items():
img_ids.append(img_id)
boxes.append([ann['bbox'] for ann in anns])
captions.append([self.id2name[ann['category_id']] for ann in anns])
assert len(img_ids) == len(boxes)
assert len(img_ids) == len(captions)
self.img_ids = img_ids
self.boxes = boxes
self.captions = captions
def __len__(self):
return len(self.coco.imgToAnns)
def __getitem__(self, idx):
image_id = self.img_ids[idx]
image_name = f'COCO_{self.split}_{str(image_id).zfill(12)}'
image_path = self.image_dir.joinpath(f'{image_name}.jpg')
image_id = image_path.stem
img = cv2.imread(str(image_path))
H, W, _ = img.shape
boxes = []
for box in self.boxes[idx]:
x, y, width, height = box
x1 = x
y1 = y
x2 = x + width
y2 = y + height
boxes.append([x1, y1, x2, y2])
assert len(boxes) > 0
boxes = np.array(boxes)
captions = self.captions[idx]
return {
'img_id': image_name,
'img': img,
'boxes': boxes,
'captions': captions
}
def collate_fn(batch):
img_ids = []
imgs = []
boxes = []
captions = []
for i, entry in enumerate(batch):
img_ids.append(entry['img_id'])
imgs.append(entry['img'])
boxes.append(entry['boxes'])
captions.append(entry['captions'])
batch_out = {}
batch_out['img_ids'] = img_ids
batch_out['imgs'] = imgs
batch_out['boxes'] = boxes
batch_out['captions'] = captions
return batch_out
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--batchsize', default=1, type=int, help='batch_size')
parser.add_argument('--cocoroot', type=str, default='/ssd-playpen/home/jmincho/workspace/datasets/COCO/')
parser.add_argument('--split', type=str, default='valid', choices=['train', 'valid', 'test'])
args = parser.parse_args()
SPLIT2DIR = {
'train': 'train2014',
'valid': 'val2014',
'test': 'test2015',
}
coco_dir = Path(args.cocoroot).resolve()
coco_img_dir = coco_dir.joinpath('images')
coco_img_split_dir = coco_img_dir.joinpath(SPLIT2DIR[args.split])
box_ann_path = coco_dir.joinpath('annotations').joinpath(f'instances_{SPLIT2DIR[args.split]}.json')
dataset_name = 'COCO'
out_dir = coco_dir.joinpath('features')
if not out_dir.exists():
out_dir.mkdir()
print('Load images from', coco_img_split_dir)
print('# Images:', len(list(coco_img_split_dir.iterdir())))
dataset = COCODataset(coco_img_split_dir, box_ann_path, SPLIT2DIR[args.split])
print('# Annotated Images:', len(dataset))
dataloader = DataLoader(dataset, batch_size=args.batchsize,
shuffle=False, collate_fn=collate_fn, num_workers=4)
output_fname = out_dir.joinpath(f'{SPLIT2DIR[args.split]}_GT.h5')
print('features will be saved at', output_fname)
desc = f'{dataset_name}_{SPLIT2DIR[args.split]}_{DIM}'
extract(output_fname, dataloader, desc)