transforms.py 63.3 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import math
16
import numbers
L
LielinJiang 已提交
17
import random
18 19
import traceback
from collections.abc import Iterable, Sequence
L
LielinJiang 已提交
20 21 22

import numpy as np

23
import paddle
L
LielinJiang 已提交
24

25
from . import functional as F
L
LielinJiang 已提交
26

27
__all__ = []
L
LielinJiang 已提交
28 29


30 31 32 33 34
def _get_image_size(img):
    if F._is_pil_image(img):
        return img.size
    elif F._is_numpy_image(img):
        return img.shape[:2][::-1]
35
    elif F._is_tensor_image(img):
36 37 38 39 40 41
        if len(img.shape) == 3:
            return img.shape[1:][::-1]  # chw -> wh
        elif len(img.shape) == 4:
            return img.shape[2:][::-1]  # nchw -> wh
        else:
            raise ValueError(
42 43 44 45
                "The dim for input Tensor should be 3-D or 4-D, but received {}".format(
                    len(img.shape)
                )
            )
46 47 48 49
    else:
        raise TypeError("Unexpected type {}".format(type(img)))


50 51 52
def _check_input(
    value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True
):
53 54 55 56
    if isinstance(value, numbers.Number):
        if value < 0:
            raise ValueError(
                "If {} is a single number, it must be non negative.".format(
57 58 59
                    name
                )
            )
60 61 62 63 64
        value = [center - value, center + value]
        if clip_first_on_zero:
            value[0] = max(value[0], 0)
    elif isinstance(value, (tuple, list)) and len(value) == 2:
        if not bound[0] <= value[0] <= value[1] <= bound[1]:
65 66 67
            raise ValueError(
                "{} values should be between {}".format(name, bound)
            )
68 69
    else:
        raise TypeError(
70 71 72 73
            "{} should be a single number or a list/tuple with lenght 2.".format(
                name
            )
        )
74 75 76 77 78 79

    if value[0] == value[1] == center:
        value = None
    return value


80
class Compose:
L
LielinJiang 已提交
81 82 83 84 85
    """
    Composes several transforms together use for composing list of transforms
    together for a dataset transform.

    Args:
86
        transforms (list|tuple): List/Tuple of transforms to compose.
L
LielinJiang 已提交
87 88 89 90 91 92

    Returns:
        A compose object which is callable, __call__ for this Compose
        object will call each given :attr:`transforms` sequencely.

    Examples:
93

L
LielinJiang 已提交
94 95
        .. code-block:: python

96 97
            from paddle.vision.datasets import Flowers
            from paddle.vision.transforms import Compose, ColorJitter, Resize
L
LielinJiang 已提交
98 99 100 101 102 103

            transform = Compose([ColorJitter(), Resize(size=608)])
            flowers = Flowers(mode='test', transform=transform)

            for i in range(10):
                sample = flowers[i]
104
                print(sample[0].size, sample[1])
L
LielinJiang 已提交
105 106 107 108 109 110

    """

    def __init__(self, transforms):
        self.transforms = transforms

111
    def __call__(self, data):
L
LielinJiang 已提交
112 113
        for f in self.transforms:
            try:
114
                data = f(data)
L
LielinJiang 已提交
115 116
            except Exception as e:
                stack_info = traceback.format_exc()
117 118 119 120
                print(
                    "fail to perform transform [{}] with error: "
                    "{} and stack:\n{}".format(f, e, str(stack_info))
                )
L
LielinJiang 已提交
121 122 123 124 125 126 127 128 129 130 131 132
                raise e
        return data

    def __repr__(self):
        format_string = self.__class__.__name__ + '('
        for t in self.transforms:
            format_string += '\n'
            format_string += '    {0}'.format(t)
        format_string += '\n)'
        return format_string


133
class BaseTransform:
134 135
    """
    Base class of all transforms used in computer vision.
L
LielinJiang 已提交
136

137
    calling logic:
138

I
Infinity_lee 已提交
139 140
    .. code-block:: text

141 142 143
        if keys is None:
            _get_params -> _apply_image()
        else:
144
            _get_params -> _apply_*() for * in keys
145 146 147

    If you want to implement a self-defined transform method for image,
    rewrite _apply_* method in subclass.
L
LielinJiang 已提交
148

149 150 151 152
    Args:
        keys (list[str]|tuple[str], optional): Input type. Input is a tuple contains different structures,
            key is used to specify the type of input. For example, if your input
            is image type, then the key can be None or ("image"). if your input
153
            is (image, image) type, then the keys should be ("image", "image").
154 155 156 157
            if your input is (image, boxes), then the keys should be ("image", "boxes").

            Current available strings & data type are describe below:

I
Infinity_lee 已提交
158 159 160 161 162
                - "image": input image, with shape of (H, W, C)
                - "coords": coordinates, with shape of (N, 2)
                - "boxes": bounding boxes, with shape of (N, 4), "xyxy" format,the 1st "xy" represents
                  top left point of a box,the 2nd "xy" represents right bottom point.
                - "mask": map used for segmentation, with shape of (H, W, 1)
163

164 165
            You can also customize your data types only if you implement the corresponding
            _apply_*() methods, otherwise ``NotImplementedError`` will be raised.
166

L
LielinJiang 已提交
167
    Examples:
168

L
LielinJiang 已提交
169 170 171
        .. code-block:: python

            import numpy as np
172 173 174 175 176 177 178 179 180 181 182 183 184 185
            from PIL import Image
            import paddle.vision.transforms.functional as F
            from paddle.vision.transforms import BaseTransform

            def _get_image_size(img):
                if F._is_pil_image(img):
                    return img.size
                elif F._is_numpy_image(img):
                    return img.shape[:2][::-1]
                else:
                    raise TypeError("Unexpected type {}".format(type(img)))

            class CustomRandomFlip(BaseTransform):
                def __init__(self, prob=0.5, keys=None):
186
                    super().__init__(keys)
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
                    self.prob = prob

                def _get_params(self, inputs):
                    image = inputs[self.keys.index('image')]
                    params = {}
                    params['flip'] = np.random.random() < self.prob
                    params['size'] = _get_image_size(image)
                    return params

                def _apply_image(self, image):
                    if self.params['flip']:
                        return F.hflip(image)
                    return image

                # if you only want to transform image, do not need to rewrite this function
                def _apply_coords(self, coords):
                    if self.params['flip']:
                        w = self.params['size'][0]
                        coords[:, 0] = w - coords[:, 0]
                    return coords

                # if you only want to transform image, do not need to rewrite this function
                def _apply_boxes(self, boxes):
                    idxs = np.array([(0, 1), (2, 1), (0, 3), (2, 3)]).flatten()
                    coords = np.asarray(boxes).reshape(-1, 4)[:, idxs].reshape(-1, 2)
                    coords = self._apply_coords(coords).reshape((-1, 4, 2))
                    minxy = coords.min(axis=1)
                    maxxy = coords.max(axis=1)
                    trans_boxes = np.concatenate((minxy, maxxy), axis=1)
                    return trans_boxes
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
                # if you only want to transform image, do not need to rewrite this function
                def _apply_mask(self, mask):
                    if self.params['flip']:
                        return F.hflip(mask)
                    return mask

            # create fake inputs
            fake_img = Image.fromarray((np.random.rand(400, 500, 3) * 255.).astype('uint8'))
            fake_boxes = np.array([[2, 3, 200, 300], [50, 60, 80, 100]])
            fake_mask = fake_img.convert('L')

            # only transform for image:
            flip_transform = CustomRandomFlip(1.0)
            converted_img = flip_transform(fake_img)

            # transform for image, boxes and mask
            flip_transform = CustomRandomFlip(1.0, keys=('image', 'boxes', 'mask'))
            (converted_img, converted_boxes, converted_mask) = flip_transform((fake_img, fake_boxes, fake_mask))
            print('converted boxes', converted_boxes)
L
LielinJiang 已提交
237 238 239

    """

240 241
    def __init__(self, keys=None):
        if keys is None:
242
            keys = ("image",)
243 244
        elif not isinstance(keys, Sequence):
            raise ValueError(
245 246
                "keys should be a sequence, but got keys={}".format(keys)
            )
