SoFunction
Updated on 2024-10-29

Pytorch Image Transformation Function Collection Summary

I. Required python modules

PyTorch's Vision module provides many functions for image transformations.

torchvision/transforms/

from __future__ import division
import torch
import sys
import math
from PIL import Image, ImageOps, ImageEnhance, PILLOW_VERSION
try:
 import accimage
except ImportError:
 accimage = None
import numpy as np
import numbers
import collections
import warnings
import matplotlib as plt

if sys.version_info < (3, 3):
 Sequence = 
 Iterable = 
else:
 Sequence = 
 Iterable = 

The following chart is an example:

img_file = ""
img = (img_file)
width, height =  #(750, 815)
()

Second, PyTorch image transformation function

2.1 Determining the image data type

# Image format checking, e.g., pil, tensor, numpy
def _is_pil_image(img):
 if accimage is not None:
  return isinstance(img, (, ))
 else:
  return isinstance(img, )

def _is_tensor_image(img):
 return torch.is_tensor(img) and () == 3

def _is_numpy_image(img):
 return isinstance(img, ) and ( in {2, 3})
# example:
_is_pil_image(img)
# True

_is_tensor_image(img)
# False

_is_numpy_image(img)
# False

_is_numpy_image((img))
# True

2.2 to_tensor(pic)

commander-in-chief (military)PIL Image maybe convert totensor

def to_tensor(pic):
 """
 Args:
  pic (PIL Image or ): Image to be converted to tensor.

 Returns:
  Tensor: Converted image.
 """
 if not(_is_pil_image(pic) or _is_numpy_image(pic)):
  raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))

 if isinstance(pic, ):
  # handle numpy array
  img = torch.from_numpy(((2, 0, 1)))
  # backward compatibility
  if isinstance(img, ):
   return ().div(255)
  else:
   return img

 if accimage is not None and isinstance(pic, ):
  nppic = ([, , ], dtype=np.float32)
  (nppic)
  return torch.from_numpy(nppic)

 # handle PIL Image
 if  == 'I':
  img = torch.from_numpy((pic, np.int32, copy=False))
 elif  == 'I;16':
  img = torch.from_numpy((pic, np.int16, copy=False))
 elif  == 'F':
  img = torch.from_numpy((pic, np.float32, copy=False))
 elif  == '1':
  img = 255 * torch.from_numpy((pic, np.uint8, copy=False))
 else:
  img = (.from_buffer(()))
 # PIL image mode: L, P, I, F, RGB, YCbCr, RGBA, CMYK
 if  == 'YCbCr':
  nchannel = 3
 elif  == 'I;16':
  nchannel = 1
 else:
  nchannel = len()
 img = ([1], [0], nchannel)
 # put it from HWC to CHW format
 # yikes, this transpose takes 80% of the loading time/CPU
 img = (0, 1).transpose(0, 2).contiguous()
 if isinstance(img, ):
  return ().div(255)
 else:
  return img

2.3 to_pil_image(pic, mode=None)

commander-in-chief (military)tensor maybendarray convert toPIL Image

