-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoco2017_dataset.py
156 lines (111 loc) · 4.78 KB
/
coco2017_dataset.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
import random
import torch
import torch.utils.data as data
import os
import nltk
from PIL import Image
from pycocotools.coco import COCO
class CocoDataset(data.Dataset):
# COCO Custom Dataset compatible with torch.utils.data.DataLoader.
def __init__(self, root, json, vocab, train, transform=None):
"""
Set the path for images, captions and vocabulary wrapper.
Args:
root: image directory.
json: coco annotation file path.
vocab: vocabulary wrapper.
transform: image transformer.
"""
self.root = root
self.coco = COCO(json)
self.train = train
# Select all captions for each training image
# if not self.train:
# self.ids = list(sorted(self.coco.imgs.keys()))
# else:
# self.ids = list(self.coco.anns.keys())
# Select a random caption for each training image
self.ids = list(sorted(self.coco.imgs.keys()))
self.vocab = vocab
self.transform = transform
def __getitem__(self, index):
# Returns one data pair (image and list of captions).
coco = self.coco
vocab = self.vocab
if not self.train:
img_id = self.ids[index]
ann_ids = coco.getAnnIds(imgIds=img_id)
captions = [coco.anns[ann_id]['caption'] for ann_id in ann_ids]
else:
# Select all captions for each image
# ann_id = self.ids[index]
# caption = coco.anns[ann_id]['caption']
# img_id = coco.anns[ann_id]['image_id']
# Select a random caption for each image
img_id = self.ids[index]
ann_ids = coco.getAnnIds(imgIds=img_id)
ann_id = random.choice(ann_ids)
caption = coco.anns[ann_id]['caption']
captions = [caption]
path = coco.loadImgs(img_id)[0]['file_name']
image = Image.open(os.path.join(self.root, path)).convert('RGB')
if self.transform is not None:
image = self.transform(image)
# Convert captions to token indices
target = []
for caption in captions:
tokens = nltk.tokenize.word_tokenize(str(caption).lower())
caption = []
caption.append(vocab('<start>'))
caption.extend([vocab(token) for token in tokens])
caption.append(vocab('<end>'))
target.append(torch.tensor(caption, dtype=torch.long))
return image, target
def __len__(self):
return len(self.ids)
def collate_fn(data):
"""
Creates mini-batch tensors from the list of tuples (image, caption).
We should build custom collate_fn rather than using default collate_fn,
because merging caption (including padding) is not supported in default.
Args:
data: list of tuple (image, caption).
- image: torch tensor of shape (3, 224, 224).
- caption: list of torch tensors of shape (?); variable length.
Returns (Training Mode):
images: torch tensor of shape (batch_size, 3, 224, 224).
targets: torch tensor of shape (batch_size, padded_length).
lengths: list; valid length for each padded caption.
Returns (Test Mode):
images: torch tensor of shape (1, 3, 224, 224).
all_captions: tuple with list of torch tensors of shape (?).
"""
# Sort a data list by caption length (descending order).
data.sort(key=lambda x: len(x[1][0]), reverse=True)
# Separate images and captions
images, all_captions = zip(*data)
# Merge images (from tuple of 3D tensor to 4D tensor)
images = torch.stack(images, 0)
# Check if we're in training mode (single caption per image) or test mode (multiple captions per image)
if len(all_captions[0]) > 1:
# Test mode: multiple captions per image
return images, all_captions
else:
# Training mode: single caption per image
# Get lengths of each caption
lengths = [len(cap[0]) for cap in all_captions]
# Create tensor of captions
targets = torch.zeros(len(all_captions), 60).long()
for i, cap in enumerate(all_captions):
end = lengths[i]
targets[i, :end] = cap[0][:end]
return images, targets, lengths
def get_loader(root, json, transform, batch_size, shuffle, vocab, first=True, train=True):
if not first:
old_vocab_length = len(vocab)
vocab.add_captions(annotations=json)
print(f'\nAdded {len(vocab) - old_vocab_length} tokens to vocabulary!\n')
# COCO caption dataset
coco = CocoDataset(root=root, json=json, vocab=vocab, train=train, transform=transform)
data_loader = torch.utils.data.DataLoader(dataset=coco, batch_size=batch_size, shuffle=shuffle, collate_fn=collate_fn)
return data_loader