247 248 249
        for k in keys:
            if self._get_apply(k) is None:
                raise NotImplementedError(
250 251
                    "{} is unsupported data structure".format(k)
                )
252 253 254 255 256 257 258 259 260 261 262
        self.keys = keys

        # storage some params get from function get_params()
        self.params = None

    def _get_params(self, inputs):
        pass

    def __call__(self, inputs):
        """Apply transform on single input data"""
        if not isinstance(inputs, tuple):
263
            inputs = (inputs,)
264 265 266 267 268 269 270 271 272 273 274

        self.params = self._get_params(inputs)

        outputs = []
        for i in range(min(len(inputs), len(self.keys))):
            apply_func = self._get_apply(self.keys[i])
            if apply_func is None:
                outputs.append(inputs[i])
            else:
                outputs.append(apply_func(inputs[i]))
        if len(inputs) > len(self.keys):
275
            outputs.extend(inputs[len(self.keys) :])
276 277 278 279 280 281

        if len(outputs) == 1:
            outputs = outputs[0]
        else:
            outputs = tuple(outputs)
        return outputs
L
LielinJiang 已提交
282

283 284
    def _get_apply(self, key):
        return getattr(self, "_apply_{}".format(key), None)
L
LielinJiang 已提交
285

286 287
    def _apply_image(self, image):
        raise NotImplementedError
L
LielinJiang 已提交
288

289 290
    def _apply_boxes(self, boxes):
        raise NotImplementedError
L
LielinJiang 已提交
291

292 293
    def _apply_mask(self, mask):
        raise NotImplementedError
L
LielinJiang 已提交
294

295 296 297 298

class ToTensor(BaseTransform):
    """Convert a ``PIL.Image`` or ``numpy.ndarray`` to ``paddle.Tensor``.

L
LielinJiang 已提交
299 300
    Converts a PIL.Image or numpy.ndarray (H x W x C) to a paddle.Tensor of shape (C x H x W).

301
    If input is a grayscale image (H x W), it will be converted to an image of shape (H x W x 1).
L
LielinJiang 已提交
302 303 304 305
    And the shape of output tensor will be (1 x H x W).

    If you want to keep the shape of output tensor as (H x W x C), you can set data_format = ``HWC`` .

306 307 308
    Converts a PIL.Image or numpy.ndarray in the range [0, 255] to a paddle.Tensor in the
    range [0.0, 1.0] if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr,
    RGBA, CMYK, 1) or if the numpy.ndarray has dtype = np.uint8.
309 310 311 312

    In the other cases, tensors are returned without scaling.

    Args:
313
        data_format (str, optional): Data format of output tensor, should be 'HWC' or
314 315
            'CHW'. Default: 'CHW'.
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
316

317 318 319 320 321 322 323
    Shape:
        - img(PIL.Image|np.ndarray): The input image with shape (H x W x C).
        - output(np.ndarray): A tensor with shape (C x H x W) or (H x W x C) according option data_format.

    Returns:
        A callable object of ToTensor.

324
    Examples:
325

326 327 328 329 330 331 332 333
        .. code-block:: python

            import numpy as np
            from PIL import Image

            import paddle.vision.transforms as T
            import paddle.vision.transforms.functional as F

L
Liyulingyue 已提交
334
            fake_img = Image.fromarray((np.random.rand(4, 5, 3) * 255.).astype(np.uint8))
335 336 337 338

            transform = T.ToTensor()

            tensor = transform(fake_img)
339

L
Liyulingyue 已提交
340 341
            print(tensor.shape)
            # [3, 4, 5]
342

L
Liyulingyue 已提交
343 344
            print(tensor.dtype)
            # paddle.float32
345 346 347
    """

    def __init__(self, data_format='CHW', keys=None):
348
        super().__init__(keys)
349 350 351 352 353 354 355 356 357 358 359 360 361 362
        self.data_format = data_format

    def _apply_image(self, img):
        """
        Args:
            img (PIL.Image|np.ndarray): Image to be converted to tensor.

        Returns:
            Tensor: Converted image.
        """
        return F.to_tensor(img, self.data_format)


class Resize(BaseTransform):
L
LielinJiang 已提交
363 364 365 366 367 368 369 370
    """Resize the input Image to the given size.

    Args:
        size (int|list|tuple): Desired output size. If size is a sequence like
            (h, w), output size will be matched to this. If size is an int,
            smaller edge of the image will be matched to this number.
            i.e, if height > width, then image will be rescaled to
            (size * height / width, size)
371 372 373 374 375 376 377
        interpolation (int|str, optional): Interpolation method. Default: 'bilinear'.
            when use pil backend, support method are as following:
            - "nearest": Image.NEAREST,
            - "bilinear": Image.BILINEAR,
            - "bicubic": Image.BICUBIC,
            - "box": Image.BOX,
            - "lanczos": Image.LANCZOS,
378
            - "hamming": Image.HAMMING
379 380 381 382 383
            when use cv2 backend, support method are as following:
            - "nearest": cv2.INTER_NEAREST,
            - "bilinear": cv2.INTER_LINEAR,
            - "area": cv2.INTER_AREA,
            - "bicubic": cv2.INTER_CUBIC,
384 385
            - "lanczos": cv2.INTER_LANCZOS4
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
386

387 388 389 390 391 392 393
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A resized image.

    Returns:
        A callable object of Resize.

L
LielinJiang 已提交
394
    Examples:
395

L
LielinJiang 已提交
396 397 398
        .. code-block:: python

            import numpy as np
399
            from PIL import Image
400
            from paddle.vision.transforms import Resize
L
LielinJiang 已提交
401

402
            fake_img = Image.fromarray((np.random.rand(256, 300, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
403

404 405 406 407 408 409 410 411 412
            transform = Resize(size=224)
            converted_img = transform(fake_img)
            print(converted_img.size)
            # (262, 224)

            transform = Resize(size=(200,150))
            converted_img = transform(fake_img)
            print(converted_img.size)
            # (150, 200)
L
LielinJiang 已提交
413 414
    """

415
    def __init__(self, size, interpolation='bilinear', keys=None):
416
        super().__init__(keys)
417 418 419
        assert isinstance(size, int) or (
            isinstance(size, Iterable) and len(size) == 2
        )
L
LielinJiang 已提交
420 421 422
        self.size = size
        self.interpolation = interpolation

423
    def _apply_image(self, img):
L
LielinJiang 已提交
424 425 426
        return F.resize(img, self.size, self.interpolation)


427
class RandomResizedCrop(BaseTransform):
L
LielinJiang 已提交
428 429 430 431 432 433
    """Crop the input data to random size and aspect ratio.
    A crop of random size (default: of 0.08 to 1.0) of the original size and a random
    aspect ratio (default: of 3/4 to 1.33) of the original aspect ratio is made.
    After applying crop transfrom, the input data will be resized to given size.

    Args:
434
        size (int|list|tuple): Target size of output image, with (height, width) shape.
I
Infinity_lee 已提交
435 436 437
        scale (list|tuple, optional): Scale range of the cropped image before resizing, relatively to the origin
            image. Default: (0.08, 1.0).
        ratio (list|tuple, optional): Range of aspect ratio of the origin aspect ratio cropped. Default: (0.75, 1.33)
438 439 440 441 442 443 444
        interpolation (int|str, optional): Interpolation method. Default: 'bilinear'. when use pil backend,
            support method are as following:
            - "nearest": Image.NEAREST,
            - "bilinear": Image.BILINEAR,
            - "bicubic": Image.BICUBIC,
            - "box": Image.BOX,
            - "lanczos": Image.LANCZOS,
445
            - "hamming": Image.HAMMING
446 447 448 449 450
            when use cv2 backend, support method are as following:
            - "nearest": cv2.INTER_NEAREST,
            - "bilinear": cv2.INTER_LINEAR,
            - "area": cv2.INTER_AREA,
            - "bicubic": cv2.INTER_CUBIC,
451 452
            - "lanczos": cv2.INTER_LANCZOS4
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
453

454 455 456 457 458 459 460
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A cropped image.

    Returns:
        A callable object of RandomResizedCrop.

L
LielinJiang 已提交
461
    Examples:
462

L
LielinJiang 已提交
463 464 465
        .. code-block:: python

            import numpy as np
466
            from PIL import Image
467
            from paddle.vision.transforms import RandomResizedCrop
L
LielinJiang 已提交
468 469 470

            transform = RandomResizedCrop(224)

471
            fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
472 473

            fake_img = transform(fake_img)
474 475
            print(fake_img.size)

L
LielinJiang 已提交
476 477
    """