def to_pil_image(pic, mode=None):
 """
 Args:
  pic (Tensor or ): Image to be converted to PIL Image.
  mode (` mode`_): color space and pixel depth of input data (optional).

 .. _PIL.Image mode: /en/latest/handbook/#concept-modes

 Returns:
  PIL Image: Image converted to PIL Image.
 """
 if not(isinstance(pic, ) or isinstance(pic, )):
  raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic)))

 elif isinstance(pic, ):
  if () not in {2, 3}:
   raise ValueError('pic should be 2/3 dimensional. Got {} '\
        'dimensions.'.format(()))

  elif () == 2:
   # if 2D image, add channel dimension (CHW)
   pic.unsqueeze_(0)

 elif isinstance(pic, ):
  if  not in {2, 3}:
   raise ValueError('pic should be 2/3 dimensional. Got {} '\
        'dimensions.'.format())

  elif  == 2:
   # if 2D image, add channel dimension (HWC)
   pic = np.expand_dims(pic, 2)

 npimg = pic
 if isinstance(pic, ):
  pic = (255).byte()
 if isinstance(pic, ):
  npimg = ((), (1, 2, 0))

 if not isinstance(npimg, ):
  raise TypeError('Input pic must be a  or NumPy ndarray, ' +
      'not {}'.format(type(npimg)))

 if [2] == 1:
  expected_mode = None
  npimg = npimg[:, :, 0]
  if  == np.uint8:
   expected_mode = 'L'
  elif  == np.int16:
   expected_mode = 'I;16'
  elif  == np.int32:
   expected_mode = 'I'
  elif  == np.float32:
   expected_mode = 'F'
  if mode is not None and mode != expected_mode:
   raise ValueError("Incorrect mode ({}) supplied for input type {}. Should be {}"
        .format(mode, , expected_mode))
  mode = expected_mode

 elif [2] == 4:
  permitted_4_channel_modes = ['RGBA', 'CMYK']
  if mode is not None and mode not in permitted_4_channel_modes:
   raise ValueError("Only modes {} are supported for 4D inputs".format(permitted_4_channel_modes))

  if mode is None and  == np.uint8:
   mode = 'RGBA'
 else:
  permitted_3_channel_modes = ['RGB', 'YCbCr', 'HSV']
  if mode is not None and mode not in permitted_3_channel_modes:
   raise ValueError("Only modes {} are supported for 3D inputs".format(permitted_3_channel_modes))
  if mode is None and  == np.uint8:
   mode = 'RGB'

 if mode is None:
  raise TypeError('Input type {} is not supported'.format())

 return (npimg, mode=mode)

2.4 normalize(tensor, mean, std)

normalizetensor The image of .in-place Calculations.

def normalize(tensor, mean, std):
 """
 Args:
  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.

 Returns:
  Tensor: Normalized Tensor image.
 """
 if not _is_tensor_image(tensor):
  raise TypeError('tensor is not a torch image.')

 # This is faster than using broadcasting, don't change without benchmarking
 for t, m, s in zip(tensor, mean, std):
  t.sub_(m).div_(s)
 return tensor
# example
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
img_normalize = normalize(img_tensor, mean, std)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(to_pil_image(img_normalize))
("off")
ax2.set_title("normalize img")
()

2.5 resize(img, size, interpolation=)

Resize the input PIL Image to a given size.
The parameter size is the adjusted size.
If size is an array (h, w), then adjust directly to that (h, w) size.
If size is an int value, the shortest edge of the resized image is that value, and the aspect ratio remains fixed.

