functional.py 22.2 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

15 16
from __future__ import division

L
LielinJiang 已提交
17
import sys
L
LielinJiang 已提交
18 19
import math
import numbers
20 21
import warnings
import collections
L
LielinJiang 已提交
22

23 24 25 26
import numpy as np
from PIL import Image
from numpy import sin, cos, tan
import paddle
L
LielinJiang 已提交
27

28 29 30
from . import functional_pil as F_pil
from . import functional_cv2 as F_cv2
from . import functional_tensor as F_t
L
LielinJiang 已提交
31

32 33 34
__all__ = [
    'to_tensor', 'hflip', 'vflip', 'resize', 'pad', 'rotate', 'to_grayscale',
    'crop', 'center_crop', 'adjust_brightness', 'adjust_contrast', 'adjust_hue',
L
LielinJiang 已提交
35
    'normalize'
36
]
L
LielinJiang 已提交
37

L
LielinJiang 已提交
38

39 40
def _is_pil_image(img):
    return isinstance(img, Image.Image)
L
LielinJiang 已提交
41 42


43 44
def _is_tensor_image(img):
    return isinstance(img, paddle.Tensor)
L
LielinJiang 已提交
45

46 47 48 49 50 51 52 53 54

def _is_numpy_image(img):
    return isinstance(img, np.ndarray) and (img.ndim in {2, 3})


def to_tensor(pic, data_format='CHW'):
    """Converts a ``PIL.Image`` or ``numpy.ndarray`` to paddle.Tensor.

    See ``ToTensor`` for more details.
L
LielinJiang 已提交
55 56

    Args:
57
        pic (PIL.Image|np.ndarray): Image to be converted to tensor.
L
LielinJiang 已提交
58
        data_format (str, optional): Data format of output tensor, should be 'HWC' or 
59 60 61
            'CHW'. Default: 'CHW'.

    Returns:
L
LielinJiang 已提交
62
        Tensor: Converted image. Data type is same as input img.
L
LielinJiang 已提交
63 64 65 66 67

    Examples:
        .. code-block:: python

            import numpy as np
68
            from PIL import Image
69
            from paddle.vision.transforms import functional as F
L
LielinJiang 已提交
70

71
            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')
L
LielinJiang 已提交
72

73
            fake_img = Image.fromarray(fake_img)
L
LielinJiang 已提交
74

75 76
            tensor = F.to_tensor(fake_img)
            print(tensor.shape)
L
LielinJiang 已提交
77 78

    """
79 80 81 82 83
    if not (_is_pil_image(pic) or _is_numpy_image(pic) or
            _is_tensor_image(pic)):
        raise TypeError(
            'pic should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
            format(type(pic)))
84 85 86

    if _is_pil_image(pic):
        return F_pil.to_tensor(pic, data_format)
87
    elif _is_numpy_image(pic):
88
        return F_cv2.to_tensor(pic, data_format)
89 90
    else:
        return pic if data_format.lower() == 'chw' else pic.transpose((1, 2, 0))
L
LielinJiang 已提交
91 92


93
def resize(img, size, interpolation='bilinear'):
L
LielinJiang 已提交
94
    """
95
    Resizes the image to given size
L
LielinJiang 已提交
96 97

    Args:
98
        input (PIL.Image|np.ndarray): Image to be resized.
L
LielinJiang 已提交
99
        size (int|list|tuple): Target size of input data, with (height, width) shape.
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        interpolation (int|str, optional): Interpolation method. when use pil backend, 
            support method are as following: 
            - "nearest": Image.NEAREST, 
            - "bilinear": Image.BILINEAR, 
            - "bicubic": Image.BICUBIC, 
            - "box": Image.BOX, 
            - "lanczos": Image.LANCZOS, 
            - "hamming": Image.HAMMING
            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, 
            - "lanczos": cv2.INTER_LANCZOS4

    Returns:
        PIL.Image or np.array: Resized image.
L
LielinJiang 已提交
117 118 119 120 121

    Examples:
        .. code-block:: python

            import numpy as np
122
            from PIL import Image
123
            from paddle.vision.transforms import functional as F
L
LielinJiang 已提交
124

125
            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')
L
LielinJiang 已提交
126

127
            fake_img = Image.fromarray(fake_img)
L
LielinJiang 已提交
128

129 130 131 132 133
            converted_img = F.resize(fake_img, 224)
            print(converted_img.size)

            converted_img = F.resize(fake_img, (200, 150))
            print(converted_img.size)
L
LielinJiang 已提交
134
    """