478 479 480 481 482 483 484 485
    def __init__(
        self,
        size,
        scale=(0.08, 1.0),
        ratio=(3.0 / 4, 4.0 / 3),
        interpolation='bilinear',
        keys=None,
    ):
486
        super().__init__(keys)
487 488
        if isinstance(size, int):
            self.size = (size, size)
L
LielinJiang 已提交
489
        else:
490
            self.size = size
491 492
        assert scale[0] <= scale[1], "scale should be of kind (min, max)"
        assert ratio[0] <= ratio[1], "ratio should be of kind (min, max)"
L
LielinJiang 已提交
493 494 495 496
        self.scale = scale
        self.ratio = ratio
        self.interpolation = interpolation

497 498
    def _get_param(self, image, attempts=10):
        width, height = _get_image_size(image)
L
LielinJiang 已提交
499 500 501 502 503 504 505 506 507 508 509
        area = height * width

        for _ in range(attempts):
            target_area = np.random.uniform(*self.scale) * area
            log_ratio = tuple(math.log(x) for x in self.ratio)
            aspect_ratio = math.exp(np.random.uniform(*log_ratio))

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

            if 0 < w <= width and 0 < h <= height:
510 511 512
                i = random.randint(0, height - h)
                j = random.randint(0, width - w)
                return i, j, h, w
L
LielinJiang 已提交
513 514 515 516 517 518 519 520 521

        # Fallback to central crop
        in_ratio = float(width) / float(height)
        if in_ratio < min(self.ratio):
            w = width
            h = int(round(w / min(self.ratio)))
        elif in_ratio > max(self.ratio):
            h = height
            w = int(round(h * max(self.ratio)))
522 523
        else:
            # return whole image
L
LielinJiang 已提交
524 525
            w = width
            h = height
526 527 528
        i = (height - h) // 2
        j = (width - w) // 2
        return i, j, h, w
L
LielinJiang 已提交
529

530 531
    def _apply_image(self, img):
        i, j, h, w = self._get_param(img)
L
LielinJiang 已提交
532

533
        cropped_img = F.crop(img, i, j, h, w)
L
LielinJiang 已提交
534 535 536
        return F.resize(cropped_img, self.size, self.interpolation)


537
class CenterCrop(BaseTransform):
L
LielinJiang 已提交
538 539 540
    """Crops the given the input data at the center.

    Args:
541 542 543
        size (int|list|tuple): Target size of output image, with (height, width) shape.
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.

544 545 546 547 548 549 550
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A cropped image.

    Returns:
        A callable object of CenterCrop.

L
LielinJiang 已提交
551
    Examples:
552

L
LielinJiang 已提交
553 554 555
        .. code-block:: python

            import numpy as np
556
            from PIL import Image
557
            from paddle.vision.transforms import CenterCrop
L
LielinJiang 已提交
558 559 560

            transform = CenterCrop(224)

561
            fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
562 563

            fake_img = transform(fake_img)
564
            print(fake_img.size)
L
LielinJiang 已提交
565 566
    """

567
    def __init__(self, size, keys=None):
568
        super().__init__(keys)
569 570
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
L
LielinJiang 已提交
571
        else:
572
            self.size = size
L
LielinJiang 已提交
573

574 575
    def _apply_image(self, img):
        return F.center_crop(img, self.size)
L
LielinJiang 已提交
576 577


578
class RandomHorizontalFlip(BaseTransform):
L
LielinJiang 已提交
579 580 581
    """Horizontally flip the input data randomly with a given probability.

    Args:
B
Bin Lu 已提交
582
        prob (float, optional): Probability of the input data being flipped. Should be in [0, 1]. Default: 0.5
583
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
584

585 586 587 588 589 590 591
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A horiziotal flipped image.

    Returns:
        A callable object of RandomHorizontalFlip.

L
LielinJiang 已提交
592
    Examples:
593

L
LielinJiang 已提交
594 595 596
        .. code-block:: python

            import numpy as np
597
            from PIL import Image
598
            from paddle.vision.transforms import RandomHorizontalFlip
L
LielinJiang 已提交
599

B
Bin Lu 已提交
600
            transform = RandomHorizontalFlip(0.5)
L
LielinJiang 已提交
601

602
            fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
603 604

            fake_img = transform(fake_img)
605
            print(fake_img.size)
L
LielinJiang 已提交
606 607
    """

608
    def __init__(self, prob=0.5, keys=None):
609
        super().__init__(keys)
I
IMMORTAL 已提交
610
        assert 0 <= prob <= 1, "probability must be between 0 and 1"
L
LielinJiang 已提交
611 612
        self.prob = prob

613 614 615
    def _apply_image(self, img):
        if random.random() < self.prob:
            return F.hflip(img)
L
LielinJiang 已提交
616 617 618
        return img


619
class RandomVerticalFlip(BaseTransform):
L
LielinJiang 已提交
620 621 622
    """Vertically flip the input data randomly with a given probability.

    Args:
623 624
        prob (float, optional): Probability of the input data being flipped. Default: 0.5
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
625

626 627 628 629 630 631 632
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A vertical flipped image.

    Returns:
        A callable object of RandomVerticalFlip.

L
LielinJiang 已提交
633
    Examples:
634

L
LielinJiang 已提交
635 636 637
        .. code-block:: python

            import numpy as np
638
            from PIL import Image
639
            from paddle.vision.transforms import RandomVerticalFlip
L
LielinJiang 已提交
640

641
            transform = RandomVerticalFlip()
L
LielinJiang 已提交
642

643
            fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
644 645

            fake_img = transform(fake_img)
646 647
            print(fake_img.size)

L
LielinJiang 已提交
648 649
    """

650
    def __init__(self, prob=0.5, keys=None):
651
        super().__init__(keys)
I
IMMORTAL 已提交
652
        assert 0 <= prob <= 1, "probability must be between 0 and 1"
L
LielinJiang 已提交
653 654
        self.prob = prob

655 656 657
    def _apply_image(self, img):
        if random.random() < self.prob:
            return F.vflip(img)
L
LielinJiang 已提交
658 659 660
        return img


661
class Normalize(BaseTransform):
L
LielinJiang 已提交
662 663 664 665 666 667
    """Normalize the input data with mean and standard deviation.
    Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,
    this transform will normalize each channel of the input data.
    ``output[channel] = (input[channel] - mean[channel]) / std[channel]``

    Args:
668 669
        mean (int|float|list|tuple, optional): Sequence of means for each channel.
        std (int|float|list|tuple, optional): Sequence of standard deviations for each channel.
670
        data_format (str, optional): Data format of img, should be 'HWC' or
671 672 673
            'CHW'. Default: 'CHW'.
        to_rgb (bool, optional): Whether to convert to rgb. Default: False.
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
674 675 676 677 678 679 680 681

    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A normalized array or tensor.

    Returns:
        A callable object of Normalize.

L
LielinJiang 已提交
682
    Examples:
683

L
LielinJiang 已提交
684
        .. code-block:: python
685 686
          :name: code-example
            import paddle
687
            from paddle.vision.transforms import Normalize
L
LielinJiang 已提交
688

689
            normalize = Normalize(mean=[127.5, 127.5, 127.5],
690 691
                                  std=[127.5, 127.5, 127.5],
                                  data_format='HWC')
L
LielinJiang 已提交
692

693
            fake_img = paddle.rand([300,320,3]).numpy() * 255.
L
LielinJiang 已提交
694 695 696

            fake_img = normalize(fake_img)
            print(fake_img.shape)
697 698 699
            # (300, 320, 3)
            print(fake_img.max(), fake_img.min())
            # 0.99999905 -0.999974
700

L
LielinJiang 已提交
701 702
    """