def resize(img, size, interpolation=):
 """
 Args:
  img (PIL Image): Image to be resized.
  size (sequence or int): Desired output size. 
  interpolation (int, optional): Desired interpolation. Default is
   ````
 Returns:
  PIL Image: Resized image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
 if not (isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)):
  raise TypeError('Got inappropriate size arg: {}'.format(size))

 if isinstance(size, int):
  w, h = 
  if (w <= h and w == size) or (h <= w and h == size):
   return img
  if w < h:
   ow = size
   oh = int(size * h / w)
   return ((ow, oh), interpolation)
  else:
   oh = size
   ow = int(size * w / h)
   return ((ow, oh), interpolation)
 else:
  return (size[::-1], interpolation)
# example:
img_resize_256x256 = resize(img, (256, 256)) # (256, 256)
img_resize_256 = resize(img, 256) # (256, 278)

# vis
ax1 = (1, 3, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 3, 2)
(img_resize_256x256)
("off")
ax2.set_title("resize_256x256 img")
ax3 = (1, 3, 3)
(img_resize_256)
("off")
ax3.set_title("resize_256 img")
()

2.6 pad(img, padding, fill=0, padding_mode=‘constant')

Based on the specifiedpadding mode and fill value for a givenPIL Image All the edges of thepad Processing.
Parameter padding - int or tuple form.

padding:

  • If it is an int value, then padding the int value is applied to all edges.
  • For a tuple of length 2, padding is applied to left/right and top/bottom.
  • For a tuple of length 4, padding is applied to the left, top, right, and bottom edges.

Parameter fill - pixel fill value, default is 0. If the value is a tuple of length 3, the R, G and B channels are filled separately. Only used whenpadding_mode='constant' of the United States of America.

Parameter padding_mode - type of padding, optional: constant, edge, reflect, symmetric. default is constant. padding constant value.

constant - padding padding constant fill.

edge - padding The last value of the edge of the image.

reflect - padding the reflection (reflection) value of the image, (not duplicated for the last pixel value at the edge of the image)
For example, [1, 2, 3, 4] in reflect mode padding 2 element values on both sides will give:
[3, 2, 1, 2, 3, 4, 3, 2]

symmetric - padding The reflection value of the image, (repeated for the last pixel value at the edge of the image).
For example, [1, 2, 3, 4] in symmetric mode padding 2 element values on either side will give:
[2, 1, 1, 2, 3, 4, 4, 3]

def pad(img, padding, fill=0, padding_mode='constant'):
 """
 Args:
  img (PIL Image): Image to be padded.
  padding (int or tuple): Padding on each border. 
  fill: Pixel fill value for constant fill. Default is 0. 
  padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. 
      Default is constant.
 Returns:
  PIL Image: Padded image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 if not isinstance(padding, (, tuple)):
  raise TypeError('Got inappropriate padding arg')
 if not isinstance(fill, (, str, tuple)):
  raise TypeError('Got inappropriate fill arg')
 if not isinstance(padding_mode, str):
  raise TypeError('Got inappropriate padding_mode arg')

 if isinstance(padding, Sequence) and len(padding) not in [2, 4]:
  raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
       "{} element tuple".format(len(padding)))

 assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \
  'Padding mode should be either constant, edge, reflect or symmetric'

 if padding_mode == 'constant':
  if  == 'P':
   palette = ()
   image = (img, border=padding, fill=fill)
   (palette)
   return image

  return (img, border=padding, fill=fill)
 else:
  if isinstance(padding, int):
   pad_left = pad_right = pad_top = pad_bottom = padding
  if isinstance(padding, Sequence) and len(padding) == 2:
   pad_left = pad_right = padding[0]
   pad_top = pad_bottom = padding[1]
  if isinstance(padding, Sequence) and len(padding) == 4:
   pad_left = padding[0]
   pad_top = padding[1]
   pad_right = padding[2]
   pad_bottom = padding[3]

  if  == 'P':
   palette = ()
   img = (img)
   img = (img, 
       ((pad_top, pad_bottom), (pad_left, pad_right)), 
       padding_mode)
   img = (img)
   (palette)
   return img

  img = (img)
  # RGB image
  if len() == 3:
   img = (img, 
       ((pad_top, pad_bottom), 
       (pad_left, pad_right), 
       (0, 0)), 
       padding_mode)
  # Grayscale image
  if len() == 2:
   img = (img, 
       ((pad_top, pad_bottom), (pad_left, pad_right)), 
       padding_mode)

  return (img)
# example:
img_padding = pad(img, (10, 20, 30 ,40), fill=128)	# (750, 815) -> (790, 875)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_padding)
("off")
ax2.set_title("padding img")
()

2.7 crop(img, i, j, h, w)

Crop the given PIL Image.

