coco.py 4.27 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

6

soumith's avatar
soumith committed
7
class CocoCaptions(data.Dataset):
8
    """`MS Coco Captions <http://mscoco.org/dataset/#captions-challenge2015>`_ Dataset.
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
    Args:
        root (string): Root directory where images are downloaded to.
        annFile (string): Path to json annotation file.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.ToTensor``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.

    Example:

        .. code:: python

            import torchvision.datasets as dset
            import torchvision.transforms as transforms
            cap = dset.CocoCaptions(root = 'dir where images are',
                                    annFile = 'json annotation file',
                                    transform=transforms.ToTensor())

            print('Number of samples: ', len(cap))
            img, target = cap[3] # load 4th sample

            print("Image Size: ", img.size())
            print(target)

        Output: ::

            Number of samples: 82783
            Image Size: (3L, 427L, 640L)
            [u'A plane emitting smoke stream flying over a mountain.',
            u'A plane darts across a bright blue sky behind a mountain covered in snow',
            u'A plane leaves a contrail above the snowy mountain top.',
            u'A mountain that has a plane flying overheard in the distance.',
            u'A mountain view with a plume of smoke in the background']

    """
soumith's avatar
soumith committed
45
46
    def __init__(self, root, annFile, transform=None, target_transform=None):
        from pycocotools.coco import COCO
47
        self.root = os.path.expanduser(root)
soumith's avatar
soumith committed
48
        self.coco = COCO(annFile)
Sean Robertson's avatar
Sean Robertson committed
49
        self.ids = list(self.coco.imgs.keys())
soumith's avatar
soumith committed
50
51
52
53
        self.transform = transform
        self.target_transform = target_transform

    def __getitem__(self, index):
54
55
56
57
58
59
60
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target). target is a list of captions for the image.
        """
soumith's avatar
soumith committed
61
62
        coco = self.coco
        img_id = self.ids[index]
63
        ann_ids = coco.getAnnIds(imgIds=img_id)
soumith's avatar
soumith committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        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)

81

soumith's avatar
soumith committed
82
class CocoDetection(data.Dataset):
83
84
85
86
87
88
89
90
91
92
    """`MS Coco Captions <http://mscoco.org/dataset/#detections-challenge2016>`_ Dataset.

    Args:
        root (string): Root directory where images are downloaded to.
        annFile (string): Path to json annotation file.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.ToTensor``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    """
93

soumith's avatar
soumith committed
94
95
96
97
    def __init__(self, root, annFile, transform=None, target_transform=None):
        from pycocotools.coco import COCO
        self.root = root
        self.coco = COCO(annFile)
98
        self.ids = list(self.coco.imgs.keys())
soumith's avatar
soumith committed
99
100
101
102
        self.transform = transform
        self.target_transform = target_transform

    def __getitem__(self, index):
103
104
105
106
107
108
109
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target). target is the object returned by ``coco.loadAnns``.
        """
soumith's avatar
soumith committed
110
111
        coco = self.coco
        img_id = self.ids[index]
112
        ann_ids = coco.getAnnIds(imgIds=img_id)
soumith's avatar
soumith committed
113
114
115
116
117
        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
118
119
120
        if self.transform is not None:
            img = self.transform(img)

soumith's avatar
soumith committed
121
122
123
124
125
126
127
        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

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