.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/plot_transforms.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_plot_transforms.py: ========================== Illustration of transforms ========================== This example illustrates the various transforms available in :ref:`the torchvision.transforms module `. .. GENERATED FROM PYTHON SOURCE LINES 9-51 .. code-block:: default from PIL import Image from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch import torchvision.transforms as T plt.rcParams["savefig.bbox"] = 'tight' orig_img = Image.open(Path('assets') / 'astronaut.jpg') # if you change the seed, make sure that the randomly-applied transforms # properly show that the image can be both transformed and *not* transformed! torch.manual_seed(0) def plot(imgs, with_orig=True, row_title=None, **imshow_kwargs): if not isinstance(imgs[0], list): # Make a 2d grid even if there's just 1 row imgs = [imgs] num_rows = len(imgs) num_cols = len(imgs[0]) + with_orig fig, axs = plt.subplots(nrows=num_rows, ncols=num_cols, squeeze=False) for row_idx, row in enumerate(imgs): row = [orig_img] + row if with_orig else row for col_idx, img in enumerate(row): ax = axs[row_idx, col_idx] ax.imshow(np.asarray(img), **imshow_kwargs) ax.set(xticklabels=[], yticklabels=[], xticks=[], yticks=[]) if with_orig: axs[0, 0].set(title='Original image') axs[0, 0].title.set_size(8) if row_title is not None: for row_idx in range(num_rows): axs[row_idx, 0].set(ylabel=row_title[row_idx]) plt.tight_layout() .. GENERATED FROM PYTHON SOURCE LINES 52-57 Pad --- The :class:`~torchvision.transforms.Pad` transform (see also :func:`~torchvision.transforms.functional.pad`) fills image borders with some pixel values. .. GENERATED FROM PYTHON SOURCE LINES 57-60 .. code-block:: default padded_imgs = [T.Pad(padding=padding)(orig_img) for padding in (3, 10, 30, 50)] plot(padded_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_001.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 61-66 Resize ------ The :class:`~torchvision.transforms.Resize` transform (see also :func:`~torchvision.transforms.functional.resize`) resizes an image. .. GENERATED FROM PYTHON SOURCE LINES 66-69 .. code-block:: default resized_imgs = [T.Resize(size=size)(orig_img) for size in (30, 50, 100, orig_img.size)] plot(resized_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_002.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 70-75 CenterCrop ---------- The :class:`~torchvision.transforms.CenterCrop` transform (see also :func:`~torchvision.transforms.functional.center_crop`) crops the given image at the center. .. GENERATED FROM PYTHON SOURCE LINES 75-78 .. code-block:: default center_crops = [T.CenterCrop(size=size)(orig_img) for size in (30, 50, 100, orig_img.size)] plot(center_crops) .. image:: /auto_examples/images/sphx_glr_plot_transforms_003.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 79-84 FiveCrop -------- The :class:`~torchvision.transforms.FiveCrop` transform (see also :func:`~torchvision.transforms.functional.five_crop`) crops the given image into four corners and the central crop. .. GENERATED FROM PYTHON SOURCE LINES 84-87 .. code-block:: default (top_left, top_right, bottom_left, bottom_right, center) = T.FiveCrop(size=(100, 100))(orig_img) plot([top_left, top_right, bottom_left, bottom_right, center]) .. image:: /auto_examples/images/sphx_glr_plot_transforms_004.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 88-93 Grayscale --------- The :class:`~torchvision.transforms.Grayscale` transform (see also :func:`~torchvision.transforms.functional.to_grayscale`) converts an image to grayscale .. GENERATED FROM PYTHON SOURCE LINES 93-96 .. code-block:: default gray_img = T.Grayscale()(orig_img) plot([gray_img], cmap='gray') .. image:: /auto_examples/images/sphx_glr_plot_transforms_005.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 97-106 Random transforms ----------------- The following transforms are random, which means that the same transfomer instance will produce different result each time it transforms a given image. ColorJitter ~~~~~~~~~~~ The :class:`~torchvision.transforms.ColorJitter` transform randomly changes the brightness, saturation, and other properties of an image. .. GENERATED FROM PYTHON SOURCE LINES 106-110 .. code-block:: default jitter = T.ColorJitter(brightness=.5, hue=.3) jitted_imgs = [jitter(orig_img) for _ in range(4)] plot(jitted_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_006.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 111-116 GaussianBlur ~~~~~~~~~~~~ The :class:`~torchvision.transforms.GaussianBlur` transform (see also :func:`~torchvision.transforms.functional.gaussian_blur`) performs gaussian blur transform on an image. .. GENERATED FROM PYTHON SOURCE LINES 116-120 .. code-block:: default blurrer = T.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5)) blurred_imgs = [blurrer(orig_img) for _ in range(4)] plot(blurred_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_007.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 121-126 RandomPerspective ~~~~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomPerspective` transform (see also :func:`~torchvision.transforms.functional.perspective`) performs random perspective transform on an image. .. GENERATED FROM PYTHON SOURCE LINES 126-130 .. code-block:: default perspective_transformer = T.RandomPerspective(distortion_scale=0.6, p=1.0) perspective_imgs = [perspective_transformer(orig_img) for _ in range(4)] plot(perspective_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_008.png :alt: Original image :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out Out: .. code-block:: none /home/matti/miniconda3/envs/pytorch-test/lib/python3.8/site-packages/torchvision/transforms/functional.py:594: UserWarning: torch.lstsq is deprecated in favor of torch.linalg.lstsq and will be removed in a future PyTorch release. torch.linalg.lstsq has reversed arguments and does not return the QR decomposition in the returned tuple (although it returns other information about the problem). To get the qr decomposition consider using torch.linalg.qr. The returned solution in torch.lstsq stored the residuals of the solution in the last m - n columns of the returned value whenever m > n. In torch.linalg.lstsq, the residuals in the field 'residuals' of the returned named tuple. The unpacking of the solution, as in X, _ = torch.lstsq(B, A).solution[:A.size(1)] should be replaced with X = torch.linalg.lstsq(A, B).solution (Triggered internally at /opt/conda/conda-bld/pytorch_1623448216815/work/aten/src/ATen/LegacyTHFunctionsCPU.cpp:389.) res = torch.lstsq(b_matrix, a_matrix)[0] .. GENERATED FROM PYTHON SOURCE LINES 131-136 RandomRotation ~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomRotation` transform (see also :func:`~torchvision.transforms.functional.rotate`) rotates an image with random angle. .. GENERATED FROM PYTHON SOURCE LINES 136-140 .. code-block:: default rotater = T.RandomRotation(degrees=(0, 180)) rotated_imgs = [rotater(orig_img) for _ in range(4)] plot(rotated_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_009.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 141-146 RandomAffine ~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomAffine` transform (see also :func:`~torchvision.transforms.functional.affine`) performs random affine transform on an image. .. GENERATED FROM PYTHON SOURCE LINES 146-150 .. code-block:: default affine_transfomer = T.RandomAffine(degrees=(30, 70), translate=(0.1, 0.3), scale=(0.5, 0.75)) affine_imgs = [affine_transfomer(orig_img) for _ in range(4)] plot(affine_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_010.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 151-156 RandomCrop ~~~~~~~~~~ The :class:`~torchvision.transforms.RandomCrop` transform (see also :func:`~torchvision.transforms.functional.crop`) crops an image at a random location. .. GENERATED FROM PYTHON SOURCE LINES 156-160 .. code-block:: default cropper = T.RandomCrop(size=(128, 128)) crops = [cropper(orig_img) for _ in range(4)] plot(crops) .. image:: /auto_examples/images/sphx_glr_plot_transforms_011.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 161-167 RandomResizedCrop ~~~~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomResizedCrop` transform (see also :func:`~torchvision.transforms.functional.resized_crop`) crops an image at a random location, and then resizes the crop to a given size. .. GENERATED FROM PYTHON SOURCE LINES 167-171 .. code-block:: default resize_cropper = T.RandomResizedCrop(size=(32, 32)) resized_crops = [resize_cropper(orig_img) for _ in range(4)] plot(resized_crops) .. image:: /auto_examples/images/sphx_glr_plot_transforms_012.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 172-177 RandomInvert ~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomInvert` transform (see also :func:`~torchvision.transforms.functional.invert`) randomly inverts the colors of the given image. .. GENERATED FROM PYTHON SOURCE LINES 177-181 .. code-block:: default inverter = T.RandomInvert() invertered_imgs = [inverter(orig_img) for _ in range(4)] plot(invertered_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_013.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 182-188 RandomPosterize ~~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomPosterize` transform (see also :func:`~torchvision.transforms.functional.posterize`) randomly posterizes the image by reducing the number of bits of each color channel. .. GENERATED FROM PYTHON SOURCE LINES 188-192 .. code-block:: default posterizer = T.RandomPosterize(bits=2) posterized_imgs = [posterizer(orig_img) for _ in range(4)] plot(posterized_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_014.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 193-199 RandomSolarize ~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomSolarize` transform (see also :func:`~torchvision.transforms.functional.solarize`) randomly solarizes the image by inverting all pixel values above the threshold. .. GENERATED FROM PYTHON SOURCE LINES 199-203 .. code-block:: default solarizer = T.RandomSolarize(threshold=192.0) solarized_imgs = [solarizer(orig_img) for _ in range(4)] plot(solarized_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_015.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 204-209 RandomAdjustSharpness ~~~~~~~~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomAdjustSharpness` transform (see also :func:`~torchvision.transforms.functional.adjust_sharpness`) randomly adjusts the sharpness of the given image. .. GENERATED FROM PYTHON SOURCE LINES 209-213 .. code-block:: default sharpness_adjuster = T.RandomAdjustSharpness(sharpness_factor=2) sharpened_imgs = [sharpness_adjuster(orig_img) for _ in range(4)] plot(sharpened_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_016.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 214-219 RandomAutocontrast ~~~~~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomAutocontrast` transform (see also :func:`~torchvision.transforms.functional.autocontrast`) randomly applies autocontrast to the given image. .. GENERATED FROM PYTHON SOURCE LINES 219-223 .. code-block:: default autocontraster = T.RandomAutocontrast() autocontrasted_imgs = [autocontraster(orig_img) for _ in range(4)] plot(autocontrasted_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_017.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 224-229 RandomEqualize ~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomEqualize` transform (see also :func:`~torchvision.transforms.functional.equalize`) randomly equalizes the histogram of the given image. .. GENERATED FROM PYTHON SOURCE LINES 229-233 .. code-block:: default equalizer = T.RandomEqualize() equalized_imgs = [equalizer(orig_img) for _ in range(4)] plot(equalized_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_018.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 234-239 AutoAugment ~~~~~~~~~~~ The :class:`~torchvision.transforms.AutoAugment` transform automatically augments data based on a given auto-augmentation policy. See :class:`~torchvision.transforms.AutoAugmentPolicy` for the available policies. .. GENERATED FROM PYTHON SOURCE LINES 239-248 .. code-block:: default policies = [T.AutoAugmentPolicy.CIFAR10, T.AutoAugmentPolicy.IMAGENET, T.AutoAugmentPolicy.SVHN] augmenters = [T.AutoAugment(policy) for policy in policies] imgs = [ [augmenter(orig_img) for _ in range(4)] for augmenter in augmenters ] row_title = [str(policy).split('.')[-1] for policy in policies] plot(imgs, row_title=row_title) .. image:: /auto_examples/images/sphx_glr_plot_transforms_019.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 249-261 Randomly-applied transforms --------------------------- Some transforms are randomly-applied given a probability ``p``. That is, the transformed image may actually be the same as the original one, even when called with the same transformer instance! RandomHorizontalFlip ~~~~~~~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomHorizontalFlip` transform (see also :func:`~torchvision.transforms.functional.hflip`) performs horizontal flip of an image, with a given probability. .. GENERATED FROM PYTHON SOURCE LINES 261-265 .. code-block:: default hflipper = T.RandomHorizontalFlip(p=0.5) transformed_imgs = [hflipper(orig_img) for _ in range(4)] plot(transformed_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_020.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 266-271 RandomVerticalFlip ~~~~~~~~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomVerticalFlip` transform (see also :func:`~torchvision.transforms.functional.vflip`) performs vertical flip of an image, with a given probability. .. GENERATED FROM PYTHON SOURCE LINES 271-275 .. code-block:: default vflipper = T.RandomVerticalFlip(p=0.5) transformed_imgs = [vflipper(orig_img) for _ in range(4)] plot(transformed_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_021.png :alt: Original image :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 276-280 RandomApply ~~~~~~~~~~~ The :class:`~torchvision.transforms.RandomApply` transform randomly applies a list of transforms, with a given probability. .. GENERATED FROM PYTHON SOURCE LINES 280-283 .. code-block:: default applier = T.RandomApply(transforms=[T.RandomCrop(size=(64, 64))], p=0.5) transformed_imgs = [applier(orig_img) for _ in range(4)] plot(transformed_imgs) .. image:: /auto_examples/images/sphx_glr_plot_transforms_022.png :alt: Original image :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 5.275 seconds) .. _sphx_glr_download_auto_examples_plot_transforms.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_transforms.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_transforms.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_