def crop(img, i, j, h, w):
 """
 Args:
  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.

 Returns:
  PIL Image: Cropped image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 return ((j, i, j + w, i + h))
# example
img_crop = crop(img, 100, 100, 500, 500)	# (750, 815) -> (500, 500)

ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_crop)
("off")
ax2.set_title("crop img")
()

2.8 center_crop(img, output_size)

def center_crop(img, output_size):
 if isinstance(output_size, ):
  output_size = (int(output_size), int(output_size))
 w, h = 
 th, tw = output_size
 i = int(round((h - th) / 2.))
 j = int(round((w - tw) / 2.))
 return crop(img, i, j, th, tw)
#example
img_centercrop = center_crop(img, (256, 256))	# (750, 815) -> (256, 256)

ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_centercrop)
("off")
ax2.set_title("centercrop img")
()

2.9 resized_crop(img, i, j, h, w, size, interpolation=)

Crops a given PIL Image and resizes it to a specific size.

def resized_crop(img, i, j, h, w, size, interpolation=):
 """
 Args:
  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 ``resize``.
  interpolation (int, optional): Desired interpolation. Default is
   ````.
 Returns:
  PIL Image: Cropped image.
 """
 assert _is_pil_image(img), 'img should be PIL Image'
 img = crop(img, i, j, h, w)
 img = resize(img, size, interpolation)
 return img
# example
img_resizedcrop = resized_crop(img, 100, 100, 500, 500, (256, 256))	# (750, 815) -> (500, 500) -> (256, 256)

ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_resizedcrop)
("off")
ax2.set_title("resizedcrop img")
()

2.10 hflip(img)

Horizontally flip the given PIL Image.

def hflip(img):
 """
 Args:
  img (PIL Image): Image to be flipped.

 Returns:
  PIL Image: Horizontall flipped image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 return (Image.FLIP_LEFT_RIGHT)

2.11 vflip(img)

Vertically flip the given PIL Image.

def vflip(img):
 """
 Args:
  img (PIL Image): Image to be flipped.

 Returns:
  PIL Image: Vertically flipped image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 return (Image.FLIP_TOP_BOTTOM)
# example:
img_hflip = hflip(img)
img_vflip = vflip(img)

ax1 = (1, 3, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 3, 2)
(img_hflip)
("off")
ax2.set_title("hflip img")
ax3 = (1, 3, 3)
(img_vflip)
("off")
ax3.set_title("vflip img")
()

2.12 five_crop(img, size)

Crop the given PIL Image into four corners and the central crop.
Crop five sub-images from the four corners and the center of a given PIL Image.

def five_crop(img, size):
 """
 Args:
  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.

 Returns:
  tuple: tuple (tl, tr, bl, br, center)
    Corresponding top left, top right, bottom left, 
    bottom right and center crop.
 """
 if isinstance(size, ):
  size = (int(size), int(size))
 else:
  assert len(size) == 2, "Please provide only two dimensions (h, w) for size."

 w, h = 
 crop_h, crop_w = size
 if crop_w > w or crop_h > h:
  raise ValueError("Requested crop size {} is bigger than input size {}".format(size,
                      (h, w)))
 tl = ((0, 0, crop_w, crop_h))
 tr = ((w - crop_w, 0, w, crop_h))
 bl = ((0, h - crop_h, crop_w, h))
 br = ((w - crop_w, h - crop_h, w, h))
 center = center_crop(img, (crop_h, crop_w))
 return (tl, tr, bl, br, center)
# example:
img_tl, img_tr, img_bl, img_br, img_center = five_crop(img, (400, 400))

ax1 = (2, 3, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (2, 3, 2)
(img_tl)
("off")
ax2.set_title("tl img")
ax3 = (2, 3, 3)
(img_tr)
("off")
ax3.set_title("tr img")
ax4 = (2, 3, 4)
(img_bl)
("off")
ax4.set_title("bl img")
ax5 = (2, 3, 5)
(img_br)
("off")
ax5.set_title("br img")
ax6 = (2, 3, 6)
(img_center)
("off")
ax6.set_title("center img")
()

2.13 ten_crop(img, size, vertical_flip=False)

Crops five sub-images from the four corners and the center of a given PIL Image and flips each sub-image. By default, the image is flipped horizontally.

def ten_crop(img, size, vertical_flip=False):
 """
 Args:
  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

 Returns:
  tuple: 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.
 """
 if isinstance(size, ):
  size = (int(size), int(size))
 else:
  assert len(size) == 2, "Please provide only two dimensions (h, w) for size."

 first_five = five_crop(img, size)

 if vertical_flip:
  img = vflip(img)
 else:
  img = hflip(img)

 second_five = five_crop(img, size)
 return first_five + second_five

2.14 adjust_brightness(img, brightness_factor)

def adjust_brightness(img, brightness_factor):
 """
 Args:
  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,
   2 increases the brightness by a factor of 2.

 Returns:
  PIL Image: Brightness adjusted image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 enhancer = (img)
 img = (brightness_factor)
 return img
