coco.py 3.88 KB
Newer Older
soumith's avatar
soumith committed
1
import os.path
2
from typing import Any, Callable, Optional, Tuple, List
soumith's avatar
soumith committed
3

4
5
6
7
from PIL import Image

from .vision import VisionDataset

8

9
10
class CocoDetection(VisionDataset):
    """`MS Coco Detection <https://cocodataset.org/#detection-2016>`_ Dataset.
11

12
13
    It requires the `COCO API to be installed <https://github.com/pdollar/coco/tree/master/PythonAPI>`_.

14
15
16
17
    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
18
            and returns a transformed version. E.g, ``transforms.PILToTensor``
19
20
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
21
22
        transforms (callable, optional): A function/transform that takes input sample and its target as entry
            and returns a transformed version.
23
    """
24

Philip Meier's avatar
Philip Meier committed
25
    def __init__(
26
27
28
29
30
31
        self,
        root: str,
        annFile: str,
        transform: Optional[Callable] = None,
        target_transform: Optional[Callable] = None,
        transforms: Optional[Callable] = None,
32
    ) -> None:
33
        super().__init__(root, transforms, transform, target_transform)
soumith's avatar
soumith committed
34
        from pycocotools.coco import COCO
35

soumith's avatar
soumith committed
36
        self.coco = COCO(annFile)
37
        self.ids = list(sorted(self.coco.imgs.keys()))
soumith's avatar
soumith committed
38

39
40
41
    def _load_image(self, id: int) -> Image.Image:
        path = self.coco.loadImgs(id)[0]["file_name"]
        return Image.open(os.path.join(self.root, path)).convert("RGB")
soumith's avatar
soumith committed
42

43
    def _load_target(self, id: int) -> List[Any]:
44
        return self.coco.loadAnns(self.coco.getAnnIds(id))
soumith's avatar
soumith committed
45

46
47
48
49
    def __getitem__(self, index: int) -> Tuple[Any, Any]:
        id = self.ids[index]
        image = self._load_image(id)
        target = self._load_target(id)
soumith's avatar
soumith committed
50

51
        if self.transforms is not None:
52
            image, target = self.transforms(image, target)
soumith's avatar
soumith committed
53

54
        return image, target
soumith's avatar
soumith committed
55

Philip Meier's avatar
Philip Meier committed
56
    def __len__(self) -> int:
soumith's avatar
soumith committed
57
58
        return len(self.ids)

59

60
61
class CocoCaptions(CocoDetection):
    """`MS Coco Captions <https://cocodataset.org/#captions-2015>`_ Dataset.
62

63
64
    It requires the `COCO API to be installed <https://github.com/pdollar/coco/tree/master/PythonAPI>`_.

65
66
67
68
    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
69
            and returns a transformed version. E.g, ``transforms.PILToTensor``
70
71
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
72
73
        transforms (callable, optional): A function/transform that takes input sample and its target as entry
            and returns a transformed version.
74

75
    Example:
soumith's avatar
soumith committed
76

77
78
79
80
81
82
        .. code:: python

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

85
86
            print('Number of samples: ', len(cap))
            img, target = cap[3] # load 4th sample
soumith's avatar
soumith committed
87

88
89
            print("Image Size: ", img.size())
            print(target)
soumith's avatar
soumith committed
90

91
        Output: ::
soumith's avatar
soumith committed
92

93
94
95
96
97
98
99
            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
100

101
102
    """

103
    def _load_target(self, id: int) -> List[str]:
104
        return [ann["caption"] for ann in super()._load_target(id)]