transforms.py 7.54 KB
Newer Older
1
from __future__ import division
soumith's avatar
soumith committed
2
3
4
import torch
import math
import random
5
from PIL import Image, ImageOps
6
import numpy as np
7
import numbers
Soumith Chintala's avatar
Soumith Chintala committed
8
import types
soumith's avatar
soumith committed
9

10

soumith's avatar
soumith committed
11
class Compose(object):
Adam Paszke's avatar
Adam Paszke committed
12
13
14
15
16
17
18
19
20
21
    """Composes several transforms together.

    Args:
        transforms (List[Transform]): list of transforms to compose.

    Example:
        >>> transforms.Compose([
        >>>     transforms.CenterCrop(10),
        >>>     transforms.ToTensor(),
        >>> ])
22
    """
23

soumith's avatar
soumith committed
24
25
26
27
28
29
30
31
32
33
    def __init__(self, transforms):
        self.transforms = transforms

    def __call__(self, img):
        for t in self.transforms:
            img = t(img)
        return img


class ToTensor(object):
34
    """Converts a PIL.Image or numpy.ndarray (H x W x C) in the range
Adam Paszke's avatar
Adam Paszke committed
35
36
    [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
    """
37

soumith's avatar
soumith committed
38
    def __call__(self, pic):
39
40
        if isinstance(pic, np.ndarray):
            # handle numpy array
41
            img = torch.from_numpy(pic.transpose((2, 0, 1)))
42
43
44
        else:
            # handle PIL Image
            img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes()))
45
46
47
48
49
50
            # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK
            if pic.mode == 'YCbCr':
                nchannel = 3
            else:
                nchannel = len(pic.mode)
            img = img.view(pic.size[1], pic.size[0], nchannel)
Soumith Chintala's avatar
Soumith Chintala committed
51
            # put it from HWC to CHW format
52
            # yikes, this transpose takes 80% of the loading time/CPU
Soumith Chintala's avatar
Soumith Chintala committed
53
            img = img.transpose(0, 1).transpose(0, 2).contiguous()
54
55
        return img.float().div(255)

Adam Paszke's avatar
Adam Paszke committed
56

57
class ToPILImage(object):
58
59
    """Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape
    H x W x C to a PIL.Image while preserving value range.
60
    """
61

62
    def __call__(self, pic):
63
64
        npimg = pic
        mode = None
65
66
67
68
69
        if isinstance(pic, torch.FloatTensor):
            pic = pic.mul(255).byte()
        if torch.is_tensor(pic):
            npimg = np.transpose(pic.numpy(), (1, 2, 0))
        assert isinstance(npimg, np.ndarray), 'pic should be Tensor or ndarray'
70
71
72

        if npimg.shape[2] == 1:
            npimg = npimg[:, :, 0]
73
74
75
76
77
78
79
80
81
82
83

            if npimg.dtype == np.uint8:
                mode = 'L'
            if npimg.dtype == np.uint16:
                mode = 'I;16'
            elif npimg.dtype == np.float32:
                mode = 'F'
        else:
            if npimg.dtype == np.uint8:
                mode = 'RGB'
        assert mode is not None, '{} is not supported'.format(npimg.dtype)
84
85
86

        return Image.fromarray(npimg, mode=mode)

soumith's avatar
soumith committed
87
88

class Normalize(object):
Adam Paszke's avatar
Adam Paszke committed
89
    """Given mean: (R, G, B) and std: (R, G, B),
90
91
92
    will normalize each channel of the torch.*Tensor, i.e.
    channel = (channel - mean) / std
    """
93

soumith's avatar
soumith committed
94
95
96
97
98
    def __init__(self, mean, std):
        self.mean = mean
        self.std = std

    def __call__(self, tensor):
99
        # TODO: make efficient
soumith's avatar
soumith committed
100
101
102
103
104
105
        for t, m, s in zip(tensor, self.mean, self.std):
            t.sub_(m).div_(s)
        return tensor


class Scale(object):
Adam Paszke's avatar
Adam Paszke committed
106
    """Rescales the input PIL.Image to the given 'size'.
107
108
109
110
111
112
    'size' will be the size of the smaller edge.
    For example, if height > width, then image will be
    rescaled to (size * height / width, size)
    size: size of the smaller edge
    interpolation: Default: PIL.Image.BILINEAR
    """
113