703 704 705
    def __init__(
        self, mean=0.0, std=1.0, data_format='CHW', to_rgb=False, keys=None
    ):
706
        super().__init__(keys)
L
LielinJiang 已提交
707 708 709 710
        if isinstance(mean, numbers.Number):
            mean = [mean, mean, mean]

        if isinstance(std, numbers.Number):
L
LielinJiang 已提交
711
            std = [std, std, std]
L
LielinJiang 已提交
712

713 714 715 716
        self.mean = mean
        self.std = std
        self.data_format = data_format
        self.to_rgb = to_rgb
L
LielinJiang 已提交
717

718
    def _apply_image(self, img):
719 720 721
        return F.normalize(
            img, self.mean, self.std, self.data_format, self.to_rgb
        )
L
LielinJiang 已提交
722 723


724 725
class Transpose(BaseTransform):
    """Transpose input data to a target format.
L
LielinJiang 已提交
726 727
    For example, most transforms use HWC mode image,
    while the Neural Network might use CHW mode input tensor.
728
    output image will be an instance of numpy.ndarray.
L
LielinJiang 已提交
729 730

    Args:
731 732
        order (list|tuple, optional): Target order of input data. Default: (2, 0, 1).
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
733

734 735
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
736
        - output(np.ndarray|Paddle.Tensor): A transposed array or tensor. If input
737 738 739 740 741
            is a PIL.Image, output will be converted to np.ndarray automatically.

    Returns:
        A callable object of Transpose.

L
LielinJiang 已提交
742
    Examples:
743

L
LielinJiang 已提交
744 745 746
        .. code-block:: python

            import numpy as np
747 748
            from PIL import Image
            from paddle.vision.transforms import Transpose
L
LielinJiang 已提交
749

750
            transform = Transpose()
L
LielinJiang 已提交
751

752
            fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
753 754 755

            fake_img = transform(fake_img)
            print(fake_img.shape)
756

L
LielinJiang 已提交
757 758
    """

759
    def __init__(self, order=(2, 0, 1), keys=None):
760
        super().__init__(keys)
761 762 763
        self.order = order

    def _apply_image(self, img):
764 765 766
        if F._is_tensor_image(img):
            return img.transpose(self.order)

767 768
        if F._is_pil_image(img):
            img = np.asarray(img)
L
LielinJiang 已提交
769

770 771
        if len(img.shape) == 2:
            img = img[..., np.newaxis]
772
        return img.transpose(self.order)
L
LielinJiang 已提交
773 774


775
class BrightnessTransform(BaseTransform):
L
LielinJiang 已提交
776 777 778 779
    """Adjust brightness of the image.

    Args:
        value (float): How much to adjust the brightness. Can be any
I
Infinity_lee 已提交
780
            non negative number. 0 gives the original image.
781
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
782

783 784 785 786 787 788 789
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in brghtness.

    Returns:
        A callable object of BrightnessTransform.

L
LielinJiang 已提交
790
    Examples:
791

L
LielinJiang 已提交
792 793 794
        .. code-block:: python

            import numpy as np
795
            from PIL import Image
796
            from paddle.vision.transforms import BrightnessTransform
L
LielinJiang 已提交
797 798 799

            transform = BrightnessTransform(0.4)

800
            fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
801 802

            fake_img = transform(fake_img)
803

L
LielinJiang 已提交
804 805
    """

806
    def __init__(self, value, keys=None):
807
        super().__init__(keys)
808
        self.value = _check_input(value, 'brightness')
L
LielinJiang 已提交
809

810 811
    def _apply_image(self, img):
        if self.value is None:
L
LielinJiang 已提交
812 813
            return img

814 815
        brightness_factor = random.uniform(self.value[0], self.value[1])
        return F.adjust_brightness(img, brightness_factor)
L
LielinJiang 已提交
816 817


818
class ContrastTransform(BaseTransform):
L
LielinJiang 已提交
819 820 821 822
    """Adjust contrast of the image.

    Args:
        value (float): How much to adjust the contrast. Can be any
I
Infinity_lee 已提交
823
            non negative number. 0 gives the original image.
824
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
825

826 827 828 829 830 831 832
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in contrast.

    Returns:
        A callable object of ContrastTransform.

L
LielinJiang 已提交
833
    Examples:
834

L
LielinJiang 已提交
835 836 837
        .. code-block:: python

            import numpy as np
838
            from PIL import Image
839
            from paddle.vision.transforms import ContrastTransform
L
LielinJiang 已提交
840 841 842

            transform = ContrastTransform(0.4)

843
            fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
844 845

            fake_img = transform(fake_img)
846

L
LielinJiang 已提交
847 848
    """

849
    def __init__(self, value, keys=None):
850
        super().__init__(keys)
L
LielinJiang 已提交
851 852
        if value < 0:
            raise ValueError("contrast value should be non-negative")
853
        self.value = _check_input(value, 'contrast')
L
LielinJiang 已提交
854

855 856
    def _apply_image(self, img):
        if self.value is None:
L
LielinJiang 已提交
857 858
            return img

859 860
        contrast_factor = random.uniform(self.value[0], self.value[1])
        return F.adjust_contrast(img, contrast_factor)
L
LielinJiang 已提交
861 862


863
class SaturationTransform(BaseTransform):
L
LielinJiang 已提交
864 865 866 867
    """Adjust saturation of the image.

    Args:
        value (float): How much to adjust the saturation. Can be any
I
Infinity_lee 已提交
868
            non negative number. 0 gives the original image.
869
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
870

871 872 873 874 875 876 877
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in saturation.

    Returns:
        A callable object of SaturationTransform.

L
LielinJiang 已提交
878
    Examples:
879

L
LielinJiang 已提交
880 881 882
        .. code-block:: python

            import numpy as np
883
            from PIL import Image
884
            from paddle.vision.transforms import SaturationTransform
L
LielinJiang 已提交
885 886 887

            transform = SaturationTransform(0.4)

888
            fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))
889

L
LielinJiang 已提交
890
            fake_img = transform(fake_img)
891

L
LielinJiang 已提交
892 893
    """

894
    def __init__(self, value, keys=None):
895
        super().__init__(keys)
896
        self.value = _check_input(value, 'saturation')
L
LielinJiang 已提交
897

898 899
    def _apply_image(self, img):
        if self.value is None:
L
LielinJiang 已提交
900 901
            return img

902 903
        saturation_factor = random.uniform(self.value[0], self.value[1])
        return F.adjust_saturation(img, saturation_factor)
L
LielinJiang 已提交
904

L
LielinJiang 已提交
905

906
class HueTransform(BaseTransform):
L
LielinJiang 已提交
907 908 909 910
    """Adjust hue of the image.

    Args:
        value (float): How much to adjust the hue. Can be any number
I
Infinity_lee 已提交
911
            between 0 and 0.5, 0 gives the original image.
912
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
913

914 915 916 917 918 919 920
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in hue.

    Returns:
        A callable object of HueTransform.

L
LielinJiang 已提交
921
    Examples:
922

L
LielinJiang 已提交
923 924 925
        .. code-block:: python

            import numpy as np
926
            from PIL import Image
927
            from paddle.vision.transforms import HueTransform
L
LielinJiang 已提交
928 929 930

            transform = HueTransform(0.4)

931
            fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
932 933

            fake_img = transform(fake_img)
934

L
LielinJiang 已提交
935 936
    """

937
    def __init__(self, value, keys=None):
938
        super().__init__(keys)
939 940 941
        self.value = _check_input(
            value, 'hue', center=0, bound=(-0.5, 0.5), clip_first_on_zero=False
        )
L
LielinJiang 已提交
942

943 944
    def _apply_image(self, img):
        if self.value is None:
L
LielinJiang 已提交
945 946
            return img

947 948
        hue_factor = random.uniform(self.value[0], self.value[1])
        return F.adjust_hue(img, hue_factor)
L
LielinJiang 已提交
949 950