# example:
img_adjust_brightness = adjust_brightness(img, 2.5)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_adjust_brightness)
("off")
ax2.set_title("adjust_brightness img")
()

2.15 adjust_contrast(img, contrast_factor)

Adjust the contrast.

def adjust_contrast(img, contrast_factor):
 """
 Args:
  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, 
   2 increases the contrast by a factor of 2.

 Returns:
  PIL Image: Contrast adjusted image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 enhancer = (img)
 img = (contrast_factor)
 return img
# example:
img_adjust_contrast = adjust_contrast(img, 2.5)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_adjust_contrast)
("off")
ax2.set_title("adjust_contrast img")
()

2.16 adjust_saturation(img, saturation_factor)

Adjust color saturation.

def adjust_saturation(img, saturation_factor):
 """
 Args:
  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.

 Returns:
  PIL Image: Saturation adjusted image.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 enhancer = (img)
 img = (saturation_factor)
 return img
# example
img_adjust_saturation = adjust_saturation(img, 2.5)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_adjust_saturation)
("off")
ax2.set_title("adjust_saturation img")
()

2.17 adjust_hue(img, hue_factor)

Adjusting the image HUE.

Image hue adjustment is achieved by converting the image to HSV space and periodically shifting the intensity in the hue channel (H).

Finally, the result is converted back to the original image mode. Parameter hue_factor - factor of the H-channel translation, its value must be in the interval [-0.5, 0.5].

def adjust_hue(img, hue_factor):
 """
 Args:
  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.

 Returns:
  PIL Image: Hue adjusted image.
 """
 if not(-0.5 <= hue_factor <= 0.5):
  raise ValueError('hue_factor is not in [-0.5, 0.5].'.format(hue_factor))

 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 input_mode = 
 if input_mode in {'L', '1', 'I', 'F'}:
  return img

 h, s, v = ('HSV').split()

 np_h = (h, dtype=np.uint8)
 # uint8 addition take cares of rotation across boundaries
 with (over='ignore'):
  np_h += np.uint8(hue_factor * 255)
 h = (np_h, 'L')

 img = ('HSV', (h, s, v)).convert(input_mode)
 return img
# example:
img_adjust_hue = adjust_hue(img, 0.5)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_adjust_hue)
("off")
ax2.set_title("adjust_hue img")
()

2.18 adjust_gamma(img, gamma, gain=1)

Performs gamma correction on an image. Also called Power Law Transform.

