# torchvision.transforms¶

Transforms are common image transforms. They can be chained together using Compose

class torchvision.transforms.Compose(transforms)

Composes several transforms together.

Parameters: transforms (list of Transform objects) – list of transforms to compose.

Example

>>> transforms.Compose([
>>>     transforms.CenterCrop(10),
>>>     transforms.ToTensor(),
>>> ])


## Transforms on PIL Image¶

class torchvision.transforms.CenterCrop(size)

Crops the given PIL Image at the center.

Parameters: size (sequence or 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.
class torchvision.transforms.ColorJitter(brightness=0, contrast=0, saturation=0, hue=0)

Randomly change the brightness, contrast and saturation of an image.

Parameters: brightness (float) – How much to jitter brightness. brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. contrast (float) – How much to jitter contrast. contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. saturation (float) – How much to jitter saturation. saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. hue (float) – How much to jitter hue. hue_factor is chosen uniformly from [-hue, hue]. Should be >=0 and <= 0.5.
class torchvision.transforms.FiveCrop(size)

Crop the given PIL Image into four corners and the central crop

Note

This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your Dataset returns. See below for an example of how to deal with this.

Parameters: size (sequence or int) – Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop of size (size, size) is made.

Example

>>> transform = Compose([
>>>    FiveCrop(size), # this is a list of PIL Images
>>>    Lambda(lambda crops: torch.stack([ToTensor()(crop) for crop in crops])) # returns a 4D tensor
>>> ])
>>> #In your test loop you can do the following:
>>> input, target = batch # input is a 5d tensor, target is 2d
>>> bs, ncrops, c, h, w = input.size()
>>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
>>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops

class torchvision.transforms.Grayscale(num_output_channels=1)

Convert image to grayscale.

Parameters: num_output_channels (int) – (1 or 3) number of channels desired for output image Grayscale version of the input. - If num_output_channels == 1 : returned image is single channel - If num_output_channels == 3 : returned image is 3 channel with r == g == b PIL Image
class torchvision.transforms.LinearTransformation(transformation_matrix)

Transform a tensor image with a square transformation matrix computed offline.

Given transformation_matrix, will flatten the torch.*Tensor, compute the dot product with the transformation matrix and reshape the tensor to its original shape.

Applications:
• whitening: zero-center the data, compute the data covariance matrix
[D x D] with np.dot(X.T, X), perform SVD on this matrix and pass it as transformation_matrix.
Parameters: transformation_matrix (Tensor) – tensor [D x D], D = C x H x W
class torchvision.transforms.Pad(padding, fill=0, padding_mode='constant')

Pad the given PIL Image on all sides with the given “pad” value.

class torchvision.transforms.RandomAffine(degrees, translate=None, scale=None, shear=None, resample=False, fillcolor=0)

Random affine transformation of the image keeping center invariant

Parameters: 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). Set to 0 to desactivate rotations. translate (tuple, optional) – tuple of 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 and vertical shift is randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default. scale (tuple, optional) – scaling factor interval, e.g (a, b), then scale is randomly sampled from the range a <= scale <= b. Will keep original scale by default. shear (sequence or float or int, optional) – 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). Will not apply shear by default resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional) – An optional resampling filter. See filters for more information. If omitted, or if the image has mode “1” or “P”, it is set to PIL.Image.NEAREST. fillcolor (int) – Optional fill color for the area outside the transform in the output image. (Pillow>=5.0.0)
class torchvision.transforms.RandomApply(transforms, p=0.5)

Apply randomly a list of transformations with a given probability

Parameters: transforms (list or tuple) – list of transformations p (float) – probability
class torchvision.transforms.RandomChoice(transforms)

Apply single transformation randomly picked from a list

class torchvision.transforms.RandomCrop(size, padding=None, pad_if_needed=False, fill=0, padding_mode='constant')

Crop the given PIL Image at a random location.

class torchvision.transforms.RandomGrayscale(p=0.1)

Randomly convert image to grayscale with a probability of p (default 0.1).

Parameters: p (float) – probability that image should be converted to grayscale. Grayscale version of the input image with probability p and unchanged with probability (1-p). - If input image is 1 channel: grayscale version is 1 channel - If input image is 3 channel: grayscale version is 3 channel with r == g == b PIL Image
class torchvision.transforms.RandomHorizontalFlip(p=0.5)

Horizontally flip the given PIL Image randomly with a given probability.

Parameters: p (float) – probability of the image being flipped. Default value is 0.5
class torchvision.transforms.RandomOrder(transforms)

Apply a list of transformations in a random order

class torchvision.transforms.RandomResizedCrop(size, scale=(0.08, 1.0), ratio=(0.75, 1.3333333333333333), interpolation=2)

Crop the given PIL Image 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 4/3) of the original aspect ratio is made. This crop is finally resized to given size. This is popularly used to train the Inception networks.

Parameters: size – expected output size of each edge scale – range of size of the origin size cropped ratio – range of aspect ratio of the origin aspect ratio cropped interpolation – Default: PIL.Image.BILINEAR
class torchvision.transforms.RandomRotation(degrees, resample=False, expand=False, center=None)