951
class ColorJitter(BaseTransform):
L
LielinJiang 已提交
952 953 954
    """Randomly change the brightness, contrast, saturation and hue of an image.

    Args:
I
Infinity_lee 已提交
955 956 957 958 959 960 961 962
        brightness (float, optional): How much to jitter brightness.
            Chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. Should be non negative numbers. Default: 0.
        contrast (float, optional): How much to jitter contrast.
            Chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. Should be non negative numbers. Default: 0.
        saturation (float, optional): How much to jitter saturation.
            Chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. Should be non negative numbers. Default: 0.
        hue (float, optional): How much to jitter hue.
            Chosen uniformly from [-hue, hue]. Should have 0<= hue <= 0.5. Default: 0.
963
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
L
LielinJiang 已提交
964

965 966 967 968 969 970 971
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A color jittered image.

    Returns:
        A callable object of ColorJitter.

L
LielinJiang 已提交
972
    Examples:
973

L
LielinJiang 已提交
974 975 976
        .. code-block:: python

            import numpy as np
977
            from PIL import Image
978
            from paddle.vision.transforms import ColorJitter
L
LielinJiang 已提交
979

980
            transform = ColorJitter(0.4, 0.4, 0.4, 0.4)
L
LielinJiang 已提交
981

982
            fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
983 984

            fake_img = transform(fake_img)
985

L
LielinJiang 已提交
986 987
    """

988 989 990
    def __init__(
        self, brightness=0, contrast=0, saturation=0, hue=0, keys=None
    ):
991
        super().__init__(keys)
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        self.brightness = brightness
        self.contrast = contrast
        self.saturation = saturation
        self.hue = hue

    def _get_param(self, brightness, contrast, saturation, hue):
        """Get a randomized transform to be applied on image.

        Arguments are same as that of __init__.

        Returns:
            Transform which randomly adjusts brightness, contrast and
            saturation in a random order.
        """
L
LielinJiang 已提交
1006
        transforms = []
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

        if brightness is not None:
            transforms.append(BrightnessTransform(brightness, self.keys))

        if contrast is not None:
            transforms.append(ContrastTransform(contrast, self.keys))

        if saturation is not None:
            transforms.append(SaturationTransform(saturation, self.keys))

        if hue is not None:
            transforms.append(HueTransform(hue, self.keys))
L
LielinJiang 已提交
1019 1020

        random.shuffle(transforms)
1021
        transform = Compose(transforms)
L
LielinJiang 已提交
1022

1023
        return transform
L
LielinJiang 已提交
1024

1025 1026 1027 1028
    def _apply_image(self, img):
        """
        Args:
            img (PIL Image): Input image.
L
LielinJiang 已提交
1029

1030 1031 1032
        Returns:
            PIL Image: Color jittered image.
        """
1033 1034 1035
        transform = self._get_param(
            self.brightness, self.contrast, self.saturation, self.hue
        )
1036 1037 1038 1039
        return transform(img)


class RandomCrop(BaseTransform):
L
LielinJiang 已提交
1040 1041 1042 1043 1044 1045
    """Crops the given CV Image at a random location.

    Args:
        size (sequence|int): Desired output size of the crop. If size is an
            int instead of sequence like (h, w), a square crop (size, size) is
            made.
1046
        padding (int|sequence, optional): Optional padding on each border
1047
            of the image. If a sequence of length 4 is provided, it is used to pad left,
1048 1049
            top, right, bottom borders respectively. Default: None, without padding.
        pad_if_needed (boolean, optional): It will pad the image if smaller than the
L
LielinJiang 已提交
1050
            desired size to avoid raising an exception. Default: False.
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        fill (float|tuple, optional): Pixel fill value for constant fill. If a tuple of
            length 3, it is used to fill R, G, B channels respectively.
            This value is only used when the padding_mode is constant. Default: 0.
        padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: 'constant'.

            - constant: pads with a constant value, this value is specified with fill

            - edge: pads with the last value on the edge of the image

            - reflect: pads with reflection of image (without repeating the last value on the edge)

                   padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
                   will result in [3, 2, 1, 2, 3, 4, 3, 2]

            - symmetric: pads with reflection of image (repeating the last value on the edge)

                     padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
                     will result in [2, 1, 1, 2, 3, 4, 4, 3]
1069
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
1070

1071
    Shape
1072 1073 1074 1075 1076 1077
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A random cropped image.

    Returns:
        A callable object of RandomCrop.

L
LielinJiang 已提交
1078
    Examples:
1079

L
LielinJiang 已提交
1080
        .. code-block:: python
1081
          :name: code-example1
L
LielinJiang 已提交
1082

1083
            import paddle
1084
            from paddle.vision.transforms import RandomCrop
L
LielinJiang 已提交
1085 1086
            transform = RandomCrop(224)

1087 1088
            fake_img = paddle.randint(0, 255, shape=(3, 324,300), dtype = 'int32')
            print(fake_img.shape) # [3, 324, 300]
L
LielinJiang 已提交
1089

1090 1091
            crop_img = transform(fake_img)
            print(crop_img.shape) # [3, 224, 224]
L
LielinJiang 已提交
1092 1093
    """

1094 1095 1096 1097 1098 1099 1100 1101 1102
    def __init__(
        self,
        size,
        padding=None,
        pad_if_needed=False,
        fill=0,
        padding_mode='constant',
        keys=None,
    ):
1103
        super().__init__(keys)
L
LielinJiang 已提交
1104 1105 1106 1107 1108 1109
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size
        self.padding = padding
        self.pad_if_needed = pad_if_needed
1110 1111
        self.fill = fill
        self.padding_mode = padding_mode
L
LielinJiang 已提交
1112

1113
    def _get_param(self, img, output_size):
L
LielinJiang 已提交
1114 1115 1116
        """Get parameters for ``crop`` for a random crop.

        Args:
1117
            img (PIL Image): Image to be cropped.
L
LielinJiang 已提交
1118 1119 1120 1121 1122
            output_size (tuple): Expected output size of the crop.

        Returns:
            tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
        """
1123
        w, h = _get_image_size(img)
L
LielinJiang 已提交
1124 1125 1126 1127
        th, tw = output_size
        if w == tw and h == th:
            return 0, 0, h, w

1128 1129
        i = random.randint(0, h - th)
        j = random.randint(0, w - tw)
L
LielinJiang 已提交
1130 1131
        return i, j, th, tw

1132
    def _apply_image(self, img):
L
LielinJiang 已提交
1133 1134
        """
        Args:
1135
            img (PIL Image): Image to be cropped.
L
LielinJiang 已提交
1136

1137 1138
        Returns:
            PIL Image: Cropped image.
L
LielinJiang 已提交
1139
        """
1140 1141 1142 1143
        if self.padding is not None:
            img = F.pad(img, self.padding, self.fill, self.padding_mode)

        w, h = _get_image_size(img)
L
LielinJiang 已提交
1144 1145

        # pad the width if needed
1146
        if self.pad_if_needed and w < self.size[1]:
1147 1148 1149
            img = F.pad(
                img, (self.size[1] - w, 0), self.fill, self.padding_mode
            )
L
LielinJiang 已提交
1150
        # pad the height if needed
1151
        if self.pad_if_needed and h < self.size[0]:
1152 1153 1154
            img = F.pad(
                img, (0, self.size[0] - h), self.fill, self.padding_mode
            )
L
LielinJiang 已提交
1155

1156
        i, j, h, w = self._get_param(img, self.size)
L
LielinJiang 已提交
1157

1158
        return F.crop(img, i, j, h, w)
L
LielinJiang 已提交
1159 1160


