lsun.py 5.25 KB
Newer Older
1
from .vision import VisionDataset
soumith's avatar
soumith committed
2
3
4
from PIL import Image
import os
import os.path
soumith's avatar
soumith committed
5
import six
soumith's avatar
soumith committed
6
7
import string
import sys
8
from collections import Iterable
9

soumith's avatar
soumith committed
10
11
12
13
14
if sys.version_info[0] == 2:
    import cPickle as pickle
else:
    import pickle

15
16
from .utils import verify_str_arg, iterable_to_str

17

18
class LSUNClass(VisionDataset):
Jason Park's avatar
Jason Park committed
19
    def __init__(self, root, transform=None, target_transform=None):
soumith's avatar
soumith committed
20
        import lmdb
21
22
        super(LSUNClass, self).__init__(root, transform=transform,
                                        target_transform=target_transform)
Jason Park's avatar
Jason Park committed
23
24

        self.env = lmdb.open(root, max_readers=1, readonly=True, lock=False,
soumith's avatar
soumith committed
25
                             readahead=False, meminit=False)
soumith's avatar
soumith committed
26
27
        with self.env.begin(write=False) as txn:
            self.length = txn.stat()['entries']
28
        cache_file = '_cache_' + ''.join(c for c in root if c in string.ascii_letters)
soumith's avatar
soumith committed
29
        if os.path.isfile(cache_file):
30
            self.keys = pickle.load(open(cache_file, "rb"))
soumith's avatar
soumith committed
31
32
        else:
            with self.env.begin(write=False) as txn:
33
34
                self.keys = [key for key, _ in txn.cursor()]
            pickle.dump(self.keys, open(cache_file, "wb"))
soumith's avatar
soumith committed
35
36
37
38
39
40
41

    def __getitem__(self, index):
        img, target = None, None
        env = self.env
        with env.begin(write=False) as txn:
            imgbuf = txn.get(self.keys[index])

soumith's avatar
soumith committed
42
        buf = six.BytesIO()
soumith's avatar
soumith committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        buf.write(imgbuf)
        buf.seek(0)
        img = Image.open(buf).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 self.length

58

59
class LSUN(VisionDataset):
soumith's avatar
soumith committed
60
    """
61
62
63
    `LSUN <http://lsun.cs.princeton.edu>`_ dataset.

    Args:
Jason Park's avatar
Jason Park committed
64
        root (string): Root directory for the database files.
65
66
67
68
69
70
        classes (string or list): One of {'train', 'val', 'test'} or a list of
            categories to load. e,g. ['bedroom_train', 'church_train'].
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
soumith's avatar
soumith committed
71
    """
72

73
74
75
    def __init__(self, root, classes='train', transform=None, target_transform=None):
        super(LSUN, self).__init__(root, transform=transform,
                                   target_transform=target_transform)
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
        self.classes = self._verify_classes(classes)

        # for each class, create an LSUNClassDataset
        self.dbs = []
        for c in self.classes:
            self.dbs.append(LSUNClass(
                root=root + '/' + c + '_lmdb',
                transform=transform))

        self.indices = []
        count = 0
        for db in self.dbs:
            count += len(db)
            self.indices.append(count)

        self.length = count

    def _verify_classes(self, classes):
soumith's avatar
soumith committed
94
95
96
97
        categories = ['bedroom', 'bridge', 'church_outdoor', 'classroom',
                      'conference_room', 'dining_room', 'kitchen',
                      'living_room', 'restaurant', 'tower']
        dset_opts = ['train', 'val', 'test']
Jason Park's avatar
Jason Park committed
98

99
100
        try:
            verify_str_arg(classes, "classes", dset_opts)
soumith's avatar
soumith committed
101
102
103
104
            if classes == 'test':
                classes = [classes]
            else:
                classes = [c + '_' + classes for c in categories]
105
        except ValueError:
106
107
108
109
110
111
112
113
            if not isinstance(classes, Iterable):
                msg = ("Expected type str or Iterable for argument classes, "
                       "but got type {}.")
                raise ValueError(msg.format(type(classes)))

            classes = list(classes)
            msg_fmtstr = ("Expected type str for elements in argument classes, "
                          "but got type {}.")
soumith's avatar
soumith committed
114
            for c in classes:
115
                verify_str_arg(c, custom_msg=msg_fmtstr.format(type(c)))
soumith's avatar
soumith committed
116
                c_short = c.split('_')
117
118
                category, dset_opt = '_'.join(c_short[:-1]), c_short[-1]

119
                msg_fmtstr = "Unknown value '{}' for {}. Valid values are {{{}}}."
120
121
122
123
124
125
                msg = msg_fmtstr.format(category, "LSUN class",
                                        iterable_to_str(categories))
                verify_str_arg(category, valid_values=categories, custom_msg=msg)

                msg = msg_fmtstr.format(dset_opt, "postfix", iterable_to_str(dset_opts))
                verify_str_arg(dset_opt, valid_values=dset_opts, custom_msg=msg)
soumith's avatar
soumith committed
126

127
        return classes
soumith's avatar
soumith committed
128
129

    def __getitem__(self, index):
130
131
132
133
134
135
136
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target) where target is the index of the target category.
        """
soumith's avatar
soumith committed
137
138
139
140
141
142
        target = 0
        sub = 0
        for ind in self.indices:
            if index < ind:
                break
            target += 1
Zhou Le's avatar
Zhou Le committed
143
            sub = ind
soumith's avatar
soumith committed
144
145
146
147
148
149
150

        db = self.dbs[target]
        index = index - sub

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

soumith's avatar
soumith committed
151
152
        img, _ = db[index]
        return img, target
soumith's avatar
soumith committed
153
154
155
156

    def __len__(self):
        return self.length

157
158
    def extra_repr(self):
        return "Classes: {classes}".format(**self.__dict__)