Rotate the image by angle.

Parameters: 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). resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional) – An optional resampling filter. See filters for more information. If omitted, or if the image has mode “1” or “P”, it is set to PIL.Image.NEAREST. expand (bool, optional) – Optional expansion flag. 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.
class torchvision.transforms.RandomSizedCrop(*args, **kwargs)

Note: This transform is deprecated in favor of RandomResizedCrop.

class torchvision.transforms.RandomVerticalFlip(p=0.5)

Vertically flip the given PIL Image randomly with a given probability.

Parameters: p (float) – probability of the image being flipped. Default value is 0.5
class torchvision.transforms.Resize(size, interpolation=2)

Resize the input PIL Image to the given size.

Parameters: size (sequence or int) – 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) interpolation (int, optional) – Desired interpolation. Default is PIL.Image.BILINEAR
class torchvision.transforms.Scale(*args, **kwargs)

Note: This transform is deprecated in favor of Resize.

class torchvision.transforms.TenCrop(size, vertical_flip=False)

Crop the given PIL Image into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default)

Note

This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your Dataset returns. See below for an example of how to deal with this.

Parameters: size (sequence or 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. vertical_flip (bool) – Use vertical flipping instead of horizontal

Example

>>> transform = Compose([
>>>    TenCrop(size), # this is a list of PIL Images
>>>    Lambda(lambda crops: torch.stack([ToTensor()(crop) for crop in crops])) # returns a 4D tensor
>>> ])
>>> #In your test loop you can do the following:
>>> input, target = batch # input is a 5d tensor, target is 2d
>>> bs, ncrops, c, h, w = input.size()
>>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
>>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops


## Transforms on torch.*Tensor¶

class torchvision.transforms.Normalize(mean, std)

Normalize a tensor image 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 torch.*Tensor i.e. input[channel] = (input[channel] - mean[channel]) / std[channel]

Note

This transform acts in-place, i.e., it mutates the input tensor.

Parameters: mean (sequence) – Sequence of means for each channel. std (sequence) – Sequence of standard deviations for each channel.
__call__(tensor)
Parameters: tensor (Tensor) – Tensor image of size (C, H, W) to be normalized. Normalized Tensor image. Tensor

## Conversion Transforms¶

class torchvision.transforms.ToPILImage(mode=None)

Convert a tensor or an ndarray to PIL Image.

Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape H x W x C to a PIL Image while preserving the value range.

Parameters: mode (PIL.Image mode) – color space and pixel depth of input data (optional). If mode is None (default) there are some assumptions made about the input data: 1. If the input has 3 channels, the mode is assumed to be RGB. 2. If the input has 4 channels, the mode is assumed to be RGBA. 3. If the input has 1 channel, the mode is determined by the data type (i,e, int, float, short).
__call__(pic)
Parameters: pic (Tensor or numpy.ndarray) – Image to be converted to PIL Image. Image converted to PIL Image. PIL Image
class torchvision.transforms.ToTensor

Convert a PIL Image or numpy.ndarray to tensor.

Converts a PIL Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].

__call__(pic)
Parameters: pic (PIL Image or numpy.ndarray) – Image to be converted to tensor. Converted image. Tensor

## Generic Transforms¶

class torchvision.transforms.Lambda(lambd)

Apply a user-defined lambda as a transform.

Parameters: lambd (function) – Lambda/function to be used for transform.

## Functional Transforms¶

torchvision.transforms.functional.adjust_brightness(img, brightness_factor)

Parameters: img (PIL Image) – PIL 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. Brightness adjusted image. PIL Image
torchvision.transforms.functional.adjust_contrast(img, contrast_factor)

Parameters: img (PIL Image) – PIL 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. Contrast adjusted image. PIL Image
torchvision.transforms.functional.adjust_gamma(img, gamma, gain=1)

Perform gamma correction on an image.

Also known as Power Law Transform. Intensities in RGB mode are adjusted based on the following equation:

$I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma}$

See Gamma Correction for more details.

Parameters: img (PIL Image) – PIL Image to be adjusted. gamma (float) – Non negative real number, same as $$\gamma$$ in the equation. gamma larger than 1 make the shadows darker, while gamma smaller than 1 make dark regions lighter. gain (float) – The constant multiplier.
torchvision.transforms.functional.adjust_hue(img, hue_factor)

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].

See Hue for more details.

Parameters: img (PIL Image) – PIL 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. Hue adjusted image. PIL Image
torchvision.transforms.functional.adjust_saturation(img, saturation_factor)

Adjust color saturation of an image.

Parameters: img (PIL Image) – PIL 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. Saturation adjusted image. PIL Image
torchvision.transforms.functional.affine(img, angle, translate, scale, shear, resample=0, fillcolor=None)

Apply affine transformation on the image keeping image center invariant