1161
class Pad(BaseTransform):
L
LielinJiang 已提交
1162 1163 1164 1165
    """Pads the given CV Image on all sides with the given "pad" value.

    Args:
        padding (int|list|tuple): Padding on each border. If a single int is provided this
1166 1167
            is used to pad all borders. If list/tuple of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a list/tuple of length 4 is provided
L
LielinJiang 已提交
1168 1169
            this is the padding for the left, top, right and bottom borders
            respectively.
1170
        fill (int|list|tuple): Pixel fill value for constant fill. Default is 0. If a list/tuple of
L
LielinJiang 已提交
1171 1172 1173
            length 3, it is used to fill R, G, B channels respectively.
            This value is only used when the padding_mode is constant
        padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
1174 1175 1176 1177
            ``constant`` means pads with a constant value, this value is specified with fill.
            ``edge`` means pads with the last value at the edge of the image.
            ``reflect`` means pads with reflection of image (without repeating the last value on the edge)
            padding ``[1, 2, 3, 4]`` with 2 elements on both sides in reflect mode
L
LielinJiang 已提交
1178 1179
            will result in ``[3, 2, 1, 2, 3, 4, 3, 2]``.
            ``symmetric`` menas pads with reflection of image (repeating the last value on the edge)
1180
            padding ``[1, 2, 3, 4]`` with 2 elements on both sides in symmetric mode
L
LielinJiang 已提交
1181
            will result in ``[2, 1, 1, 2, 3, 4, 4, 3]``.
1182
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
1183

1184 1185 1186 1187 1188 1189 1190
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A paded image.

    Returns:
        A callable object of Pad.

L
LielinJiang 已提交
1191
    Examples:
1192

L
LielinJiang 已提交
1193 1194 1195
        .. code-block:: python

            import numpy as np
1196
            from PIL import Image
1197
            from paddle.vision.transforms import Pad
L
LielinJiang 已提交
1198 1199 1200

            transform = Pad(2)

1201
            fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
1202 1203

            fake_img = transform(fake_img)
1204
            print(fake_img.size)
L
LielinJiang 已提交
1205 1206
    """

1207
    def __init__(self, padding, fill=0, padding_mode='constant', keys=None):
L
LielinJiang 已提交
1208 1209 1210
        assert isinstance(padding, (numbers.Number, list, tuple))
        assert isinstance(fill, (numbers.Number, str, list, tuple))
        assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']
1211 1212 1213 1214 1215 1216 1217

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

        if isinstance(padding, Sequence) and len(padding) not in [2, 4]:
L
LielinJiang 已提交
1218
            raise ValueError(
1219 1220 1221
                "Padding must be an int or a 2, or 4 element tuple, not a "
                + "{} element tuple".format(len(padding))
            )
L
LielinJiang 已提交
1222

1223
        super().__init__(keys)
L
LielinJiang 已提交
1224 1225 1226 1227
        self.padding = padding
        self.fill = fill
        self.padding_mode = padding_mode

1228
    def _apply_image(self, img):
L
LielinJiang 已提交
1229 1230
        """
        Args:
1231 1232
            img (PIL Image): Image to be padded.

L
LielinJiang 已提交
1233
        Returns:
1234
            PIL Image: Padded image.
L
LielinJiang 已提交
1235 1236 1237 1238
        """
        return F.pad(img, self.padding, self.fill, self.padding_mode)


1239
def _check_sequence_input(x, name, req_sizes):
1240 1241 1242 1243 1244
    msg = (
        req_sizes[0]
        if len(req_sizes) < 2
        else " or ".join([str(s) for s in req_sizes])
    )
1245 1246 1247 1248 1249 1250
    if not isinstance(x, Sequence):
        raise TypeError(f"{name} should be a sequence of length {msg}.")
    if len(x) not in req_sizes:
        raise ValueError(f"{name} should be sequence of length {msg}.")


1251
def _setup_angle(x, name, req_sizes=(2,)):
1252 1253 1254
    if isinstance(x, numbers.Number):
        if x < 0:
            raise ValueError(
1255 1256
                f"If {name} is a single number, it must be positive."
            )
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
        x = [-x, x]
    else:
        _check_sequence_input(x, name, req_sizes)

    return [float(d) for d in x]


class RandomAffine(BaseTransform):
    """Random affine transformation of the image.

    Args:
        degrees (int|float|tuple): The angle interval of the random rotation.
            If set as a number instead of sequence like (min, max), the range of degrees
            will be (-degrees, +degrees) in clockwise order. If set 0, will not rotate.
        translate (tuple, optional): Maximum absolute fraction for horizontal and vertical translations.
            For example translate=(a, b), then horizontal shift is randomly sampled in the range -img_width * a < dx < img_width * a
1273
            and vertical shift is randomly sampled in the range -img_height * b < dy < img_height * b.
1274
            Default is None, will not translate.
1275
        scale (tuple, optional): Scaling factor interval, e.g (a, b), then scale is randomly sampled from the range a <= scale <= b.
1276 1277
            Default is None, will keep original scale and not scale.
        shear (sequence or number, optional): Range of degrees to shear, ranges from -180 to 180 in clockwise order.
1278 1279
            If set as a number, a shear parallel to the x axis in the range (-shear, +shear) will be applied.
            Else if set as a sequence of 2 values a shear parallel to the x axis in the range (shear[0], shear[1]) will be applied.
1280 1281
            Else if set as a sequence of 4 values, a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
            Default is None, will not apply shear.
1282 1283 1284 1285 1286 1287
        interpolation (str, optional): Interpolation method. If omitted, or if the
            image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST
            according the backend.
            When use pil backend, support method are as following:
            - "nearest": Image.NEAREST,
            - "bilinear": Image.BILINEAR,
1288
            - "bicubic": Image.BICUBIC
1289 1290 1291
            When use cv2 backend, support method are as following:
            - "nearest": cv2.INTER_NEAREST,
            - "bilinear": cv2.INTER_LINEAR,
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
            - "bicubic": cv2.INTER_CUBIC
        fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed
            image. If given a number, the value is used for all bands respectively.
        center (2-tuple, optional): Optional center of rotation, (x, y).
            Origin is the upper left corner.
            Default is the center of the image.
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.

    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): An affined image.

    Returns:
        A callable object of RandomAffine.

    Examples:
1308

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        .. code-block:: python

            import paddle
            from paddle.vision.transforms import RandomAffine

            transform = RandomAffine([-90, 90], translate=[0.2, 0.2], scale=[0.5, 0.5], shear=[-10, 10])

            fake_img = paddle.randn((3, 256, 300)).astype(paddle.float32)

            fake_img = transform(fake_img)
            print(fake_img.shape)
    """

1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    def __init__(
        self,
        degrees,
        translate=None,
        scale=None,
        shear=None,
        interpolation='nearest',
        fill=0,
        center=None,
        keys=None,
    ):
        self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
1334

1335
        super().__init__(keys)
1336 1337 1338 1339
        assert interpolation in ['nearest', 'bilinear', 'bicubic']
        self.interpolation = interpolation

        if translate is not None:
1340
            _check_sequence_input(translate, "translate", req_sizes=(2,))
1341 1342 1343
            for t in translate:
                if not (0.0 <= t <= 1.0):
                    raise ValueError(
1344 1345
                        "translation values should be between 0 and 1"
                    )
1346 1347 1348
        self.translate = translate

        if scale is not None:
1349
            _check_sequence_input(scale, "scale", req_sizes=(2,))
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
            for s in scale:
                if s <= 0:
                    raise ValueError("scale values should be positive")
        self.scale = scale

        if shear is not None:
            self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4))
        else:
            self.shear = shear

        if fill is None:
            fill = 0
        elif not isinstance(fill, (Sequence, numbers.Number)):
            raise TypeError("Fill should be either a sequence or a number.")
        self.fill = fill

        if center is not None:
1367
            _check_sequence_input(center, "center", req_sizes=(2,))
1368 1369
        self.center = center

1370 1371 1372
    def _get_param(
        self, img_size, degrees, translate=None, scale_ranges=None, shears=None
    ):
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
        """Get parameters for affine transformation

        Returns:
            params to be passed to the affine transformation
        """
        angle = random.uniform(degrees[0], degrees[1])

        if translate is not None:
            max_dx = float(translate[0] * img_size[0])
            max_dy = float(translate[1] * img_size[1])
            tx = int(random.uniform(-max_dx, max_dx))
            ty = int(random.uniform(-max_dy, max_dy))
            translations = (tx, ty)
        else:
            translations = (0, 0)

        if scale_ranges is not None:
            scale = random.uniform(scale_ranges[0], scale_ranges[1])
        else:
            scale = 1.0

        shear_x, shear_y = 0.0, 0.0
        if shears is not None:
            shear_x = random.uniform(shears[0], shears[1])
            if len(shears) == 4:
                shear_y = random.uniform(shears[2], shears[3])
        shear = (shear_x, shear_y)

        return angle, translations, scale, shear

    def _apply_image(self, img):
        """
        Args:
            img (PIL.Image|np.array): Image to be affine transformed.

        Returns:
            PIL.Image or np.array: Affine transformed image.
        """

        w, h = _get_image_size(img)
        img_size = [w, h]