def adjust_gamma(img, gamma, gain=1):
 """
 Args:
  img (PIL Image): PIL Image to be adjusted.
  gamma (float): Non negative real number, As in Eq. \gamma (be) worth.
   gamma larger than 1 make the shadows darker,
   while gamma smaller than 1 make dark regions lighter.
  gain (float): The constant multiplier.
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 if gamma < 0:
  raise ValueError('Gamma should be a non-negative real number')

 input_mode = 
 img = ('RGB')

 gamma_map = [255 * gain * pow(ele / 255., gamma) for ele in range(256)] * 3
 img = (gamma_map) # use PIL's point-function to accelerate this part

 img = (input_mode)
 return img
# example:
img_adjust_gamma = adjust_gamma(img, 0.5)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_adjust_gamma)
("off")
ax2.set_title("adjust_gamma img")
()

2.19 rotate(img, angle, resample=False, expand=False, center=None)

Rotate the image.

parametersresample
Optional values: , , .
If the parameterresample is ignored, or the mode of the image is 1 or P, then resample=.

parametersexpand
If expand=True, then extend the output image to include the entire rotated image.
If expand=False or is ignored, keep the output image the same size as the input image.
expand assumes that the rotation is centered and there is no translation.

def rotate(img, angle, resample=False, expand=False, center=None):
 """
 Args:
  img (PIL Image): PIL Image to be rotated.
  angle (float or int): In degrees degrees counter clockwise order.
  resample (```` or ```` or 
     ````, optional):
  expand (bool, optional): Optional expansion flag.
  center (2-tuple, optional): Optional center of rotation.
   Origin is the upper left corner.
   Default is the center of the image.
 """

 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 return (angle, resample, expand, center)
# example:
img_rotate = rotate(img, 60)

# vis
ax1 = (1, 2, 1)
(img)
("off")
ax1.set_title("orig img")
ax2 = (1, 2, 2)
(img_rotate)
("off")
ax2.set_title("rotate img")
()

2.20 affine(img, angle, translate, scale, shear, resample=0, fillcolor=None)

Keeping the center of the image constant, the affine transformation is performed.

def _get_inverse_affine_matrix(center, angle, translate, scale, shear):
 # Helper method to compute inverse matrix for affine transformation

 # As it is explained in 
 # We need compute INVERSE of affine transformation matrix: M = T * C * RSS * C^-1
 # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
 #  C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
 #  RSS is rotation with scale and shear matrix
 #  RSS(a, scale, shear) = [ cos(a)*scale -sin(a + shear)*scale  0]
 #        [ sin(a)*scale cos(a + shear)*scale  0]
 #        [  0     0   1]
 # Thus, the inverse is M^-1 = C * RSS^-1 * C^-1 * T^-1

 angle = (angle)
 shear = (shear)
 scale = 1.0 / scale

 # Inverted rotation matrix with scale and shear
 d = (angle + shear) * (angle) + (angle + shear) * (angle)
 matrix = [
  (angle + shear), (angle + shear), 0,
  -(angle), (angle), 0
 ]
 matrix = [scale / d * m for m in matrix]

 # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1
 matrix[2] += matrix[0] * (-center[0] - translate[0]) + matrix[1] * (-center[1] - translate[1])
 matrix[5] += matrix[3] * (-center[0] - translate[0]) + matrix[4] * (-center[1] - translate[1])

 # Apply center translation: C * RSS^-1 * C^-1 * T^-1
 matrix[2] += center[0]
 matrix[5] += center[1]
 return matrix


def affine(img, angle, translate, scale, shear, resample=0, fillcolor=None):
 """
 Args:
  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 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 (```` or ```` or 
     ````, optional):
  fillcolor (int): Optional fill color for the area outside the transform in the output image. (Pillow>=5.0.0)
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 assert isinstance(translate, (tuple, list)) and len(translate) == 2, \
  "Argument translate should be a list or tuple of length 2"

 assert scale > 0.0, "Argument scale should be positive"

 output_size = 
 center = ([0] * 0.5 + 0.5, [1] * 0.5 + 0.5)
 matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear)
 kwargs = {"fillcolor": fillcolor} if PILLOW_VERSION[0] == '5' else {}
 return (output_size, , matrix, resample, **kwargs)

2.21 to_grayscale(img, num_output_channels=1)

Convert an image to grayscale.

def to_grayscale(img, num_output_channels=1):
 """
 Args:
  img (PIL Image): Image to be converted to grayscale.

 Returns:
  PIL Image: 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
 """
 if not _is_pil_image(img):
  raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

 if num_output_channels == 1:
  img = ('L')
 elif num_output_channels == 3:
  img = ('L')
  np_img = (img, dtype=np.uint8)
  np_img = ([np_img, np_img, np_img])
  img = (np_img, 'RGB')
 else:
  raise ValueError('num_output_channels should be either 1 or 3')

 return img

Reference Links

 /

To this point, this collection of Pytorch image transformation function summary of the article is introduced to this, more related Pytorch image transformation function content, please search for my previous posts or continue to browse the following related articles I hope that you will support me in the future!