Transforming and augmenting images¶
Transforms are common image transformations available in the
torchvision.transforms
module. They can be chained together using
Compose
.
Most transform classes have a function equivalent: functional
transforms give fine-grained control over the
transformations.
This is useful if you have to build a more complex transformation pipeline
(e.g. in the case of segmentation tasks).
Most transformations accept both PIL images and tensor images, although some transformations are PIL-only and some are tensor-only. The Conversion Transforms may be used to convert to and from PIL images.
The transformations that accept tensor images also accept batches of tensor
images. A Tensor Image is a tensor with (C, H, W)
shape, where C
is a
number of channels, H
and W
are image height and width. A batch of
Tensor Images is a tensor of (B, C, H, W)
shape, where B
is a number
of images in the batch.
The expected range of the values of a tensor image is implicitly defined by
the tensor dtype. Tensor images with a float dtype are expected to have
values in [0, 1)
. Tensor images with an integer dtype are expected to
have values in [0, MAX_DTYPE]
where MAX_DTYPE
is the largest value
that can be represented in that dtype.
Randomized transformations will apply the same transformation to all the images of a given batch, but they will produce different transformations across calls. For reproducible transformations across calls, you may use functional transforms.
The following examples illustrate the use of the available transforms:
Warning
Since v0.8.0 all random transformations are using torch default random generator to sample random parameters. It is a backward compatibility breaking change and user should set the random state as following:
# Previous versions
# import random
# random.seed(12)
# Now
import torch
torch.manual_seed(17)
Please, keep in mind that the same seed for torch random generator and Python random generator will not produce the same results.
Scriptable transforms¶
In order to script the transformations, please use torch.nn.Sequential
instead of Compose
.
transforms = torch.nn.Sequential(
transforms.CenterCrop(10),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
)
scripted_transforms = torch.jit.script(transforms)
Make sure to use only scriptable transformations, i.e. that work with torch.Tensor
and does not require
lambda functions or PIL.Image
.
For any custom transformations to be used with torch.jit.script
, they should be derived from torch.nn.Module
.
Transforms on PIL Image and torch.*Tensor¶
|
Crops the given image at the center. |
|
Randomly change the brightness, contrast, saturation and hue of an image. |
|
Crop the given image into four corners and the central crop. |
|
Convert image to grayscale. |
|
Pad the given image on all sides with the given “pad” value. |
|
Random affine transformation of the image keeping center invariant. |
|
Apply randomly a list of transformations with a given probability. |
|
Crop the given image at a random location. |
|
Randomly convert image to grayscale with a probability of p (default 0.1). |
|
Horizontally flip the given image randomly with a given probability. |
|
Performs a random perspective transformation of the given image with a given probability. |
|
Crop a random portion of image and resize it to a given size. |
|
Rotate the image by angle. |
|
Vertically flip the given image randomly with a given probability. |
|
Resize the input image to the given size. |
|
Crop the given image into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). |
|
Blurs image with randomly chosen Gaussian blur. |
|
Inverts the colors of the given image randomly with a given probability. |
|
Posterize the image randomly with a given probability by reducing the number of bits for each color channel. |
|
Solarize the image randomly with a given probability by inverting all pixel values above a threshold. |
|
Adjust the sharpness of the image randomly with a given probability. |
|
Autocontrast the pixels of the given image randomly with a given probability. |
|
Equalize the histogram of the given image randomly with a given probability. |
Transforms on PIL Image only¶
|
Apply single transformation randomly picked from a list. |
|
Apply a list of transformations in a random order. |
Transforms on torch.*Tensor only¶
|
Transform a tensor image with a square transformation matrix and a mean_vector computed offline. |
|
Normalize a tensor image with mean and standard deviation. |
|
Randomly selects a rectangle region in an torch Tensor image and erases its pixels. |
|
Convert a tensor image to the given |
Conversion Transforms¶
|
Convert a tensor or an ndarray to PIL Image. |
|
Convert a |
Convert a |
Automatic Augmentation Transforms¶
AutoAugment is a common Data Augmentation technique that can improve the accuracy of Image Classification models. Though the data augmentation policies are directly linked to their trained dataset, empirical studies show that ImageNet policies provide significant improvements when applied to other datasets. In TorchVision we implemented 3 policies learned on the following datasets: ImageNet, CIFAR10 and SVHN. The new transform can be used standalone or mixed-and-matched with existing transforms:
|
AutoAugment policies learned on different datasets. |
|
AutoAugment data augmentation method based on “AutoAugment: Learning Augmentation Strategies from Data”. |
|
RandAugment data augmentation method based on “RandAugment: Practical automated data augmentation with a reduced search space”. |
|
Dataset-independent data-augmentation with TrivialAugment Wide, as described in “TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation”. |
Functional Transforms¶
Functional transforms give you fine-grained control of the transformation pipeline. As opposed to the transformations above, functional transforms don’t contain a random number generator for their parameters. That means you have to specify/generate all parameters, but the functional transform will give you reproducible results across calls.
Example: you can apply a functional transform with the same parameters to multiple images like this:
import torchvision.transforms.functional as TF
import random
def my_segmentation_transforms(image, segmentation):
if random.random() > 0.5:
angle = random.randint(-30, 30)
image = TF.rotate(image, angle)
segmentation = TF.rotate(segmentation, angle)
# more transforms ...
return image, segmentation
Example: you can use a functional transform to build transform classes with custom behavior:
import torchvision.transforms.functional as TF
import random
class MyRotationTransform:
"""Rotate by one of the given angles."""
def __init__(self, angles):
self.angles = angles
def __call__(self, x):
angle = random.choice(self.angles)
return TF.rotate(x, angle)
rotation_transform = MyRotationTransform(angles=[-30, -15, 0, 15, 30])
|
Adjust brightness of an image. |
|
Adjust contrast of an image. |
|
Perform gamma correction on an image. |
|
Adjust hue of an image. |
|
Adjust color saturation of an image. |
|
Adjust the sharpness of an image. |
|
Apply affine transformation on the image keeping image center invariant. |
|
Maximize contrast of an image by remapping its pixels per channel so that the lowest becomes black and the lightest becomes white. |
|
Crops the given image at the center. |
|
Convert a tensor image to the given |
|
Crop the given image at specified location and output size. |
|
Equalize the histogram of an image by applying a non-linear mapping to the input in order to create a uniform distribution of grayscale values in the output. |
|
Erase the input Tensor Image with given value. |
|
Crop the given image into four corners and the central crop. |
|
Performs Gaussian blurring on the image by given kernel. |
Returns the number of channels of an image. |
|
|
Returns the size of an image as [width, height]. |
|
Horizontally flip the given image. |
|
Invert the colors of an RGB/grayscale image. |
|
Normalize a float tensor image with mean and standard deviation. |
|
Pad the given image on all sides with the given “pad” value. |
|
Perform perspective transform of the given image. |
|
Convert a |
|
Posterize an image by reducing the number of bits for each color channel. |
|
Resize the input image to the given size. |
|
Crop the given image and resize it to desired size. |
|
Convert RGB image to grayscale version of image. |
|
Rotate the image by angle. |
|
Solarize an RGB/grayscale image by inverting all pixel values above a threshold. |
|
Generate ten cropped images from the given image. |
|
Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image. |
|
Convert a tensor or an ndarray to PIL Image. |
|
Convert a |
|
Vertically flip the given image. |