soumith's avatar
soumith committed
114
115
116
117
118
119
120
121
122
    def __init__(self, size, interpolation=Image.BILINEAR):
        self.size = size
        self.interpolation = interpolation

    def __call__(self, img):
        w, h = img.size
        if (w <= h and w == self.size) or (h <= w and h == self.size):
            return img
        if w < h:
123
124
125
            ow = self.size
            oh = int(self.size * h / w)
            return img.resize((ow, oh), self.interpolation)
soumith's avatar
soumith committed
126
        else:
127
128
129
            oh = self.size
            ow = int(self.size * w / h)
            return img.resize((ow, oh), self.interpolation)
soumith's avatar
soumith committed
130
131
132


class CenterCrop(object):
133
134
135
136
    """Crops the given PIL.Image at the center to have a region of
    the given size. size can be a tuple (target_height, target_width)
    or an integer, in which case the target will be of a square shape (size, size)
    """
137

soumith's avatar
soumith committed
138
    def __init__(self, size):
139
140
141
142
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size
soumith's avatar
soumith committed
143
144
145

    def __call__(self, img):
        w, h = img.size
146
        th, tw = self.size
147
148
        x1 = int(round((w - tw) / 2.))
        y1 = int(round((h - th) / 2.))
149
        return img.crop((x1, y1, x1 + tw, y1 + th))
soumith's avatar
soumith committed
150
151


152
153
class Pad(object):
    """Pads the given PIL.Image on all sides with the given "pad" value"""
154

155
156
    def __init__(self, padding, fill=0):
        assert isinstance(padding, numbers.Number)
157
        assert isinstance(fill, numbers.Number) or isinstance(fill, str) or isinstance(fill, tuple)
158
159
160
161
162
163
        self.padding = padding
        self.fill = fill

    def __call__(self, img):
        return ImageOps.expand(img, border=self.padding, fill=self.fill)

164

Soumith Chintala's avatar
Soumith Chintala committed
165
class Lambda(object):
Adam Paszke's avatar
Adam Paszke committed
166
    """Applies a lambda as a transform."""
167

Soumith Chintala's avatar
Soumith Chintala committed
168
    def __init__(self, lambd):
169
        assert isinstance(lambd, types.LambdaType)
Soumith Chintala's avatar
Soumith Chintala committed
170
171
172
173
174
        self.lambd = lambd

    def __call__(self, img):
        return self.lambd(img)

175

soumith's avatar
soumith committed
176
class RandomCrop(object):
177
178
179
180
    """Crops the given PIL.Image at a random location to have a region of
    the given size. size can be a tuple (target_height, target_width)
    or an integer, in which case the target will be of a square shape (size, size)
    """
181

soumith's avatar
soumith committed
182
    def __init__(self, size, padding=0):
183
184
185
186
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size
soumith's avatar
soumith committed
187
188
189
190
        self.padding = padding

    def __call__(self, img):
        if self.padding > 0:
191
            img = ImageOps.expand(img, border=self.padding, fill=0)
soumith's avatar
soumith committed
192
193

        w, h = img.size
194
195
        th, tw = self.size
        if w == tw and h == th:
soumith's avatar
soumith committed
196
197
            return img

198
199
200
        x1 = random.randint(0, w - tw)
        y1 = random.randint(0, h - th)
        return img.crop((x1, y1, x1 + tw, y1 + th))
soumith's avatar
soumith committed
201
202
203


class RandomHorizontalFlip(object):
204
205
    """Randomly horizontally flips the given PIL.Image with a probability of 0.5
    """
206

soumith's avatar
soumith committed
207
208
209
210
211
212
213
    def __call__(self, img):
        if random.random() < 0.5:
            return img.transpose(Image.FLIP_LEFT_RIGHT)
        return img


class RandomSizedCrop(object):
214
215
216
217
218
219
    """Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size
    and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio
    This is popularly used to train the Inception networks
    size: size of the smaller edge
    interpolation: Default: PIL.Image.BILINEAR
    """
220

soumith's avatar
soumith committed
221
222
223
224
225
226
227
228
    def __init__(self, size, interpolation=Image.BILINEAR):
        self.size = size
        self.interpolation = interpolation

    def __call__(self, img):
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.08, 1.0) * area
229
            aspect_ratio = random.uniform(3. / 4, 4. / 3)
soumith's avatar
soumith committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                assert(img.size == (w, h))

                return img.resize((self.size, self.size), self.interpolation)

        # Fallback
        scale = Scale(self.size, interpolation=self.interpolation)
        crop = CenterCrop(self.size)
        return crop(scale(img))