lsun.py 4.38 KB
Newer Older
soumith's avatar
soumith committed
1
2
3
4
import torch.utils.data as data
from PIL import Image
import os
import os.path
soumith's avatar
soumith committed
5
import six
soumith's avatar
soumith committed
6
7
8
9
10
11
12
import string
import sys
if sys.version_info[0] == 2:
    import cPickle as pickle
else:
    import pickle

soumith's avatar
soumith committed
13
class LSUNClass(data.Dataset):
soumith's avatar
soumith committed
14
15
16
    def __init__(self, db_path, transform=None, target_transform=None):
        import lmdb
        self.db_path = db_path
soumith's avatar
soumith committed
17
18
        self.env = lmdb.open(db_path, max_readers=1, readonly=True, lock=False,
                             readahead=False, meminit=False)
soumith's avatar
soumith committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
        with self.env.begin(write=False) as txn:
            self.length = txn.stat()['entries']
        cache_file = '_cache_' + db_path.replace('/', '_')
        if os.path.isfile(cache_file):
            self.keys = pickle.load( open( cache_file, "rb" ) )
        else:
            with self.env.begin(write=False) as txn:
                self.keys = [ key for key, _ in txn.cursor() ]
            pickle.dump( self.keys, open( cache_file, "wb" ) )
        self.transform = transform
        self.target_transform = target_transform

    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
37
        buf = six.BytesIO()
soumith's avatar
soumith committed
38
39
40
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

    def __repr__(self):
        return self.__class__.__name__ + ' (' + self.db_path + ')'

soumith's avatar
soumith committed
56
class LSUN(data.Dataset):
soumith's avatar
soumith committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    """
    db_path = root directory for the database files
    classes = 'train' | 'val' | 'test' | ['bedroom_train', 'church_train', ...]
    """
    def __init__(self, db_path, classes='train',
                 transform=None, target_transform=None):
        categories = ['bedroom', 'bridge', 'church_outdoor', 'classroom',
                      'conference_room', 'dining_room', 'kitchen',
                      'living_room', 'restaurant', 'tower']
        dset_opts = ['train', 'val', 'test']
        self.db_path = db_path
        if type(classes) == str and classes in dset_opts:
            classes = [c + '_' + classes for c in categories]
        if type(classes) == list:
            for c in classes:
                c_short = c.split('_')
                c_short.pop(len(c_short) - 1)
Adam Lerer's avatar
Adam Lerer committed
74
                c_short = '_'.join(c_short)
soumith's avatar
soumith committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
                if c_short not in categories:
                    raise(ValueError('Unknown LSUN class: ' + c_short + '.'\
                          'Options are: ' + str(categories)))
                c_short = c.split('_')
                c_short = c_short.pop(len(c_short) - 1)
                if c_short not in dset_opts:
                    raise(ValueError('Unknown postfix: ' + c_short + '.'\
                          'Options are: ' + str(dset_opts)))
        else:
            raise(ValueError('Unknown option for classes'))
        self.classes = classes

        # for each class, create an LSUNClassDataset
        self.dbs = []
        for c in self.classes:
soumith's avatar
soumith committed
90
            self.dbs.append(LSUNClass(
soumith's avatar
soumith committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
                db_path = db_path + '/' + c + '_lmdb',
                transform = transform))

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

        self.length = count
        self.target_transform = target_transform

    def __getitem__(self, index):
        target = 0
        sub = 0
        for ind in self.indices:
            if index < ind:
                break
            target += 1
            sub += ind

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

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

soumith's avatar
soumith committed
118
119
        img, _ = db[index]
        return img, target
soumith's avatar
soumith committed
120
121
122
123
124
125
126
127

    def __len__(self):
        return self.length

    def __repr__(self):
        return self.__class__.__name__ + ' (' + self.db_path + ')'

if __name__ == '__main__':
soumith's avatar
soumith committed
128
    #lsun = LSUNClass(db_path='/home/soumith/local/lsun/train/bedroom_train_lmdb')
soumith's avatar
soumith committed
129
    #a = lsun[0]
soumith's avatar
soumith committed
130
    lsun = LSUN(db_path='/home/soumith/local/lsun/train',
soumith's avatar
soumith committed
131
132
133
134
135
136
                       classes=['bedroom_train', 'church_outdoor_train'])
    print(lsun.classes)
    print(lsun.dbs)
    a, t = lsun[len(lsun)-1]
    print(a)
    print(t)