1415 1416 1417
        ret = self._get_param(
            img_size, self.degrees, self.translate, self.scale, self.shear
        )
1418

1419 1420 1421 1422 1423 1424 1425
        return F.affine(
            img,
            *ret,
            interpolation=self.interpolation,
            fill=self.fill,
            center=self.center,
        )
1426 1427


1428
class RandomRotation(BaseTransform):
L
LielinJiang 已提交
1429 1430 1431 1432 1433 1434
    """Rotates the image by angle.

    Args:
        degrees (sequence or float or int): Range of degrees to select from.
            If degrees is a number instead of sequence like (min, max), the range of degrees
            will be (-degrees, +degrees) clockwise order.
1435 1436 1437 1438 1439
        interpolation (str, optional): Interpolation method. If omitted, or if the
            image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST
            according the backend. when use pil backend, support method are as following:
            - "nearest": Image.NEAREST,
            - "bilinear": Image.BILINEAR,
1440
            - "bicubic": Image.BICUBIC
1441 1442 1443
            when use cv2 backend, support method are as following:
            - "nearest": cv2.INTER_NEAREST,
            - "bilinear": cv2.INTER_LINEAR,
1444
            - "bicubic": cv2.INTER_CUBIC
L
LielinJiang 已提交
1445 1446 1447 1448 1449 1450 1451
        expand (bool|optional): Optional expansion flag. Default: False.
            If true, expands the output to make it large enough to hold the entire rotated image.
            If false or omitted, make the output image the same size as the input image.
            Note that the expand flag assumes rotation around the center and no translation.
        center (2-tuple|optional): Optional center of rotation.
            Origin is the upper left corner.
            Default is the center of the image.
1452
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
1453

1454 1455 1456 1457 1458 1459 1460
    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A rotated image.

    Returns:
        A callable object of RandomRotation.

L
LielinJiang 已提交
1461
    Examples:
1462

L
LielinJiang 已提交
1463 1464 1465
        .. code-block:: python

            import numpy as np
1466 1467
            from PIL import Image
            from paddle.vision.transforms import RandomRotation
L
LielinJiang 已提交
1468

1469
            transform = RandomRotation(90)
L
LielinJiang 已提交
1470

1471
            fake_img = Image.fromarray((np.random.rand(200, 150, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
1472 1473

            fake_img = transform(fake_img)
1474
            print(fake_img.size)
L
LielinJiang 已提交
1475 1476
    """

1477 1478 1479 1480 1481 1482 1483 1484 1485
    def __init__(
        self,
        degrees,
        interpolation='nearest',
        expand=False,
        center=None,
        fill=0,
        keys=None,
    ):
L
LielinJiang 已提交
1486 1487 1488
        if isinstance(degrees, numbers.Number):
            if degrees < 0:
                raise ValueError(
1489 1490
                    "If degrees is a single number, it must be positive."
                )
L
LielinJiang 已提交
1491 1492 1493 1494
            self.degrees = (-degrees, degrees)
        else:
            if len(degrees) != 2:
                raise ValueError(
1495 1496
                    "If degrees is a sequence, it must be of len 2."
                )
L
LielinJiang 已提交
1497 1498
            self.degrees = degrees

1499
        super().__init__(keys)
1500
        self.interpolation = interpolation
L
LielinJiang 已提交
1501 1502
        self.expand = expand
        self.center = center
1503
        self.fill = fill
L
LielinJiang 已提交
1504

1505
    def _get_param(self, degrees):
L
LielinJiang 已提交
1506 1507 1508 1509
        angle = random.uniform(degrees[0], degrees[1])

        return angle

1510
    def _apply_image(self, img):
L
LielinJiang 已提交
1511
        """
1512 1513 1514
        Args:
            img (PIL.Image|np.array): Image to be rotated.

L
LielinJiang 已提交
1515
        Returns:
1516
            PIL.Image or np.array: Rotated image.
L
LielinJiang 已提交
1517 1518
        """

1519
        angle = self._get_param(self.degrees)
L
LielinJiang 已提交
1520

1521 1522 1523
        return F.rotate(
            img, angle, self.interpolation, self.expand, self.center, self.fill
        )
L
LielinJiang 已提交
1524 1525


1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
class RandomPerspective(BaseTransform):
    """Random perspective transformation with a given probability.

    Args:
        prob (float, optional): Probability of using transformation, ranges from
            0 to 1, default is 0.5.
        distortion_scale (float, optional): Degree of distortion, ranges from
            0 to 1, default is 0.5.
        interpolation (str, optional): Interpolation method. If omitted, or if
            the image has only one channel, it is set to PIL.Image.NEAREST or
            cv2.INTER_NEAREST.
1537 1538 1539
            When use pil backend, support method are as following:
            - "nearest": Image.NEAREST,
            - "bilinear": Image.BILINEAR,
1540
            - "bicubic": Image.BICUBIC
1541 1542 1543
            When use cv2 backend, support method are as following:
            - "nearest": cv2.INTER_NEAREST,
            - "bilinear": cv2.INTER_LINEAR,
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
            - "bicubic": cv2.INTER_CUBIC
        fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed
            image. If given a number, the value is used for all bands respectively.
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.

    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
        - output(PIL.Image|np.ndarray|Paddle.Tensor): A perspectived image.

    Returns:
        A callable object of RandomPerspective.

    Examples:
1557

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
        .. code-block:: python

            import paddle
            from paddle.vision.transforms import RandomPerspective

            transform = RandomPerspective(prob=1.0, distortion_scale=0.9)

            fake_img = paddle.randn((3, 200, 150)).astype(paddle.float32)

            fake_img = transform(fake_img)
            print(fake_img.shape)
    """

1571 1572 1573 1574 1575 1576 1577 1578
    def __init__(
        self,
        prob=0.5,
        distortion_scale=0.5,
        interpolation='nearest',
        fill=0,
        keys=None,
    ):
1579
        super().__init__(keys)
1580
        assert 0 <= prob <= 1, "probability must be between 0 and 1"
1581 1582 1583
        assert (
            0 <= distortion_scale <= 1
        ), "distortion_scale must be between 0 and 1"
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
        assert interpolation in ['nearest', 'bilinear', 'bicubic']
        assert isinstance(fill, (numbers.Number, str, list, tuple))

        self.prob = prob
        self.distortion_scale = distortion_scale
        self.interpolation = interpolation
        self.fill = fill

    def get_params(self, width, height, distortion_scale):
        """
        Returns:
            startpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the original image,
            endpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the transformed image.
        """
        half_height = height // 2
        half_width = width // 2
        topleft = [
1601 1602
            int(random.uniform(0, int(distortion_scale * half_width) + 1)),
            int(random.uniform(0, int(distortion_scale * half_height) + 1)),
1603 1604 1605
        ]
        topright = [
            int(
1606 1607 1608 1609 1610
                random.uniform(
                    width - int(distortion_scale * half_width) - 1, width
                )
            ),
            int(random.uniform(0, int(distortion_scale * half_height) + 1)),
1611 1612 1613
        ]
        botright = [
            int(
1614 1615 1616 1617
                random.uniform(
                    width - int(distortion_scale * half_width) - 1, width
                )
            ),
1618
            int(
1619 1620 1621 1622
                random.uniform(
                    height - int(distortion_scale * half_height) - 1, height
                )
            ),
1623 1624
        ]
        botleft = [
1625
            int(random.uniform(0, int(distortion_scale * half_width) + 1)),
1626
            int(
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
                random.uniform(
                    height - int(distortion_scale * half_height) - 1, height
                )
            ),
        ]
        startpoints = [
            [0, 0],
            [width - 1, 0],
            [width - 1, height - 1],
            [0, height - 1],
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
        ]
        endpoints = [topleft, topright, botright, botleft]

        return startpoints, endpoints

    def _apply_image(self, img):
        """
        Args:
            img (PIL.Image|np.array|paddle.Tensor): Image to be Perspectively transformed.

        Returns:
            PIL.Image|np.array|paddle.Tensor: Perspectively transformed image.
        """

        width, height = _get_image_size(img)

        if random.random() < self.prob:
