coco.py 1.89 KB
Newer Older
soumith's avatar
soumith committed
1
2
3
4
5
import torch.utils.data as data
from PIL import Image
import os
import os.path

soumith's avatar
soumith committed
6
class CocoCaptions(data.Dataset):
soumith's avatar
soumith committed
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
    def __init__(self, root, annFile, transform=None, target_transform=None):
        from pycocotools.coco import COCO
        self.root = root
        self.coco = COCO(annFile)
        self.ids = self.coco.imgs.keys()
        self.transform = transform
        self.target_transform = target_transform

    def __getitem__(self, index):
        coco = self.coco
        img_id = self.ids[index]
        ann_ids = coco.getAnnIds(imgIds = img_id)
        anns = coco.loadAnns(ann_ids)
        target = [ann['caption'] for ann in anns]

        path = coco.loadImgs(img_id)[0]['file_name']

        img = Image.open(os.path.join(self.root, path)).convert('RGB')
        if self.transform is not None:
            img = self.transform(img)

        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

    def __len__(self):
        return len(self.ids)

soumith's avatar
soumith committed
36
class CocoDetection(data.Dataset):
soumith's avatar
soumith committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    def __init__(self, root, annFile, transform=None, target_transform=None):
        from pycocotools.coco import COCO
        self.root = root
        self.coco = COCO(annFile)
        self.ids = self.coco.imgs.keys()
        self.transform = transform
        self.target_transform = target_transform

    def __getitem__(self, index):
        coco = self.coco
        img_id = self.ids[index]
        ann_ids = coco.getAnnIds(imgIds = img_id)
        target = coco.loadAnns(ann_ids)

        path = coco.loadImgs(img_id)[0]['file_name']

        img = Image.open(os.path.join(self.root, path)).convert('RGB')
Francisco Massa's avatar
Francisco Massa committed
54
55
56
        if self.transform is not None:
            img = self.transform(img)

soumith's avatar
soumith committed
57
58
59
60
61
62
63
        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

    def __len__(self):
        return len(self.ids)