functional_pil.py 12.2 KB
Newer Older
1
import numbers
2
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
3

vfdev's avatar
vfdev committed
4
import numpy as np
5
import torch
6
from PIL import Image, ImageOps, ImageEnhance
vfdev's avatar
vfdev committed
7

8
9
10
11
12
13
14
try:
    import accimage
except ImportError:
    accimage = None


@torch.jit.unused
vfdev's avatar
vfdev committed
15
def _is_pil_image(img: Any) -> bool:
16
17
18
19
20
21
    if accimage is not None:
        return isinstance(img, (Image.Image, accimage.Image))
    else:
        return isinstance(img, Image.Image)


vfdev's avatar
vfdev committed
22
@torch.jit.unused
23
def get_image_size(img: Any) -> List[int]:
vfdev's avatar
vfdev committed
24
    if _is_pil_image(img):
25
        return list(img.size)
26
    raise TypeError(f"Unexpected type {type(img)}")
vfdev's avatar
vfdev committed
27
28


29
@torch.jit.unused
30
def get_image_num_channels(img: Any) -> int:
31
    if _is_pil_image(img):
32
        return 1 if img.mode == "L" else 3
33
    raise TypeError(f"Unexpected type {type(img)}")
34
35


36
@torch.jit.unused
37
def hflip(img: Image.Image) -> Image.Image:
38
    if not _is_pil_image(img):
39
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
40
41
42
43
44

    return img.transpose(Image.FLIP_LEFT_RIGHT)


@torch.jit.unused
45
def vflip(img: Image.Image) -> Image.Image:
46
    if not _is_pil_image(img):
47
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
48
49

    return img.transpose(Image.FLIP_TOP_BOTTOM)
50
51
52


@torch.jit.unused
53
def adjust_brightness(img: Image.Image, brightness_factor: float) -> Image.Image:
54
    if not _is_pil_image(img):
55
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
56
57
58
59
60
61
62

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img


@torch.jit.unused
63
def adjust_contrast(img: Image.Image, contrast_factor: float) -> Image.Image:
64
    if not _is_pil_image(img):
65
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
66
67
68
69
70
71
72

    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(contrast_factor)
    return img


@torch.jit.unused
73
def adjust_saturation(img: Image.Image, saturation_factor: float) -> Image.Image:
74
    if not _is_pil_image(img):
75
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
76
77
78
79
80
81
82

    enhancer = ImageEnhance.Color(img)
    img = enhancer.enhance(saturation_factor)
    return img


@torch.jit.unused
83
def adjust_hue(img: Image.Image, hue_factor: float) -> Image.Image:
84
    if not (-0.5 <= hue_factor <= 0.5):
85
        raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].")
86
87

    if not _is_pil_image(img):
88
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
89
90

    input_mode = img.mode
91
    if input_mode in {"L", "1", "I", "F"}:
92
93
        return img

94
    h, s, v = img.convert("HSV").split()
95
96
97

    np_h = np.array(h, dtype=np.uint8)
    # uint8 addition take cares of rotation across boundaries
98
    with np.errstate(over="ignore"):
99
        np_h += np.uint8(hue_factor * 255)
100
    h = Image.fromarray(np_h, "L")
101

102
    img = Image.merge("HSV", (h, s, v)).convert(input_mode)
103
    return img
104
105


106
@torch.jit.unused
107
108
109
110
111
112
def adjust_gamma(
    img: Image.Image,
    gamma: float,
    gain: float = 1.0,
) -> Image.Image:

113
    if not _is_pil_image(img):
114
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
115
116

    if gamma < 0:
117
        raise ValueError("Gamma should be a non-negative real number")
118
119

    input_mode = img.mode
120
121
    img = img.convert("RGB")
    gamma_map = [(255 + 1 - 1e-3) * gain * pow(ele / 255.0, gamma) for ele in range(256)] * 3
122
123
124
125
126
127
    img = img.point(gamma_map)  # use PIL's point-function to accelerate this part

    img = img.convert(input_mode)
    return img


128
@torch.jit.unused
129
130
131
132
133
134
135
def pad(
    img: Image.Image,
    padding: Union[int, List[int], Tuple[int, ...]],
    fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0,
    padding_mode: str = "constant",
) -> Image.Image:

136
    if not _is_pil_image(img):
137
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
138
139
140
141
142
143
144
145
146
147
148
149

    if not isinstance(padding, (numbers.Number, tuple, list)):
        raise TypeError("Got inappropriate padding arg")
    if not isinstance(fill, (numbers.Number, str, tuple)):
        raise TypeError("Got inappropriate fill arg")
    if not isinstance(padding_mode, str):
        raise TypeError("Got inappropriate padding_mode arg")

    if isinstance(padding, list):
        padding = tuple(padding)

    if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]:
