coco.py 4.12 KB
Newer Older
1
from .vision import VisionDataset
soumith's avatar
soumith committed
2
3
4
5
from PIL import Image
import os
import os.path

6

7
class CocoCaptions(VisionDataset):
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']

    """
45

46
47
    def __init__(self, root, annFile, transform=None, target_transform=None, transforms=None):
        super(CocoCaptions, self).__init__(root, transforms, transform, target_transform)
soumith's avatar
soumith committed
48
49
        from pycocotools.coco import COCO
        self.coco = COCO(annFile)
50
        self.ids = list(sorted(self.coco.imgs.keys()))
soumith's avatar
soumith committed
51
52

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

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

70
71
        if self.transforms is not None:
            img, target = self.transforms(img, target)
soumith's avatar
soumith committed
72
73
74
75
76
77

        return img, target

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

78

79
class CocoDetection(VisionDataset):
80
    """`MS Coco Detection <http://mscoco.org/dataset/#detections-challenge2016>`_ Dataset.
81
82
83
84
85
86
87
88
89

    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.
    """
90

91
92
    def __init__(self, root, annFile, transform=None, target_transform=None, transforms=None):
        super(CocoDetection, self).__init__(root, transforms, transform, target_transform)
soumith's avatar
soumith committed
93
94
        from pycocotools.coco import COCO
        self.coco = COCO(annFile)
95
        self.ids = list(sorted(self.coco.imgs.keys()))
soumith's avatar
soumith committed
96
97

    def __getitem__(self, index):
98
99
100
101
102
103
104
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target). target is the object returned by ``coco.loadAnns``.
        """
soumith's avatar
soumith committed
105
106
        coco = self.coco
        img_id = self.ids[index]
107
        ann_ids = coco.getAnnIds(imgIds=img_id)
soumith's avatar
soumith committed
108
109
110
111
112
        target = coco.loadAnns(ann_ids)

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

        img = Image.open(os.path.join(self.root, path)).convert('RGB')
113
114
        if self.transforms is not None:
            img, target = self.transforms(img, target)
soumith's avatar
soumith committed
115
116
117
118
119

        return img, target

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