1654 1655 1656 1657 1658 1659
            startpoints, endpoints = self.get_params(
                width, height, self.distortion_scale
            )
            return F.perspective(
                img, startpoints, endpoints, self.interpolation, self.fill
            )
1660 1661 1662
        return img


1663
class Grayscale(BaseTransform):
L
LielinJiang 已提交
1664 1665 1666
    """Converts image to grayscale.

    Args:
I
Infinity_lee 已提交
1667
        num_output_channels (int, optional): (1 or 3) number of channels desired for output image. Default: 1.
1668
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
1669 1670 1671

    Shape:
        - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).
1672
        - output(PIL.Image|np.ndarray|Paddle.Tensor): Grayscale version of the input image.
1673 1674 1675
            - If output_channels == 1 : returned image is single channel
            - If output_channels == 3 : returned image is 3 channel with r == g == b

L
LielinJiang 已提交
1676
    Returns:
1677
        A callable object of Grayscale.
L
LielinJiang 已提交
1678 1679

    Examples:
1680

L
LielinJiang 已提交
1681 1682 1683
        .. code-block:: python

            import numpy as np
1684
            from PIL import Image
1685
            from paddle.vision.transforms import Grayscale
L
LielinJiang 已提交
1686 1687 1688

            transform = Grayscale()

1689
            fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))
L
LielinJiang 已提交
1690 1691

            fake_img = transform(fake_img)
1692
            print(np.array(fake_img).shape)
L
LielinJiang 已提交
1693 1694
    """

1695
    def __init__(self, num_output_channels=1, keys=None):
1696
        super().__init__(keys)
1697
        self.num_output_channels = num_output_channels
L
LielinJiang 已提交
1698

1699
    def _apply_image(self, img):
L
LielinJiang 已提交
1700 1701
        """
        Args:
1702 1703
            img (PIL Image): Image to be converted to grayscale.

L
LielinJiang 已提交
1704
        Returns:
1705
            PIL Image: Randomly grayscaled image.
L
LielinJiang 已提交
1706
        """
1707
        return F.to_grayscale(img, self.num_output_channels)
1708 1709 1710 1711 1712 1713 1714


class RandomErasing(BaseTransform):
    """Erase the pixels in a rectangle region selected randomly.

    Args:
        prob (float, optional): Probability of the input data being erased. Default: 0.5.
1715
        scale (sequence, optional): The proportional range of the erased area to the input image.
1716 1717 1718
                                    Default: (0.02, 0.33).
        ratio (sequence, optional): Aspect ratio range of the erased area. Default: (0.3, 3.3).
        value (int|float|sequence|str, optional): The value each pixel in erased area will be replaced with.
1719 1720 1721
                               If value is a single number, all pixels will be erased with this value.
                               If value is a sequence with length 3, the R, G, B channels will be ereased
                               respectively. If value is set to "random", each pixel will be erased with
1722 1723 1724
                               random values. Default: 0.
        inplace (bool, optional): Whether this transform is inplace. Default: False.
        keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.
1725

1726
    Shape:
1727
        - img(paddle.Tensor | np.array | PIL.Image): The input image. For Tensor input, the shape should be (C, H, W).
1728 1729 1730 1731 1732 1733 1734
                 For np.array input, the shape should be (H, W, C).
        - output(paddle.Tensor | np.array | PIL.Image): A random erased image.

    Returns:
        A callable object of RandomErasing.

    Examples:
1735

1736 1737 1738
        .. code-block:: python

            import paddle
1739

1740 1741
            fake_img = paddle.randn((3, 10, 10)).astype(paddle.float32)
            transform = paddle.vision.transforms.RandomErasing()
J
JYChen 已提交
1742 1743 1744
            result = transform(fake_img)

            print(result)
1745 1746
    """

1747 1748 1749 1750 1751 1752 1753 1754 1755
    def __init__(
        self,
        prob=0.5,
        scale=(0.02, 0.33),
        ratio=(0.3, 3.3),
        value=0,
        inplace=False,
        keys=None,
    ):
1756
        super().__init__(keys)
1757
        assert isinstance(
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
            scale, (tuple, list)
        ), "scale should be a tuple or list"
        assert (
            scale[0] >= 0 and scale[1] <= 1 and scale[0] <= scale[1]
        ), "scale should be of kind (min, max) and in range [0, 1]"
        assert isinstance(
            ratio, (tuple, list)
        ), "ratio should be a tuple or list"
        assert (
            ratio[0] >= 0 and ratio[0] <= ratio[1]
        ), "ratio should be of kind (min, max)"
        assert (
            prob >= 0 and prob <= 1
        ), "The probability should be in range [0, 1]"
        assert isinstance(
            value, (numbers.Number, str, tuple, list)
        ), "value should be a number, tuple, list or str"
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
        if isinstance(value, str) and value != "random":
            raise ValueError("value must be 'random' when type is str")

        self.prob = prob
        self.scale = scale
        self.ratio = ratio
        self.value = value
        self.inplace = inplace

    def _get_param(self, img, scale, ratio, value):
        """Get parameters for ``erase`` for a random erasing.

        Args:
            img (paddle.Tensor | np.array | PIL.Image): Image to be erased.
1789
            scale (sequence, optional): The proportional range of the erased area to the input image.
1790 1791
            ratio (sequence, optional): Aspect ratio range of the erased area.
            value (sequence | None): The value each pixel in erased area will be replaced with.
1792
                               If value is a sequence with length 3, the R, G, B channels will be ereased
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
                               respectively. If value is None, each pixel will be erased with random values.

        Returns:
            tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erase.
        """
        if F._is_pil_image(img):
            shape = np.asarray(img).astype(np.uint8).shape
            h, w, c = shape[-3], shape[-2], shape[-1]
        elif F._is_numpy_image(img):
            h, w, c = img.shape[-3], img.shape[-2], img.shape[-1]
        elif F._is_tensor_image(img):
            c, h, w = img.shape[-3], img.shape[-2], img.shape[-1]

        img_area = h * w
        log_ratio = np.log(ratio)
        for _ in range(10):
            erase_area = np.random.uniform(*scale) * img_area
            aspect_ratio = np.exp(np.random.uniform(*log_ratio))
            erase_h = int(round(np.sqrt(erase_area * aspect_ratio)))
            erase_w = int(round(np.sqrt(erase_area / aspect_ratio)))
            if erase_h >= h or erase_w >= w:
                continue
            if F._is_tensor_image(img):
                if value is None:
1817
                    v = paddle.normal(shape=[c, erase_h, erase_w]).astype(
1818 1819
                        img.dtype
                    )
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
                else:
                    v = paddle.to_tensor(value, dtype=img.dtype)[:, None, None]
            else:
                if value is None:
                    v = np.random.normal(size=[erase_h, erase_w, c]) * 255
                else:
                    v = np.array(value)[None, None, :]
            top = np.random.randint(0, h - erase_h + 1)
            left = np.random.randint(0, w - erase_w + 1)

            return top, left, erase_h, erase_w, v

        return 0, 0, h, w, img

    def _apply_image(self, img):
        """
        Args:
            img (paddle.Tensor | np.array | PIL.Image): Image to be Erased.

        Returns:
            output (paddle.Tensor np.array | PIL.Image): A random erased image.
        """

        if random.random() < self.prob:
            if isinstance(self.value, numbers.Number):
                value = [self.value]
            elif isinstance(self.value, str):
                value = None
            else:
                value = self.value
            if value is not None and not (len(value) == 1 or len(value) == 3):
                raise ValueError(
                    "Value should be a single number or a sequence with length equals to image's channel."
                )
1854
            top, left, erase_h, erase_w, v = self._get_param(
1855 1856
                img, self.scale, self.ratio, value
            )
1857 1858
            return F.erase(img, top, left, erase_h, erase_w, v, self.inplace)
        return img