150
        raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple")
151
152
153
154
155
156
157
158
159

    if isinstance(padding, tuple) and len(padding) == 1:
        # Compatibility with `functional_tensor.pad`
        padding = padding[0]

    if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
        raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")

    if padding_mode == "constant":
160
        opts = _parse_fill(fill, img, name="fill")
161
162
        if img.mode == "P":
            palette = img.getpalette()
163
            image = ImageOps.expand(img, border=padding, **opts)
164
165
166
            image.putpalette(palette)
            return image

167
        return ImageOps.expand(img, border=padding, **opts)
168
169
170
171
172
173
174
175
176
177
178
179
    else:
        if isinstance(padding, int):
            pad_left = pad_right = pad_top = pad_bottom = padding
        if isinstance(padding, tuple) and len(padding) == 2:
            pad_left = pad_right = padding[0]
            pad_top = pad_bottom = padding[1]
        if isinstance(padding, tuple) and len(padding) == 4:
            pad_left = padding[0]
            pad_top = padding[1]
            pad_right = padding[2]
            pad_bottom = padding[3]

180
181
182
183
184
185
186
187
188
        p = [pad_left, pad_top, pad_right, pad_bottom]
        cropping = -np.minimum(p, 0)

        if cropping.any():
            crop_left, crop_top, crop_right, crop_bottom = cropping
            img = img.crop((crop_left, crop_top, img.width - crop_right, img.height - crop_bottom))

        pad_left, pad_top, pad_right, pad_bottom = np.maximum(p, 0)

189
        if img.mode == "P":
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
            palette = img.getpalette()
            img = np.asarray(img)
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)
            img = Image.fromarray(img)
            img.putpalette(palette)
            return img

        img = np.asarray(img)
        # RGB image
        if len(img.shape) == 3:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode)
        # Grayscale image
        if len(img.shape) == 2:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)

        return Image.fromarray(img)
vfdev's avatar
vfdev committed
206
207
208


@torch.jit.unused
209
210
211
212
213
214
215
216
def crop(
    img: Image.Image,
    top: int,
    left: int,
    height: int,
    width: int,
) -> Image.Image:

vfdev's avatar
vfdev committed
217
    if not _is_pil_image(img):
218
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
vfdev's avatar
vfdev committed
219
220

    return img.crop((left, top, left + width, top + height))
vfdev's avatar
vfdev committed
221
222
223


@torch.jit.unused
224
225
226
227
228
229
230
def resize(
    img: Image.Image,
    size: Union[Sequence[int], int],
    interpolation: int = Image.BILINEAR,
    max_size: Optional[int] = None,
) -> Image.Image:

vfdev's avatar
vfdev committed
231
    if not _is_pil_image(img):
232
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
vfdev's avatar
vfdev committed
233
    if not (isinstance(size, int) or (isinstance(size, Sequence) and len(size) in (1, 2))):
234
        raise TypeError(f"Got inappropriate size arg: {size}")
vfdev's avatar
vfdev committed
235

236
237
238
    if isinstance(size, Sequence) and len(size) == 1:
        size = size[0]
    if isinstance(size, int):
vfdev's avatar
vfdev committed
239
        w, h = img.size
240
241
242

        short, long = (w, h) if w <= h else (h, w)
        if short == size:
vfdev's avatar
vfdev committed
243
            return img
244
245
246
247
248
249
250
251
252
253
254
255
256
257

        new_short, new_long = size, int(size * long / short)

        if max_size is not None:
            if max_size <= size:
                raise ValueError(
                    f"max_size = {max_size} must be strictly greater than the requested "
                    f"size for the smaller edge size = {size}"
                )
            if new_long > max_size:
                new_short, new_long = int(max_size * new_short / new_long), max_size

        new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short)
        return img.resize((new_w, new_h), interpolation)
vfdev's avatar
vfdev committed
258
    else:
259
260
261
262
263
        if max_size is not None:
            raise ValueError(
                "max_size should only be passed if size specifies the length of the smaller edge, "
                "i.e. size should be an int or a sequence of length 1 in torchscript mode."
            )
vfdev's avatar
vfdev committed
264
        return img.resize(size[::-1], interpolation)
vfdev's avatar
vfdev committed
265
266
267


