lsun.py 5.67 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
Philip Meier's avatar
Philip Meier committed
5
import io
soumith's avatar
soumith committed
6
import string
7
from collections.abc import Iterable
8
import pickle
9
from typing import Any, Callable, cast, List, Optional, Tuple, Union
10
11
from .utils import verify_str_arg, iterable_to_str

12

13
class LSUNClass(VisionDataset):
14
15
16
17
    def __init__(
            self, root: str, transform: Optional[Callable] = None,
            target_transform: Optional[Callable] = None
    ) -> None:
soumith's avatar
soumith committed
18
        import lmdb
19
20
        super(LSUNClass, self).__init__(root, transform=transform,
                                        target_transform=target_transform)
Jason Park's avatar
Jason Park committed
21
22

        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
                self.keys = [key for key in txn.cursor().iternext(keys=True, values=False)]
32
            pickle.dump(self.keys, open(cache_file, "wb"))
soumith's avatar
soumith committed
33

34
    def __getitem__(self, index: int) -> Tuple[Any, Any]:
soumith's avatar
soumith committed
35
36
37
38
39
        img, target = None, None
        env = self.env
        with env.begin(write=False) as txn:
            imgbuf = txn.get(self.keys[index])

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

53
    def __len__(self) -> int:
soumith's avatar
soumith committed
54
55
        return self.length

56

57
class LSUN(VisionDataset):
soumith's avatar
soumith committed
58
    """
Gerald Baier's avatar
Gerald Baier committed
59
    `LSUN <https://www.yf.io/p/lsun>`_ dataset.
60
61

    Args:
Jason Park's avatar
Jason Park committed
62
        root (string): Root directory for the database files.
63
        classes (string or list): One of {'train', 'val', 'test'} or a list of
64
            categories to load. e,g. ['bedroom_train', 'church_outdoor_train'].
65
66
67
68
        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

71
72
73
74
75
76
77
    def __init__(
            self,
            root: str,
            classes: Union[str, List[str]] = "train",
            transform: Optional[Callable] = None,
            target_transform: Optional[Callable] = None,
    ) -> None:
78
79
        super(LSUN, self).__init__(root, transform=transform,
                                   target_transform=target_transform)
80
81
82
83
84
85
        self.classes = self._verify_classes(classes)

        # for each class, create an LSUNClassDataset
        self.dbs = []
        for c in self.classes:
            self.dbs.append(LSUNClass(
86
                root=os.path.join(root, f"{c}_lmdb"),
87
88
89
90
91
92
93
94
95
96
                transform=transform))

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

        self.length = count

97
    def _verify_classes(self, classes: Union[str, List[str]]) -> List[str]:
soumith's avatar
soumith committed
98
99
100
101
        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
102

103
        try:
104
            classes = cast(str, classes)
105
            verify_str_arg(classes, "classes", dset_opts)
soumith's avatar
soumith committed
106
107
108
109
            if classes == 'test':
                classes = [classes]
            else:
                classes = [c + '_' + classes for c in categories]
110
        except ValueError:
111
112
113
114
115
116
            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)
117
118
            msg_fmtstr_type = ("Expected type str for elements in argument classes, "
                               "but got type {}.")
soumith's avatar
soumith committed
119
            for c in classes:
120
                verify_str_arg(c, custom_msg=msg_fmtstr_type.format(type(c)))
soumith's avatar
soumith committed
121
                c_short = c.split('_')
122
123
                category, dset_opt = '_'.join(c_short[:-1]), c_short[-1]

124
                msg_fmtstr = "Unknown value '{}' for {}. Valid values are {{{}}}."
125
126
127
128
129
130
                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
131

132
        return classes
soumith's avatar
soumith committed
133

134
    def __getitem__(self, index: int) -> Tuple[Any, Any]:
135
136
137
138
139
140
141
        """
        Args:
            index (int): Index

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

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

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

soumith's avatar
soumith committed
156
157
        img, _ = db[index]
        return img, target
soumith's avatar
soumith committed
158

159
    def __len__(self) -> int:
soumith's avatar
soumith committed
160
161
        return self.length

162
    def extra_repr(self) -> str:
163
        return "Classes: {classes}".format(**self.__dict__)