lsun.py 4.72 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

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

14

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

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

    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
40
        buf = six.BytesIO()
soumith's avatar
soumith committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        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

56

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

    Args:
Jason Park's avatar
Jason Park committed
62
        root (string): Root directory for the database files.
63
64
65
66
67
68
        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
69
    """
70

Jason Park's avatar
Jason Park committed
71
    def __init__(self, root, classes='train',
soumith's avatar
soumith committed
72
                 transform=None, target_transform=None):
73
74
75
        super(LSUN, self).__init__(root)
        self.transform = transform
        self.target_transform = target_transform
soumith's avatar
soumith committed
76
77
78
79
        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
80

soumith's avatar
soumith committed
81
        if type(classes) == str and classes in dset_opts:
soumith's avatar
soumith committed
82
83
84
85
            if classes == 'test':
                classes = [classes]
            else:
                classes = [c + '_' + classes for c in categories]
86
        elif type(classes) == list:
soumith's avatar
soumith committed
87
88
89
            for c in classes:
                c_short = c.split('_')
                c_short.pop(len(c_short) - 1)
Adam Lerer's avatar
Adam Lerer committed
90
                c_short = '_'.join(c_short)
soumith's avatar
soumith committed
91
                if c_short not in categories:
92
93
                    raise (ValueError('Unknown LSUN class: ' + c_short + '.'
                                      'Options are: ' + str(categories)))
soumith's avatar
soumith committed
94
95
96
                c_short = c.split('_')
                c_short = c_short.pop(len(c_short) - 1)
                if c_short not in dset_opts:
97
98
                    raise (ValueError('Unknown postfix: ' + c_short + '.'
                                      'Options are: ' + str(dset_opts)))
soumith's avatar
soumith committed
99
        else:
100
            raise (ValueError('Unknown option for classes'))
soumith's avatar
soumith committed
101
102
103
104
105
        self.classes = classes

        # for each class, create an LSUNClassDataset
        self.dbs = []
        for c in self.classes:
soumith's avatar
soumith committed
106
            self.dbs.append(LSUNClass(
Jason Park's avatar
Jason Park committed
107
                root=root + '/' + c + '_lmdb',
108
                transform=transform))
soumith's avatar
soumith committed
109
110
111
112
113
114
115
116
117
118

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

        self.length = count

    def __getitem__(self, index):
119
120
121
122
123
124
125
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target) where target is the index of the target category.
        """
soumith's avatar
soumith committed
126
127
128
129
130
131
        target = 0
        sub = 0
        for ind in self.indices:
            if index < ind:
                break
            target += 1
Zhou Le's avatar
Zhou Le committed
132
            sub = ind
soumith's avatar
soumith committed
133
134
135
136
137
138
139

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

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

soumith's avatar
soumith committed
140
141
        img, _ = db[index]
        return img, target
soumith's avatar
soumith committed
142
143
144
145

    def __len__(self):
        return self.length

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