135 136
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
137
        raise TypeError(
138
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
139 140 141 142
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.resize(img, size, interpolation)
143 144
    elif _is_tensor_image(img):
        return F_t.resize(img, size, interpolation)
L
LielinJiang 已提交
145
    else:
146
        return F_cv2.resize(img, size, interpolation)
L
LielinJiang 已提交
147 148


149 150 151
def pad(img, padding, fill=0, padding_mode='constant'):
    """
    Pads the given PIL.Image or numpy.array on all sides with specified padding mode and fill value.
L
LielinJiang 已提交
152 153

    Args:
154 155
        img (PIL.Image|np.array): Image to be padded.
        padding (int|list|tuple): Padding on each border. If a single int is provided this
156 157
            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 已提交
158 159
            this is the padding for the left, top, right and bottom borders
            respectively.
160
        fill (float, optional): Pixel fill value for constant fill. If a tuple of
L
LielinJiang 已提交
161
            length 3, it is used to fill R, G, B channels respectively.
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
            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]
L
LielinJiang 已提交
178 179

    Returns:
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        PIL.Image or np.array: Padded image.

    Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            padded_img = F.pad(fake_img, padding=1)
            print(padded_img.size)

            padded_img = F.pad(fake_img, padding=(2, 1))
            print(padded_img.size)
    """
199 200
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
201
        raise TypeError(
202
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
203 204 205 206
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.pad(img, padding, fill, padding_mode)
207 208
    elif _is_tensor_image(img):
        return F_t.pad(img, padding, fill, padding_mode)
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    else:
        return F_cv2.pad(img, padding, fill, padding_mode)


def crop(img, top, left, height, width):
    """Crops the given Image.

    Args:
        img (PIL.Image|np.array): Image to be cropped. (0,0) denotes the top left 
            corner of the image.
        top (int): Vertical component of the top left corner of the crop box.
        left (int): Horizontal component of the top left corner of the crop box.
        height (int): Height of the crop box.
        width (int): Width of the crop box.

    Returns:
        PIL.Image or np.array: Cropped image.
L
LielinJiang 已提交
226 227 228 229 230

    Examples:
        .. code-block:: python

            import numpy as np
231 232
            from PIL import Image
            from paddle.vision.transforms import functional as F
L
LielinJiang 已提交
233

234
            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')
L
LielinJiang 已提交
235

236
            fake_img = Image.fromarray(fake_img)
L
LielinJiang 已提交
237

238 239
            cropped_img = F.crop(fake_img, 56, 150, 200, 100)
            print(cropped_img.size)
L
LielinJiang 已提交
240 241

    """
242 243
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
244
        raise TypeError(
245
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
246 247 248 249
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.crop(img, top, left, height, width)
250 251
    elif _is_tensor_image(img):
        return F_t.crop(img, top, left, height, width)
252 253 254 255 256 257 258 259 260 261 262 263 264 265
    else:
        return F_cv2.crop(img, top, left, height, width)


def center_crop(img, output_size):
    """Crops the given Image and resize it to desired size.

        Args:
            img (PIL.Image|np.array): Image to be cropped. (0,0) denotes the top left corner of the image.
            output_size (sequence or int): (height, width) of the crop box. If int,
                it is used for both directions
        
        Returns:
            PIL.Image or np.array: Cropped image.
L
LielinJiang 已提交
266

267 268 269 270 271 272 273 274 275 276 277 278 279 280
        Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            cropped_img = F.center_crop(fake_img, (150, 100))
            print(cropped_img.size)
        """
281 282
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
283
        raise TypeError(
284
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
285 286 287 288
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.center_crop(img, output_size)
289 290
    elif _is_tensor_image(img):
        return F_t.center_crop(img, output_size)
291 292 293 294
    else:
        return F_cv2.center_crop(img, output_size)


L
LielinJiang 已提交
295
def hflip(img):
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    """Horizontally flips the given Image or np.array.

    Args:
        img (PIL.Image|np.array): Image to be flipped.

    Returns:
        PIL.Image or np.array:  Horizontall flipped image.

    Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            flpped_img = F.hflip(fake_img)
            print(flpped_img.size)

    """
319 320
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
321
        raise TypeError(
322
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
323 324 325 326
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.hflip(img)
327 328
    elif _is_tensor_image(img):
        return F_t.hflip(img)
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    else:
        return F_cv2.hflip(img)


def vflip(img):
    """Vertically flips the given Image or np.array.

    Args:
        img (PIL.Image|np.array): Image to be flipped.

    Returns:
        PIL.Image or np.array:  Vertically flipped image.

    Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            flpped_img = F.vflip(fake_img)
            print(flpped_img.size)

    """
357 358
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
359
        raise TypeError(
360
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
361 362 363 364
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.vflip(img)
365 366
    elif _is_tensor_image(img):
        return F_t.vflip(img)
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    else:
        return F_cv2.vflip(img)


def adjust_brightness(img, brightness_factor):
    """Adjusts brightness of an Image.

    Args:
        img (PIL.Image|np.array): Image to be adjusted.
        brightness_factor (float): How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL.Image or np.array: Brightness adjusted image.

    Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            converted_img = F.adjust_brightness(fake_img, 0.4)
            print(converted_img.size)
    """
    if not (_is_pil_image(img) or _is_numpy_image(img)):
        raise TypeError(
            'img should be PIL Image or ndarray with dim=[2 or 3]. Got {}'.
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.adjust_brightness(img, brightness_factor)
    else:
        return F_cv2.adjust_brightness(img, brightness_factor)


def adjust_contrast(img, contrast_factor):
    """Adjusts contrast of an Image.

    Args:
        img (PIL.Image|np.array): Image to be adjusted.
        contrast_factor (float): How much to adjust the contrast. Can be any
            non negative number. 0 gives a solid gray image, 1 gives the
            original image while 2 increases the contrast by a factor of 2.

    Returns:
        PIL.Image or np.array: Contrast adjusted image.

    Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            converted_img = F.adjust_contrast(fake_img, 0.4)
            print(converted_img.size)
    """
    if not (_is_pil_image(img) or _is_numpy_image(img)):
        raise TypeError(
            'img should be PIL Image or ndarray with dim=[2 or 3]. Got {}'.
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.adjust_contrast(img, contrast_factor)
    else:
        return F_cv2.adjust_contrast(img, contrast_factor)


def adjust_saturation(img, saturation_factor):
    """Adjusts color saturation of an image.

    Args:
        img (PIL.Image|np.array): Image to be adjusted.
        saturation_factor (float):  How much to adjust the saturation. 0 will
            give a black and white image, 1 will give the original image while
            2 will enhance the saturation by a factor of 2.

    Returns:
        PIL.Image or np.array: Saturation adjusted image.

    Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            converted_img = F.adjust_saturation(fake_img, 0.4)
            print(converted_img.size)

    """
    if not (_is_pil_image(img) or _is_numpy_image(img)):
        raise TypeError(
            'img should be PIL Image or ndarray with dim=[2 or 3]. Got {}'.
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.adjust_saturation(img, saturation_factor)
    else:
        return F_cv2.adjust_saturation(img, saturation_factor)


def adjust_hue(img, hue_factor):
    """Adjusts hue of an image.

    The image hue is adjusted by converting the image to HSV and
    cyclically shifting the intensities in the hue channel (H).
    The image is then converted back to original image mode.

    `hue_factor` is the amount of shift in H channel and must be in the
    interval `[-0.5, 0.5]`.

    Args:
        img (PIL.Image|np.array): Image to be adjusted.
        hue_factor (float):  How much to shift the hue channel. Should be in
            [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
            HSV space in positive and negative direction respectively.
            0 means no shift. Therefore, both -0.5 and 0.5 will give an image
            with complementary colors while 0 gives the original image.

    Returns:
        PIL.Image or np.array: Hue adjusted image.

    Examples:
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            converted_img = F.adjust_hue(fake_img, 0.4)
            print(converted_img.size)

    """
    if not (_is_pil_image(img) or _is_numpy_image(img)):
        raise TypeError(
            'img should be PIL Image or ndarray with dim=[2 or 3]. Got {}'.
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.adjust_hue(img, hue_factor)
    else:
        return F_cv2.adjust_hue(img, hue_factor)


530 531 532 533 534 535
def rotate(img,
           angle,
           interpolation="nearest",
           expand=False,
           center=None,
           fill=0):
L
LielinJiang 已提交
536 537
    """Rotates the image by angle.

538

L
LielinJiang 已提交
539
    Args:
540 541
        img (PIL.Image|np.array): Image to be rotated.
        angle (float or int): In degrees degrees counter clockwise order.
542
        interpolation (str, optional): Interpolation method. If omitted, or if the 
543 544 545 546 547 548 549 550 551 552
            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, 
            - "bicubic": Image.BICUBIC
            when use cv2 backend, support method are as following: 
            - "nearest": cv2.INTER_NEAREST, 
            - "bilinear": cv2.INTER_LINEAR, 
            - "bicubic": cv2.INTER_CUBIC
        expand (bool, optional): Optional expansion flag.
L
LielinJiang 已提交
553 554 555
            If true, expands the output image 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.
556
        center (2-list|2-tuple, optional): Optional center of rotation.
L
LielinJiang 已提交
557 558
            Origin is the upper left corner.
            Default is the center of the image.
559
        fill (3-list|3-tuple or int): RGB pixel fill value for area outside the rotated image.
560 561
            If int, it is used for all channels respectively.

L
LielinJiang 已提交
562 563

    Returns:
564
        PIL.Image or np.array: Rotated image.
L
LielinJiang 已提交
565 566 567 568 569

    Examples:
        .. code-block:: python

            import numpy as np
570 571 572 573
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')
L
LielinJiang 已提交
574

575
            fake_img = Image.fromarray(fake_img)
L
LielinJiang 已提交
576

577 578
            rotated_img = F.rotate(fake_img, 90)
            print(rotated_img.size)
L
LielinJiang 已提交
579 580

    """
581 582
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
583
        raise TypeError(
584
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
585 586
            format(type(img)))

587 588 589 590 591
    if isinstance(center, list):
        center = tuple(center)
    if isinstance(fill, list):
        fill = tuple(fill)

592
    if _is_pil_image(img):
593
        return F_pil.rotate(img, angle, interpolation, expand, center, fill)
594 595
    elif _is_tensor_image(img):
        return F_t.rotate(img, angle, interpolation, expand, center, fill)
L
LielinJiang 已提交
596
    else:
597
        return F_cv2.rotate(img, angle, interpolation, expand, center, fill)
L
LielinJiang 已提交
598 599 600 601 602 603


def to_grayscale(img, num_output_channels=1):
    """Converts image to grayscale version of image.

    Args:
604
        img (PIL.Image|np.array): Image to be converted to grayscale.
L
LielinJiang 已提交
605 606

    Returns:
607 608 609 610
        PIL.Image or np.array: Grayscale version of the image.
            if num_output_channels = 1 : returned image is single channel

            if num_output_channels = 3 : returned image is 3 channel with r = g = b
L
LielinJiang 已提交
611 612
    
    Examples:
613 614 615 616 617 618 619 620 621 622 623 624 625 626
        .. code-block:: python

            import numpy as np
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)

            gray_img = F.to_grayscale(fake_img)
            print(gray_img.size)

    """
627 628
    if not (_is_pil_image(img) or _is_numpy_image(img) or
            _is_tensor_image(img)):
629
        raise TypeError(
630
            'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
631 632 633 634
            format(type(img)))

    if _is_pil_image(img):
        return F_pil.to_grayscale(img, num_output_channels)
635 636
    elif _is_tensor_image(img):
        return F_t.to_grayscale(img, num_output_channels)
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    else:
        return F_cv2.to_grayscale(img, num_output_channels)


def normalize(img, mean, std, data_format='CHW', to_rgb=False):
    """Normalizes a tensor or image with mean and standard deviation.

    Args:
        img (PIL.Image|np.array|paddle.Tensor): input data to be normalized.
        mean (list|tuple): Sequence of means for each channel.
        std (list|tuple): Sequence of standard deviations for each channel.
        data_format (str, optional): Data format of input img, should be 'HWC' or 
            'CHW'. Default: 'CHW'.
        to_rgb (bool, optional): Whether to convert to rgb. If input is tensor, 
            this option will be igored. Default: False.

    Returns:
L
LielinJiang 已提交
654
        np.ndarray or Tensor: Normalized mage. Data format is same as input img.
L
LielinJiang 已提交
655
    
656
    Examples:
L
LielinJiang 已提交
657 658 659
        .. code-block:: python

            import numpy as np
660 661 662 663 664 665
            from PIL import Image
            from paddle.vision.transforms import functional as F

            fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')

            fake_img = Image.fromarray(fake_img)
L
LielinJiang 已提交
666

667 668
            mean = [127.5, 127.5, 127.5]
            std = [127.5, 127.5, 127.5]
L
LielinJiang 已提交
669

670 671
            normalized_img = F.normalize(fake_img, mean, std, data_format='HWC')
            print(normalized_img.max(), normalized_img.min())
L
LielinJiang 已提交
672 673 674

    """

675 676
    if _is_tensor_image(img):
        return F_t.normalize(img, mean, std, data_format)
L
LielinJiang 已提交
677
    else:
678 679
        if _is_pil_image(img):
            img = np.array(img).astype(np.float32)
L
LielinJiang 已提交
680

681
        return F_cv2.normalize(img, mean, std, data_format, to_rgb)