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

soumith's avatar
soumith committed
9
10
11
12
    def __init__(self, root, annFile, transform=None, target_transform=None):
        from pycocotools.coco import COCO
        self.root = root
        self.coco = COCO(annFile)
Sean Robertson's avatar
Sean Robertson committed
13
        self.ids = list(self.coco.imgs.keys())
soumith's avatar
soumith committed
14
15
16
17
18
19
        self.transform = transform
        self.target_transform = target_transform

    def __getitem__(self, index):
        coco = self.coco
        img_id = self.ids[index]
20
        ann_ids = coco.getAnnIds(imgIds=img_id)
soumith's avatar
soumith committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
        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)

38

soumith's avatar
soumith committed
39
class CocoDetection(data.Dataset):
40

soumith's avatar
soumith committed
41
42
43
44
    def __init__(self, root, annFile, transform=None, target_transform=None):
        from pycocotools.coco import COCO
        self.root = root
        self.coco = COCO(annFile)
45
        self.ids = list(self.coco.imgs.keys())
soumith's avatar
soumith committed
46
47
48
49
50
51
        self.transform = transform
        self.target_transform = target_transform

    def __getitem__(self, index):
        coco = self.coco
        img_id = self.ids[index]
52
        ann_ids = coco.getAnnIds(imgIds=img_id)
soumith's avatar
soumith committed
53
54
55
56
57
        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
58
59
60
        if self.transform is not None:
            img = self.transform(img)

soumith's avatar
soumith committed
61
62
63
64
65
66
67
        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

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