@torch.jit.unused
268
269
270
271
272
273
def _parse_fill(
    fill: Optional[Union[float, List[float], Tuple[float, ...]]],
    img: Image.Image,
    name: str = "fillcolor",
) -> Dict[str, Optional[Union[float, List[float], Tuple[float, ...]]]]:

274
    # Process fill color for affine transforms
vfdev's avatar
vfdev committed
275
276
277
278
279
    num_bands = len(img.getbands())
    if fill is None:
        fill = 0
    if isinstance(fill, (int, float)) and num_bands > 1:
        fill = tuple([fill] * num_bands)
280
281
    if isinstance(fill, (list, tuple)):
        if len(fill) != num_bands:
282
            msg = "The number of elements in 'fill' does not match the number of bands of the image ({} != {})"
283
284
285
            raise ValueError(msg.format(len(fill), num_bands))

        fill = tuple(fill)
vfdev's avatar
vfdev committed
286

287
    return {name: fill}
vfdev's avatar
vfdev committed
288
289
290


@torch.jit.unused
291
292
293
294
295
296
297
def affine(
    img: Image.Image,
    matrix: List[float],
    interpolation: int = Image.NEAREST,
    fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0,
) -> Image.Image:

vfdev's avatar
vfdev committed
298
    if not _is_pil_image(img):
299
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
vfdev's avatar
vfdev committed
300
301

    output_size = img.size
302
    opts = _parse_fill(fill, img)
303
    return img.transform(output_size, Image.AFFINE, matrix, interpolation, **opts)
vfdev's avatar
vfdev committed
304
305
306


@torch.jit.unused
307
308
309
310
311
312
313
314
315
def rotate(
    img: Image.Image,
    angle: float,
    interpolation: int = Image.NEAREST,
    expand: bool = False,
    center: Optional[Tuple[int, int]] = None,
    fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0,
) -> Image.Image:

vfdev's avatar
vfdev committed
316
    if not _is_pil_image(img):
317
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
vfdev's avatar
vfdev committed
318

319
    opts = _parse_fill(fill, img)
320
    return img.rotate(angle, interpolation, expand, center, **opts)
321
322
323


@torch.jit.unused
324
325
326
327
328
329
330
def perspective(
    img: Image.Image,
    perspective_coeffs: float,
    interpolation: int = Image.BICUBIC,
    fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0,
) -> Image.Image:

331
    if not _is_pil_image(img):
332
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
333

334
    opts = _parse_fill(fill, img)
335
336

    return img.transform(img.size, Image.PERSPECTIVE, perspective_coeffs, interpolation, **opts)
337
338
339


@torch.jit.unused
340
def to_grayscale(img: Image.Image, num_output_channels: int) -> Image.Image:
341
    if not _is_pil_image(img):
342
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
343
344

    if num_output_channels == 1:
345
        img = img.convert("L")
346
    elif num_output_channels == 3:
347
        img = img.convert("L")
348
349
        np_img = np.array(img, dtype=np.uint8)
        np_img = np.dstack([np_img, np_img, np_img])
350
        img = Image.fromarray(np_img, "RGB")
351
    else:
352
        raise ValueError("num_output_channels should be either 1 or 3")
353
354

    return img
355
356
357


@torch.jit.unused
358
def invert(img: Image.Image) -> Image.Image:
359
    if not _is_pil_image(img):
360
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
361
362
363
364
    return ImageOps.invert(img)


@torch.jit.unused
365
def posterize(img: Image.Image, bits: int) -> Image.Image:
366
    if not _is_pil_image(img):
367
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
368
369
370
371
    return ImageOps.posterize(img, bits)


@torch.jit.unused
372
def solarize(img: Image.Image, threshold: int) -> Image.Image:
373
    if not _is_pil_image(img):
374
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
375
376
377
378
    return ImageOps.solarize(img, threshold)


@torch.jit.unused
379
def adjust_sharpness(img: Image.Image, sharpness_factor: float) -> Image.Image:
380
    if not _is_pil_image(img):
381
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
382
383
384
385
386
387
388

    enhancer = ImageEnhance.Sharpness(img)
    img = enhancer.enhance(sharpness_factor)
    return img


@torch.jit.unused
389
def autocontrast(img: Image.Image) -> Image.Image:
390
    if not _is_pil_image(img):
391
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
392
393
394
395
    return ImageOps.autocontrast(img)


@torch.jit.unused
396
def equalize(img: Image.Image) -> Image.Image:
397
    if not _is_pil_image(img):
398
        raise TypeError(f"img should be PIL Image. Got {type(img)}")
399
    return ImageOps.equalize(img)