Parameters: img (PIL Image) – PIL Image to be rotated. angle (float or int) – rotation angle in degrees between -180 and 180, clockwise direction. translate (list or tuple of python:integers) – horizontal and vertical translations (post-rotation translation) scale (float) – overall scale shear (float) – shear angle value in degrees between -180 to 180, clockwise direction. resample (PIL.Image.NEAREST or PIL.Image.BILINEAR or PIL.Image.BICUBIC, optional) – An optional resampling filter. See filters for more information. If omitted, or if the image has mode “1” or “P”, it is set to PIL.Image.NEAREST. fillcolor (int) – Optional fill color for the area outside the transform in the output image. (Pillow>=5.0.0)
torchvision.transforms.functional.crop(img, i, j, h, w)

Crop the given PIL Image.

Parameters: img (PIL Image) – Image to be cropped. i – Upper pixel coordinate. j – Left pixel coordinate. h – Height of the cropped image. w – Width of the cropped image. Cropped image. PIL Image
torchvision.transforms.functional.five_crop(img, size)

Crop the given PIL Image into four corners and the central crop.

Note

This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your Dataset returns.

Parameters: size (sequence or 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. tuple (tl, tr, bl, br, center) Corresponding top left, top right, bottom left, bottom right and center crop. tuple
torchvision.transforms.functional.hflip(img)

Horizontally flip the given PIL Image.

Parameters: img (PIL Image) – Image to be flipped. Horizontall flipped image. PIL Image
torchvision.transforms.functional.normalize(tensor, mean, std)

Normalize a tensor image with mean and standard deviation.

Note

This transform acts in-place, i.e., it mutates the input tensor.

See Normalize for more details.

Parameters: tensor (Tensor) – Tensor image of size (C, H, W) to be normalized. mean (sequence) – Sequence of means for each channel. std (sequence) – Sequence of standard deviations for each channely. Normalized Tensor image. Tensor
torchvision.transforms.functional.pad(img, padding, fill=0, padding_mode='constant')

Pad the given PIL Image on all sides with specified padding mode and fill value.

torchvision.transforms.functional.resize(img, size, interpolation=2)

Resize the input PIL Image to the given size.

Parameters: img (PIL Image) – Image to be resized. size (sequence or int) – Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if height > width, then image will be rescaled to $$\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)$$ interpolation (int, optional) – Desired interpolation. Default is PIL.Image.BILINEAR Resized image. PIL Image
torchvision.transforms.functional.resized_crop(img, i, j, h, w, size, interpolation=2)

Crop the given PIL Image and resize it to desired size.

Notably used in RandomResizedCrop.

Parameters: img (PIL Image) – Image to be cropped. i – Upper pixel coordinate. j – Left pixel coordinate. h – Height of the cropped image. w – Width of the cropped image. size (sequence or int) – Desired output size. Same semantics as scale. interpolation (int, optional) – Desired interpolation. Default is PIL.Image.BILINEAR. Cropped image. PIL Image
torchvision.transforms.functional.rotate(img, angle, resample=False, expand=False, center=None)

Rotate the image by angle.

Parameters: img (PIL Image) – PIL Image to be rotated. angle (float or int) – In degrees degrees counter clockwise order. resample (PIL.Image.NEAREST or PIL.Image.BILINEAR or PIL.Image.BICUBIC, optional) – An optional resampling filter. See filters for more information. If omitted, or if the image has mode “1” or “P”, it is set to PIL.Image.NEAREST. expand (bool, optional) – Optional expansion flag. 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. center (2-tuple, optional) – Optional center of rotation. Origin is the upper left corner. Default is the center of the image.
torchvision.transforms.functional.ten_crop(img, size, vertical_flip=False)
Crop the given PIL Image into four corners and the central crop plus the
flipped version of these (horizontal flipping is used by default).

Note

This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your Dataset returns.

Parameters: size (sequence or 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. vertical_flip (bool) – Use vertical flipping instead of horizontal tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip) Corresponding top left, top right, bottom left, bottom right and center crop and same for the flipped image. tuple
torchvision.transforms.functional.to_grayscale(img, num_output_channels=1)

Convert image to grayscale version of image.

Parameters: img (PIL Image) – Image to be converted to grayscale. Grayscale version of the image. if num_output_channels = 1 : returned image is single channelif num_output_channels = 3 : returned image is 3 channel with r = g = b PIL Image
torchvision.transforms.functional.to_pil_image(pic, mode=None)

Convert a tensor or an ndarray to PIL Image.

See ToPILImage for more details.

Parameters: pic (Tensor or numpy.ndarray) – Image to be converted to PIL Image. mode (PIL.Image mode) – color space and pixel depth of input data (optional).
Returns: Image converted to PIL Image. PIL Image
torchvision.transforms.functional.to_tensor(pic)

Convert a PIL Image or numpy.ndarray to tensor.

See ToTensor for more details.

Parameters: pic (PIL Image or numpy.ndarray) – Image to be converted to tensor. Converted image. Tensor
torchvision.transforms.functional.vflip(img)

Vertically flip the given PIL Image.

Parameters: img (PIL Image) – Image to be flipped. Vertically flipped image. PIL Image