Data augmentation in computer vision

Open In Colab

Transforms to apply data augmentation in Computer Vision

  1. /usr/local/lib/python3.8/dist-packages/torch/cuda/__init__.py:52: UserWarning: CUDA initialization: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx (Triggered internally at /pytorch/c10/cuda/CUDAFunctions.cpp:100.)
  2. return torch._C._cuda_getDeviceCount() > 0
  1. img = PILImage(PILImage.create(TEST_IMAGE).resize((600,400)))

class RandTransform[source]

RandTransform(p=1.0, nm=None, before_call=None, **kwargs) :: DisplayedTransform

A transform that beforecall its state at each `_call`

As for all Transform you can pass encodes and decodes at init or subclass and implement them. You can do the same for the before_call method that is called at each __call__. Note that to have a consistent state for inputs and targets, a RandTransform must be applied at the tuple level.

By default the before_call behavior is to execute the transform with probability p (if subclassing and wanting to tweak that behavior, the attribute self.do, if it exists, is looked for to decide if the transform is executed or not).

Note: A RandTransform is only applied to the training set by default, so you have to pass split_idx=0 if you are calling it directly and not through a Datasets. That behavior can be changed by setting the attr split_idx of the transform to None.

RandTransform.before_call[source]

RandTransform.before_call(b, split_idx)

Set self.do based on self.p

  1. def _add1(x): return x+1
  2. dumb_tfm = RandTransform(enc=_add1, p=0.5)
  3. start,d1,d2 = 2,False,False
  4. for _ in range(40):
  5. t = dumb_tfm(start, split_idx=0)
  6. if dumb_tfm.do: test_eq(t, start+1); d1=True
  7. else: test_eq(t, start) ; d2=True
  8. assert d1 and d2
  9. dumb_tfm
  1. _add1 -- {'p': 0.5}:
  2. encodes: (object,object) -> _add1decodes:

Item transforms

class FlipItem[source]

FlipItem(p=0.5) :: RandTransform

Randomly flip with probability p

Calls @patch‘d flip_lr behaviors for Image, TensorImage, TensorPoint, and TensorBBox

  1. tflip = FlipItem(p=1.)
  2. test_eq(tflip(bbox,split_idx=0), tensor([[1.,0., 0.,1]]) -1)

class DihedralItem[source]

DihedralItem(p=1.0, nm=None, before_call=None, **kwargs) :: RandTransform

Randomly flip with probability p

Calls @patch‘d dihedral behaviors for PILImage, TensorImage, TensorPoint, and TensorBBox

By default each of the 8 dihedral transformations (including noop) have the same probability of being picked when the transform is applied. You can customize this behavior by passing your own draw function. To force a specific flip, you can also pass an integer between 0 and 7.

  1. _,axs = subplots(2, 4)
  2. for ax in axs.flatten():
  3. show_image(DihedralItem(p=1.)(img, split_idx=0), ctx=ax)

Data Augmentation - 图2

Resize with crop, pad or squish

class PadMode[source]

PadMode(*args, **kwargs)

All possible padding mode as attributes to get tab-completion and typo-proofing

class CropPad[source]

CropPad(size, pad_mode='zeros', **kwargs) :: DisplayedTransform

Center crop or pad an image to size

Calls @patch‘d crop_pad behaviors for Image, TensorImage, TensorPoint, and TensorBBox

  1. _,axs = plt.subplots(1,3,figsize=(12,4))
  2. for ax,sz in zip(axs.flatten(), [300, 500, 700]):
  3. show_image(img.crop_pad(sz), ctx=ax, title=f'Size {sz}');

Data Augmentation - 图3

  1. _,axs = plt.subplots(1,3,figsize=(12,4))
  2. for ax,mode in zip(axs.flatten(), [PadMode.Zeros, PadMode.Border, PadMode.Reflection]):
  3. show_image(img.crop_pad((600,700), pad_mode=mode), ctx=ax, title=mode);

Data Augmentation - 图4

class RandomCrop[source]

RandomCrop(size, **kwargs) :: RandTransform

Randomly crop an image to size

class OldRandomCrop[source]

OldRandomCrop(size, pad_mode='zeros', enc=None, dec=None, split_idx=None, order=None) :: CropPad

Randomly crop an image to size

  1. _,axs = plt.subplots(1,3,figsize=(12,4))
  2. f = RandomCrop(200)
  3. for ax in axs: show_image(f(img), ctx=ax);

Data Augmentation - 图5

On the validation set, we take a center crop.

  1. _,axs = plt.subplots(1,3,figsize=(12,4))
  2. for ax in axs: show_image(f(img, split_idx=1), ctx=ax);

Data Augmentation - 图6

class ResizeMethod[source]

ResizeMethod(*args, **kwargs)

All possible resize method as attributes to get tab-completion and typo-proofing

  1. test_eq(ResizeMethod.Squish, 'squish')

class Resize[source]

Resize(size, method='crop', pad_mode='reflection', resamples=(2, 0), **kwargs) :: RandTransform

A transform that beforecall its state at each `_call`

size can be an integer (in which case images will be resized to a square) or a tuple. Depending on the method:

  • we squish any rectangle to size
  • we resize so that the shorter dimension is a match an use padding with pad_mode
  • we resize so that the larger dimension is match and crop (randomly on the training set, center crop for the validation set)

When doing the resize, we use resamples[0] for images and resamples[1] for segmentation masks.

  1. _,axs = plt.subplots(1,3,figsize=(12,4))
  2. for ax,method in zip(axs.flatten(), [ResizeMethod.Squish, ResizeMethod.Pad, ResizeMethod.Crop]):
  3. rsz = Resize(256, method=method)
  4. show_image(rsz(img, split_idx=0), ctx=ax, title=method);

Data Augmentation - 图7

On the validation set, the crop is always a center crop (on the dimension that’s cropped).

  1. _,axs = plt.subplots(1,3,figsize=(12,4))
  2. for ax,method in zip(axs.flatten(), [ResizeMethod.Squish, ResizeMethod.Pad, ResizeMethod.Crop]):
  3. rsz = Resize(256, method=method)
  4. show_image(rsz(img, split_idx=1), ctx=ax, title=method);

Data Augmentation - 图8

class RandomResizedCrop[source]

RandomResizedCrop(size, min_scale=0.08, ratio=(0.75, 1.3333333333333333), resamples=(2, 0), val_xtra=0.14, max_scale=1.0, **kwargs) :: RandTransform

Picks a random scaled crop of an image and resize it to size

The crop picked as a random scale in range (min_scale,max_scale) and ratio in the range passed, then the resize is done with resamples[0] for images and resamples[1] for segmentation masks. On the validation set, we center crop the image if it’s ratio isn’t in the range (to the minmum or maximum value) then resize.

  1. crop = RandomResizedCrop(256)
  2. _,axs = plt.subplots(3,3,figsize=(9,9))
  3. for ax in axs.flatten():
  4. cropped = crop(img)
  5. show_image(cropped, ctx=ax);

Data Augmentation - 图9

  1. test_eq(cropped.shape, [256,256])

Squish is used on the validation set, removing val_xtra proportion of each side first.

  1. _,axs = subplots(1,3)
  2. for ax in axs.flatten(): show_image(crop(img, split_idx=1), ctx=ax);

Data Augmentation - 图10

By setting max_scale to lower values, one can enforce small crops.

  1. small_crop = RandomResizedCrop(256, min_scale=0.05, max_scale=0.15)
  2. _,axs = plt.subplots(3,3,figsize=(9,9))
  3. for ax in axs.flatten():
  4. cropped = small_crop(img)
  5. show_image(cropped, ctx=ax);

Data Augmentation - 图11

class RatioResize[source]

RatioResize(max_sz, resamples=(2, 0), **kwargs) :: DisplayedTransform

Resizes the biggest dimension of an image to max_sz maintaining the aspect ratio

  1. RatioResize(256)(img)

Data Augmentation - 图12

Affine and coord tfm on the GPU

  1. timg = TensorImage(array(img)).permute(2,0,1).float()/255.
  2. def _batch_ex(bs): return TensorImage(timg[None].expand(bs, *timg.shape).clone())

Uses coordinates in coords to map coordinates in x to new locations for transformations such as flip. Preferably use TensorImage.affine_coord as this combines _grid_sample with F.affine_grid for easier usage. UseF.affine_grid to make it easier to generate the coords, as this tends to be large [H,W,2] where H and W are the height and width of your image x.

This is the image we start with, and are going to be using for the following examples.

  1. img=torch.tensor([[[0,0,0],[1,0,0],[2,0,0]],
  2. [[0,1,0],[1,1,0],[2,1,0]],
  3. [[0,2,0],[1,2,0],[2,2,0]]]).permute(2,0,1)[None]/2.
  4. show_images(img)

Data Augmentation - 图13

Here we _grid_sample, but do not change the original image. Notice how the coordinates in grid map to the coordiants in img.

  1. grid=torch.tensor([[[[-1,-1],[0,-1],[1,-1]],
  2. [[-1,0],[0,0],[1,0]],
  3. [[-1,1],[0,1],[1,1.]]]])
  4. img=_grid_sample(img, grid,align_corners=True)
  5. show_images(img)

Data Augmentation - 图14

Next we do a flip by manually editing the grid.

  1. grid=torch.tensor([[[1.,-1],[0,-1],[-1,-1]],
  2. [[1,0],[0,0],[-1,0]],
  3. [[1,1],[0,1],[-1,1]]])
  4. img=_grid_sample(img, grid[None],align_corners=True)
  5. show_images(img)

Data Augmentation - 图15

Next we shift the image up by one. By drfault _grid_sample uses reflection padding.

  1. grid=torch.tensor([[[[-1,0],[0,0],[1,0]],
  2. [[-1,1],[0,1],[1,1]],
  3. [[-1,2],[0,2],[1,2.]]]])
  4. img=_grid_sample(img, grid,align_corners=True)
  5. show_images(img)

Data Augmentation - 图16

affine_coord allows us to much more easily work with images, by allowing us to specify much smaller mat, by comparison to grids, which require us to specify values for every pixel.

affine_grid[source]

affine_grid(theta, size, align_corners=None)

class AffineCoordTfm[source]

AffineCoordTfm(aff_fs=None, coord_fs=None, size=None, mode='bilinear', pad_mode='reflection', mode_mask='nearest', align_corners=None, **kwargs) :: RandTransform

Combine and apply affine and coord transforms

Calls @patch‘d affine_coord behaviors for TensorImage, TensorMask, TensorPoint, and TensorBBox

Multiplies all the matrices returned by aff_fs before doing the corresponding affine transformation on a basic grid corresponding to size, then applies all coord_fs on the resulting flow of coordinates before finally doing an interpolation with mode and pad_mode.

Here are examples of how to use affine_coord on images. Including the identity or original image, a flip, and moving the image to the left.

  1. imgs=_batch_ex(3)
  2. identity=torch.tensor([[1,0,0],[0,1,0.]])
  3. flip=torch.tensor([[-1,0,0],[0,1,0.]])
  4. translation=torch.tensor([[1,0,1.],[0,1,0]])
  5. mats=torch.stack((identity,flip,translation))
  6. show_images(imgs.affine_coord(mats,pad_mode=PadMode.Zeros)) #Zeros easiest to see

Data Augmentation - 图17

Now you may be asking, “What is this mat“? Well lets take a quick look at the identify below.

  1. imgs=_batch_ex(1)
  2. identity=torch.tensor([[1,0,0],[0,1,0.]])
  3. eye=identity[:,0:2]
  4. bi=identity[:,2:3]
  5. eye,bi
  1. (tensor([[1., 0.],
  2. [0., 1.]]),
  3. tensor([[0.],
  4. [0.]]))

Notice the the tensor ‘eye’ is an identity matrix. If we multiply this by a single coordinate in our original image x,y we will simply the same values returned for x and y. bi is added after this multiplication. For example, lets flip the image so the left top corner is in the right top corner:

  1. t=torch.tensor([[-1,0,0],[0,1,0.]])
  2. eye=t[:,0:2]
  3. bi=t[:,2:3]
  4. xy=torch.tensor([-1.,-1]) #upper left corner
  5. torch.sum(xy*eye,dim=1)+bi[0] #now the upper right corner
  1. tensor([ 1., -1.])

AffineCoordTfm.compose[source]

AffineCoordTfm.compose(tfm)

Compose self with another AffineCoordTfm to only do the interpolation step once

class RandomResizedCropGPU[source]

RandomResizedCropGPU(size, min_scale=0.08, ratio=(0.75, 1.3333333333333333), mode='bilinear', valid_scale=1.0, max_scale=1.0, **kwargs) :: RandTransform

Picks a random scaled crop of an image and resize it to size

  1. t = _batch_ex(8)
  2. rrc = RandomResizedCropGPU(224, p=1.)
  3. y = rrc(t)
  4. _,axs = plt.subplots(2,4, figsize=(12,6))
  5. for ax in axs.flatten():
  6. show_image(y[i], ctx=ax)

Data Augmentation - 图18

Note: RandomResizedCropGPU uses the same region for all images in the batch.

GPU helpers

This section contain helpers for working with augmentations on GPUs that is used throughout the code.

mask_tensor[source]

mask_tensor(x, p=0.5, neutral=0.0, batch=False)

Mask elements of x with neutral with probability 1-p

Lets look at some examples of how [`mask_tensor`](/vision.augment.html#mask_tensor) might be used, we are using clone() because this operation overwrites the input. For this example lets try using degrees for rotating an image.

  1. with no_random():
  2. x=torch.tensor([60,-30,90,-210,270,-180,120,-240,150])
  3. print('p=0.5: ',mask_tensor(x.clone()))
  4. print('p=1.0: ',mask_tensor(x.clone(),p=1.))
  5. print('p=0.0: ',mask_tensor(x.clone(),p=0.))
  1. p=0.5: tensor([ 0, 0, 90, -210, 270, -180, 120, 0, 150])
  2. p=1.0: tensor([ 60, -30, 90, -210, 270, -180, 120, -240, 150])
  3. p=0.0: tensor([0, 0, 0, 0, 0, 0, 0, 0, 0])

Notice how p controls how likely a value is expected to be replaced with 0, or be unchanged since a 0 degree rotation would just be the original image. batch acts on the entire batch instead of single elements of the batch. Now lets consider a different example, of working with brightness. Note: with brightness 0 is a completely black image.

  1. x=torch.tensor([0.6,0.4,0.3,0.7,0.4])
  2. print('p=0.: ',mask_tensor(x.clone(),p=0))
  3. print('p=0.,neutral=0.5: ',mask_tensor(x.clone(),p=0,neutral=0.5))
  1. p=0.: tensor([0., 0., 0., 0., 0.])
  2. p=0.,neutral=0.5: tensor([0.5000, 0.5000, 0.5000, 0.5000, 0.5000])

Here is would be very bad if we had a completely black image, as that is not an unchanged image. Instead we set neutral to 0.5 which is the value for an unchanged image for brightness.

_draw_mask is used to support the api of many following transformations to create [`mask_tensor`](/vision.augment.html#mask_tensor)s. (p, neutral, batch) are passed down to [`mask_tensor`](/vision.augment.html#mask_tensor). def_draw is the default draw function, and what should happen if no custom user setting is provided. draw is user defined behavior and can be a function, list of floats, or a float. draw and def_draw must return a tensor.

Here we use random integers from 1 to 8 for our def_draw, this example is very similar to [`Dihedral`](/vision.augment.html#Dihedral).

  1. x = torch.zeros(10,2,3)
  2. def def_draw(x):
  3. x=torch.randint(1,8, (x.size(0),))
  4. return x
  5. with no_random(): print(torch.randint(1,8, (x.size(0),)))
  6. with no_random(): print(_draw_mask(x, def_draw))
  1. tensor([2, 3, 5, 6, 5, 4, 6, 6, 1, 1])
  2. TensorBase([2, 0, 0, 0, 0, 4, 0, 0, 0, 0])

Next, there are three ways to define draw, as a constant, as a list, and as a function. All of these override def_draw, so that it has no effect on the final result.

  1. with no_random():
  2. print('const: ',_draw_mask(x, def_draw, draw=1))
  3. print('list : ', _draw_mask(x, def_draw, draw=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
  4. print('list : ',_draw_mask(x[0:2], def_draw, draw=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]))
  5. print('funct: ',_draw_mask(x, def_draw, draw=lambda x: torch.arange(1,x.size(0)+1)))
  6. try:
  7. _draw_mask(x, def_draw, draw=[1,2])
  8. except AssertionError as e:
  9. print(type(e),'n',e)
  1. const: TensorBase([0., 0., 1., 1., 1., 1., 1., 0., 1., 0.])
  2. list : TensorBase([0., 0., 0., 4., 0., 0., 7., 0., 9., 0.])
  3. list : TensorBase([0., 2.])
  4. funct: TensorBase([1, 0, 3, 0, 5, 0, 7, 0, 9, 0])
  5. <class 'AssertionError'>

Note, when using a list it can be larger than the batch size, but it cannot be smaller than the batch size. Otherwise there would not be enough augmentations for elements of the batch.

  1. x = torch.zeros(5,2,3)
  2. def_draw = lambda x: torch.randint(0,8, (x.size(0),))
  3. t = _draw_mask(x, def_draw)
  4. assert (0. <= t).all() and (t <= 7).all()
  5. t = _draw_mask(x, def_draw, 1)
  6. assert (0. <= t).all() and (t <= 1).all()
  7. test_eq(_draw_mask(x, def_draw, 1, p=1), tensor([1.,1,1,1,1]))
  8. test_eq(_draw_mask(x, def_draw, [0,1,2,3,4], p=1), tensor([0.,1,2,3,4]))
  9. test_eq(_draw_mask(x[0:3], def_draw, [0,1,2,3,4], p=1), tensor([0.,1,2]))
  10. for i in range(5):
  11. t = _draw_mask(x, def_draw, 1,batch=True)
  12. assert (t==torch.zeros(5)).all() or (t==torch.ones(5)).all()

Flip/Dihedral GPU Helpers

affine_mat is used to transform the length-6 vestor into a [bs,3,3] tensor. This is used to allow us to combine affine transforms.

affine_mat[source]

affine_mat(*ms)

Restructure length-6 vector ms into an affine matrix with 0,0,1 in the last line

Here is an example of how flipping an image would look using affine_mat.

  1. flips=torch.tensor([-1,1,-1])
  2. ones=t1(flips)
  3. zeroes=t0(flips)
  4. affines=affine_mat(flips,zeroes,zeroes,zeroes,ones,zeroes)
  5. print(affines)
  1. tensor([[[-1, 0, 0],
  2. [ 0, 1, 0],
  3. [ 0, 0, 1]],
  4. [[ 1, 0, 0],
  5. [ 0, 1, 0],
  6. [ 0, 0, 1]],
  7. [[-1, 0, 0],
  8. [ 0, 1, 0],
  9. [ 0, 0, 1]]])

This is done so that we can combine multiple affine transformations without doing the math on the entire image. We need the matrices to be the same size, so we can do a matric multiple in order to combines affine transformations. While this is usually done on and entire batch, here is what it would look like to have multiple flip transformations for a single image. Since we flip twice we end up with an affine matrix that would simply return our original image.

If you would like more information on how this works, see affine_coord.

  1. x = torch.eye(3,dtype=torch.int64)
  2. for affine in affines:
  3. x @= affine
  4. print(x)
  1. tensor([[-1, 0, 0],
  2. [ 0, 1, 0],
  3. [ 0, 0, 1]])
  4. tensor([[-1, 0, 0],
  5. [ 0, 1, 0],
  6. [ 0, 0, 1]])
  7. tensor([[1, 0, 0],
  8. [0, 1, 0],
  9. [0, 0, 1]])

flip_mat will generate a [bs,3,3] tensor representing our flips for a batch with probability p. draw can be used to define a function, constant, or list that defines what flips to use. If draw is a list, the length must be greater than or equal to the batch size. For draw 0 is the original image, or 1 is a flipped image. batch will mean that the entire batch will be flipped or not.

flip_mat[source]

flip_mat(x, p=0.5, draw=None, batch=False)

Return a random flip matrix

Below are some examples of how to use draw as a constant, list and function.

  1. with no_random():
  2. x=torch.randn(2,4,3)
  3. print('const: ',flip_mat(x, draw=1))
  4. print('list : ', flip_mat(x, draw=[1, 0]))
  5. print('list : ',flip_mat(x[0:2], draw=[1, 0, 1, 0, 1]))
  6. print('funct: ',flip_mat(x, draw=lambda x: torch.ones(x.size(0))))
  7. test_fail(lambda: flip_mat(x, draw=[1]))
  1. const: TensorBase([[[-1., 0., 0.],
  2. [ 0., 1., 0.],
  3. [ 0., 0., 1.]],
  4. [[-1., 0., 0.],
  5. [ 0., 1., 0.],
  6. [ 0., 0., 1.]]])
  7. list : TensorBase([[[1., 0., 0.],
  8. [0., 1., 0.],
  9. [0., 0., 1.]],
  10. [[1., 0., 0.],
  11. [0., 1., 0.],
  12. [0., 0., 1.]]])
  13. list : TensorBase([[[-1., 0., 0.],
  14. [ 0., 1., 0.],
  15. [ 0., 0., 1.]],
  16. [[ 1., 0., 0.],
  17. [ 0., 1., 0.],
  18. [ 0., 0., 1.]]])
  19. funct: TensorBase([[[-1., 0., 0.],
  20. [ 0., 1., 0.],
  21. [ 0., 0., 1.]],
  22. [[ 1., 0., 0.],
  23. [ 0., 1., 0.],
  24. [ 0., 0., 1.]]])
  1. x = flip_mat(torch.randn(100,4,3))
  2. test_eq(set(x[:,0,0].numpy()), {-1,1}) #might fail with probability 2*2**(-100) (picked only 1s or -1s)

Flip images,masks,points and bounding boxes horizontally. p is the probability of a flip being applied. draw can be used to define custom flip behavior.

class Flip[source]

Flip(p=0.5, draw=None, size=None, mode='bilinear', pad_mode='reflection', align_corners=True, batch=False) :: AffineCoordTfm

Randomly flip a batch of images with a probability p

Calls @patch‘d flip_batch behaviors for TensorImage, TensorMask, TensorPoint, and TensorBBox

Here are some examples of using flip. Notice that a constant draw=1, is effectively the same as the default settings. Also notice the fine-tune control we can get in the third example, by setting p=1. and defining a custom draw.

  1. with no_random(32):
  2. imgs = _batch_ex(5)
  3. deflt = Flip()
  4. const = Flip(p=1.,draw=1) #same as default
  5. listy = Flip(p=1.,draw=[1,0,1,0,1]) #completely manual!!!
  6. funct = Flip(draw=lambda x: torch.ones(x.size(0))) #same as default
  7. show_images( deflt(imgs) ,suptitle='Default Flip')
  8. show_images( const(imgs) ,suptitle='Constant Flip',titles=[f'Flipped' for i in['','','','','']]) #same above
  9. show_images( listy(imgs) ,suptitle='Listy Flip',titles=[f'{i}Flipped' for i in ['','Not ','','Not ','']])
  10. show_images( funct(imgs) ,suptitle='Flip By Function') #same as default

Data Augmentation - 图19

Data Augmentation - 图20

Data Augmentation - 图21

Data Augmentation - 图22

  1. flip = Flip(p=1.)
  2. t = _pnt2tensor([[1,0], [2,1]], (3,3))
  3. y = flip(TensorImage(t[None,None]), split_idx=0)
  4. test_eq(y, _pnt2tensor([[1,0], [0,1]], (3,3))[None,None])
  5. pnts = TensorPoint((tensor([[1.,0.], [2,1]]) -1)[None])
  6. test_eq(flip(pnts, split_idx=0), tensor([[[1.,0.], [0,1]]]) -1)
  7. bbox = TensorBBox(((tensor([[1.,0., 2.,1]]) -1)[None]))
  8. test_eq(flip(bbox, split_idx=0), tensor([[[0.,0., 1.,1.]]]) -1)

class DeterministicDraw[source]

DeterministicDraw(vals)

  1. t = _batch_ex(8)
  2. draw = DeterministicDraw(list(range(8)))
  3. for i in range(15): test_eq(draw(t), torch.zeros(8)+(i%8))

class DeterministicFlip[source]

DeterministicFlip(size=None, mode='bilinear', pad_mode='reflection', align_corners=True, **kwargs) :: Flip

Flip the batch every other call

  1. dih = DeterministicFlip({'p':.3})

Next we loop through multiple batches of the example images. DeterministicFlip will first not flip the images, and then on the next batch it will flip the images.

  1. b = _batch_ex(2)
  2. dih = DeterministicFlip()
  3. for i,flipped in enumerate(['Not Flipped','Flipped']*2):
  4. show_images(dih(b),suptitle=f'Batch {i}',titles=[flipped]*2)

Data Augmentation - 图23

Data Augmentation - 图24

Data Augmentation - 图25

Data Augmentation - 图26

Since we are working with squares and rectangles, we can think of dihedral flips as flips across the horizontal, vertical, and diagonal and their combinations. Remember though that rectangles are not symmetrical across their diagonal, so this will effectively cropping parts of rectangles.

dihedral_mat[source]

dihedral_mat(x, p=0.5, draw=None, batch=False)

Return a random dihedral matrix

class Dihedral[source]

Dihedral(p=0.5, draw=None, size=None, mode='bilinear', pad_mode='reflection', align_corners=None, batch=False) :: AffineCoordTfm

Apply a random dihedral transformation to a batch of images with a probability p

Calls @patch‘d dihedral_batch behaviors for TensorImage, TensorMask, TensorPoint, and TensorBBox

draw can be specified if you want to customize which flip is picked when the transform is applied (default is a random number between 0 and 7). It can be an integer between 0 and 7, a list of such integers (which then should have a length equal to or greater than the size of the batch) or a callable that returns a long tensor between 0 and 7.

  1. with no_random():
  2. imgs = _batch_ex(5)
  3. deflt = Dihedral()
  4. const = Dihedral(p=1.,draw=1) #same as flip_batch
  5. listy = Dihedral(p=1.,draw=[0,1,2,3,4]) #completely manual!!!
  6. funct = Dihedral(draw=lambda x: torch.randint(0,8,(x.size(0),))) #same as default
  7. show_images( deflt(imgs) ,suptitle='Default Flips',titles=[i for i in range(imgs.size(0))])
  8. show_images( const(imgs) ,suptitle='Constant Horizontal Flip',titles=[f'Flip 1' for i in [0,1,1,1,1]])
  9. show_images( listy(imgs) ,suptitle='Manual Listy Flips',titles=[f'Flip {i}' for i in [0,1,2,3,4]]) #manually specified, not random!
  10. show_images( funct(imgs) ,suptitle='Default Functional Flips',titles=[i for i in range(imgs.size(0))]) #same as default

Data Augmentation - 图27

Data Augmentation - 图28

Data Augmentation - 图29

Data Augmentation - 图30

class DeterministicDihedral[source]

DeterministicDihedral(size=None, mode='bilinear', pad_mode='reflection', align_corners=None) :: Dihedral

Apply a random dihedral transformation to a batch of images with a probability p

DeterministicDihedral guarantees that the first call will not be flipped, then the following call will be flip in a deterministic order. After all 7 possible dihedral flips the pattern will reset to the unflipped version. If we were to do this on a batch size of one it would look like this:

  1. t = _batch_ex(10)
  2. dih = DeterministicDihedral()
  3. _,axs = plt.subplots(2,5, figsize=(14,6))
  4. for i,ax in enumerate(axs.flatten()):
  5. y = dih(t)
  6. show_image(y[0], ctx=ax, title=f'Batch {i}')

Data Augmentation - 图31

rotate_mat[source]

rotate_mat(x, max_deg=10, p=0.5, draw=None, batch=False)

Return a random rotation matrix with max_deg and p

class Rotate[source]

Rotate(max_deg=10, p=0.5, draw=None, size=None, mode='bilinear', pad_mode='reflection', align_corners=True, batch=False) :: AffineCoordTfm

Apply a random rotation of at most max_deg with probability p to a batch of images

Calls @patch‘d rotate behaviors for TensorImage, TensorMask, TensorPoint, and TensorBBox

draw can be specified if you want to customize which angle is picked when the transform is applied (default is a random flaot between -max_deg and max_deg). It can be a float, a list of floats (which then should have a length equal to or greater than the size of the batch) or a callable that returns a float tensor.

Rotate by default can only rotate 10 degrees, which makes the changes harder to see. This is usually combined with either flip or dihedral, which make much larger changes by default. A rotate of 180 degrees is the same as a vertical flip for example.

  1. with no_random():
  2. thetas = [-30,-15,0,15,30]
  3. imgs = _batch_ex(5)
  4. deflt = Rotate()
  5. const = Rotate(p=1.,draw=180) #same as a vertical flip
  6. listy = Rotate(p=1.,draw=[-30,-15,0,15,30]) #completely manual!!!
  7. funct = Rotate(draw=lambda x: x.new_empty(x.size(0)).uniform_(-10, 10)) #same as default
  8. show_images( deflt(imgs) ,suptitle='Default Rotate, notice the small rotation',titles=[i for i in range(imgs.size(0))])
  9. show_images( const(imgs) ,suptitle='Constant 180 Rotate',titles=[f'180 Degrees' for i in range(imgs.size(0))])
  10. #manually specified, not random!
  11. show_images( listy(imgs) ,suptitle='Manual List Rotate',titles=[f'{i} Degrees' for i in [-30,-15,0,15,30]])
  12. #same as default
  13. show_images( funct(imgs) ,suptitle='Default Functional Rotate',titles=[i for i in range(imgs.size(0))])

Data Augmentation - 图32

Data Augmentation - 图33

Data Augmentation - 图34

Data Augmentation - 图35

zoom_mat[source]

zoom_mat(x, min_zoom=1.0, max_zoom=1.1, p=0.5, draw=None, draw_x=None, draw_y=None, batch=False)

Return a random zoom matrix with max_zoom and p

class Zoom[source]

Zoom(min_zoom=1.0, max_zoom=1.1, p=0.5, draw=None, draw_x=None, draw_y=None, size=None, mode='bilinear', pad_mode='reflection', batch=False, align_corners=True) :: AffineCoordTfm

Apply a random zoom of at most max_zoom with probability p to a batch of images

Calls @patch‘d zoom behaviors for TensorImage, TensorMask, TensorPoint, and TensorBBox

draw, draw_x and draw_y can be specified if you want to customize which scale and center are picked when the transform is applied (default is a random float between 1 and max_zoom for the first, between 0 and 1 for the last two). Each can be a float, a list of floats (which then should have a length equal to or greater than the size of the batch) or a callable that returns a float tensor.

draw_x and draw_y are expected to be the position of the center in pct, 0 meaning the most left/top possible and 1 meaning the most right/bottom possible.

Note: By default Zooms are rather small.

  1. with no_random():
  2. scales = [0.8, 1., 1.1, 1.25, 1.5]
  3. imgs = _batch_ex(5)
  4. deflt = Zoom()
  5. const = Zoom(p=1., draw=1.5) #'Constant scale and different random centers'
  6. listy = Zoom(p=1.,draw=scales,draw_x=0.5, draw_y=0.5) #completely manual scales, constant center
  7. funct = Zoom(draw=lambda x: x.new_empty(x.size(0)).uniform_(1., 1.1)) #same as default
  8. show_images( deflt(imgs) ,suptitle='Default Zoom, note the small zooming', titles=[i for i in range(imgs.size(0))])
  9. show_images( const(imgs) ,suptitle='Constant Scale, Valiable Position', titles=[f'Scale 1.5x' for i in range(imgs.size(0))])
  10. show_images( listy(imgs) ,suptitle='Manual Listy Scale, Centered', titles=[f'Scale {i}x' for i in scales])
  11. show_images( funct(imgs) ,suptitle='Default Functional Zoom', titles=[i for i in range(imgs.size(0))]) #same as default

Data Augmentation - 图36

Data Augmentation - 图37

Data Augmentation - 图38

Data Augmentation - 图39

Warping

find_coeffs[source]

find_coeffs(p1, p2)

Find coefficients for warp tfm from p1 to p2

apply_perspective[source]

apply_perspective(coords, coeffs)

Apply perspective tranfom on coords with coeffs

class Warp[source]

Warp(magnitude=0.2, p=0.5, draw_x=None, draw_y=None, size=None, mode='bilinear', pad_mode='reflection', batch=False, align_corners=True) :: AffineCoordTfm

Apply perspective warping with magnitude and p on a batch of matrices

Calls @patch‘d warp behaviors for TensorImage, TensorMask, TensorPoint, and TensorBBox

draw_x and draw_y can be specified if you want to customize the magnitudes that are picked when the transform is applied (default is a random float between -magnitude and magnitude. Each can be a float, a list of floats (which then should have a length equal to or greater than the size of the batch) or a callable that returns a float tensor.

  1. scales = [-0.4, -0.2, 0., 0.2, 0.4]
  2. imgs=_batch_ex(5)
  3. vert_warp = Warp(p=1., draw_y=scales, draw_x=0.)
  4. horz_warp = Warp(p=1., draw_x=scales, draw_y=0.)
  5. show_images( vert_warp(imgs) ,suptitle='Vertical warping', titles=[f'magnitude {i}' for i in scales])
  6. show_images( horz_warp(imgs) ,suptitle='Horizontal warping', titles=[f'magnitude {i}' for i in scales])

Data Augmentation - 图40

Data Augmentation - 图41

Lighting transforms

Lighting transforms are transforms that effect how light is represented in an image. These don’t change the location of the object like previous transforms, but instead simulate how light could change in a scene. The simclr paper evaluates these transforms against other transforms for their use case of self-supurved image classification, note they use “color” and “color distortion” to refer to a combination of these transforms.

TensorImage.lighting[source]

TensorImage.lighting(x:TensorImage, func)

Most lighting transforms work better in “logit space”, as we do not want to blowout the image by going over maximum or minimum brightness. Taking the sigmoid of the logit allows us to get back to “linear space.”

  1. x=TensorImage(torch.tensor([.01* i for i in range(0,101)]))
  2. f_lin= lambda x:(2*(x-0.5)+0.5).clamp(0,1) #blue line
  3. f_log= lambda x:2*x #red line
  4. plt.plot(x,f_lin(x),'b',x,x.lighting(f_log),'r');

Data Augmentation - 图42

The above graph shows the results of doing a contrast transformation in both linear and logit space. Notice how the blue linear plot has to be clamped, and we have lost information on how large 0.0 is by comparision to 0.2. While in the red plot the values curve, so we keep this relative information.

First we create a general SpaceTfm. This allows us compose multiple transforms together, so that we only have to convert to a space once, before doing multiple transforms. The space_fn must convert from rgb to a space, apply a function, and then convert back to rgb. fs should be list-like, and contain a functions that will be composed together.

class SpaceTfm[source]

SpaceTfm(fs, space_fn, **kwargs) :: RandTransform

Apply fs to the logits

LightingTfm is a SpaceTfm that uses TensorImage.lighting to convert to logit space. Use this to limit images loosing detail when they become very dark or bright.

class LightingTfm[source]

LightingTfm(fs, **kwargs) :: SpaceTfm

Apply fs to the logits

Brightness refers to the amount of light on a scene. This can be zero in which the image is completely black or one where the image is completely white. This may be especially useful if you expect your dataset to have over or under exposed images.

class Brightness[source]

Brightness(max_lighting=0.2, p=0.75, draw=None, batch=False) :: LightingTfm

Apply fs to the logits

Calls @patch‘d brightness behaviors for TensorImage

draw can be specified if you want to customize the magnitude that is picked when the transform is applied (default is a random float between -0.5*(1-max_lighting) and 0.5*(1+max_lighting). Each can be a float, a list of floats (which then should have a length equal to or greater than the size of the batch) or a callable that returns a float tensor.

  1. scales = [0.1, 0.3, 0.5, 0.7, 0.9]
  2. y = _batch_ex(5).brightness(draw=scales, p=1.)
  3. fig,axs = plt.subplots(1,5, figsize=(15,3))
  4. for i,ax in enumerate(axs.flatten()):
  5. show_image(y[i], ctx=ax, title=f'scale {scales[i]}')

Data Augmentation - 图43

Contrast pushes pixels to either the maximum or minimum values. The minimum value for contrast is a solid gray image. As an example take a picture of a bright light source in a dark room. Your eyes should be able to see some detail in the room, but the photo taken should instead have much higher contrast, with all of the detail in the background missing to the darkness. This is one example of what this transform can help simulate.

class Contrast[source]

Contrast(max_lighting=0.2, p=0.75, draw=None, batch=False) :: LightingTfm

Apply change in contrast of max_lighting to batch of images with probability p.

Calls @patch‘d contrast behaviors for TensorImage

draw can be specified if you want to customize the magnitude that is picked when the transform is applied (default is a random float taken with the log uniform distribution between (1-max_lighting) and 1/(1-max_lighting). Each can be a float, a list of floats (which then should have a length equal to or greater than the size of the batch) or a callable that returns a float tensor.

  1. scales = [0.65, 0.8, 1., 1.25, 1.55]
  2. y = _batch_ex(5).contrast(p=1., draw=scales)
  3. fig,axs = plt.subplots(1,5, figsize=(15,3))
  4. for i,ax in enumerate(axs.flatten()): show_image(y[i], ctx=ax, title=f'scale {scales[i]}')

Data Augmentation - 图44

grayscale[source]

grayscale(x)

Tensor to grayscale tensor. Uses the ITU-R 601-2 luma transform.

The above is just one way to convert to grayscale. We chose this one because it was fast. Notice that the sum of the weight of each channel is 1.

  1. f'{sum([0.2989,0.5870,0.1140]):.3f}'
  1. '1.000'

class Saturation[source]

Saturation(max_lighting=0.2, p=0.75, draw=None, batch=False) :: LightingTfm

Apply change in saturation of max_lighting to batch of images with probability p.

Calls @patch‘d saturation behaviors for TensorImage

  1. scales = [0., 0.5, 1., 1.5, 2.0]
  2. y = _batch_ex(5).saturation(p=1., draw=scales)
  3. fig,axs = plt.subplots(1,5, figsize=(15,3))
  4. for i,ax in enumerate(axs.flatten()): show_image(y[i], ctx=ax, title=f'scale {scales[i]}')

Data Augmentation - 图45

Saturation controls the amount of color in the image, but not the lightness or darkness of an image. If has no effect on neutral colors such as whites,grays and blacks. At zero saturation you actually get a grayscale image. Pushing saturation past one causes more neutral colors to take on any underlying chromatic color.

rgb2hsv, and hsv2rgb are utilities for converting to and from hsv space. Hsv space stands for hue,saturation, and value space. This allows us to more easily perform certain transforms.

  1. torch.max(tensor([1]).as_subclass(TensorBase), dim=0)
  1. (TensorBase(1), TensorBase(0))

rgb2hsv[source]

rgb2hsv(img)

Converts a RGB image to an HSV image. Note: Will not work on logit space images.

hsv2rgb[source]

hsv2rgb(img)

Converts a HSV image to an RGB image.

Very similar to lighting which is done in logit space, hsv transforms are done in hsv space. We can compose any transforms that are done in hsv space.

class HSVTfm[source]

HSVTfm(fs, **kwargs) :: SpaceTfm

Apply fs to the images in HSV space

Calls @patch‘d hsv behaviors for TensorImage

  1. fig,axs=plt.subplots(figsize=(20, 4),ncols=5)
  2. axs[0].set_ylabel('Hue')
  3. for ax in axs:
  4. ax.set_xlabel('Saturation')
  5. ax.set_yticklabels([])
  6. ax.set_xticklabels([])
  7. hsvs=torch.stack([torch.arange(0,2.1,0.01)[:,None].repeat(1,210),
  8. torch.arange(0,1.05,0.005)[None].repeat(210,1),
  9. torch.ones([210,210])])[None]
  10. for ax,i in zip(axs,range(0,5)):
  11. if i>0: hsvs[:,2].mul_(0.80)
  12. ax.set_title('V='+'%.1f' %0.8**i)
  13. ax.imshow(hsv2rgb(hsvs)[0].permute(1,2,0))

Data Augmentation - 图46

For the Hue transform we are using hsv space instead of logit space. HSV stands for hue,saturation and value. Hue in hsv space just cycles through colors of the rainbow. Notices how there is no maximum, because the colors just repeat.

Above are some examples of Hue(H) and Saturation(S) at various Values(V). One property of note in HSV space is that V controls the color you get at minimum saturation when in HSV space.

class Hue[source]

Hue(max_hue=0.1, p=0.75, draw=None, batch=False) :: HSVTfm

Apply change in hue of max_hue to batch of images with probability p.

Calls @patch‘d hue behaviors for TensorImage

  1. scales = [0.5, 0.75, 1., 1.5, 1.75]
  2. y = _batch_ex(len(scales)).hue(p=1., draw=scales)
  3. fig,axs = plt.subplots(1,len(scales), figsize=(15,3))
  4. for i,ax in enumerate(axs.flatten()): show_image(y[i], ctx=ax, title=f'scale {scales[i]}')

Data Augmentation - 图47

RandomErasing

Random Erasing Data Augmentation. This variant, designed by Ross Wightman, is applied to either a batch or single image tensor after it has been normalized.

cutout_gaussian[source]

cutout_gaussian(x, areas)

Replace all areas in x with N(0,1) noise

Since this should be applied after normalization, we’ll define a helper to apply a function inside normalization.

norm_apply_denorm[source]

norm_apply_denorm(x, f, nrm)

Normalize x with nrm, then apply f, then denormalize

  1. nrm = Normalize.from_stats(*imagenet_stats, cuda=False)
  1. f = partial(cutout_gaussian, areas=[(100,200,100,200),(200,300,200,300)])
  2. show_image(norm_apply_denorm(timg, f, nrm)[0]);

Data Augmentation - 图48

class RandomErasing[source]

RandomErasing(p=0.5, sl=0.0, sh=0.3, min_aspect=0.3, max_count=1) :: RandTransform

Randomly selects a rectangle region in an image and randomizes its pixels.

Args:

  • p: The probability that the Random Erasing operation will be performed
  • sl: Minimum proportion of erased area
  • sh: Maximum proportion of erased area
  • min_aspect: Minimum aspect ratio of erased area
  • max_count: maximum number of erasing blocks per image, area per box is scaled by count
  1. tfm = RandomErasing(p=1., max_count=6)
  2. _,axs = subplots(2,3, figsize=(12,6))
  3. f = partial(tfm, split_idx=0)
  4. for i,ax in enumerate(axs.flatten()): show_image(norm_apply_denorm(timg, f, nrm)[0], ctx=ax)

Data Augmentation - 图49

  1. y = _batch_ex(6)
  2. _,axs = plt.subplots(2,3, figsize=(12,6))
  3. y = norm_apply_denorm(y, f, nrm)
  4. for i,ax in enumerate(axs.flatten()): show_image(y[i], ctx=ax)

Data Augmentation - 图50

  1. tfm = RandomErasing(p=1., max_count=6)
  2. _,axs = subplots(2,3, figsize=(12,6))
  3. f = partial(tfm, split_idx=1)
  4. for i,ax in enumerate(axs.flatten()): show_image(norm_apply_denorm(timg, f, nrm)[0], ctx=ax)

Data Augmentation - 图51

All together

setup_aug_tfms[source]

setup_aug_tfms(tfms)

Go through tfms and combines together affine/coord or lighting transforms

  1. tfms = [Rotate(draw=10., p=1), Zoom(draw=1.1, draw_x=0.5, draw_y=0.5, p=1.)]
  2. comp = setup_aug_tfms([Rotate(draw=10., p=1), Zoom(draw=1.1, draw_x=0.5, draw_y=0.5, p=1.)])
  3. test_eq(len(comp), 1)
  4. x = torch.randn(4,3,5,5)
  5. test_close(comp[0]._get_affine_mat(x)[...,:2],tfms[0]._get_affine_mat(x)[...,:2] @ tfms[1]._get_affine_mat(x)[...,:2])
  6. #We can't test that the ouput of comp or the composition of tfms on x is the same cause it's not (1 interpol vs 2 sp)
  1. tfms = [Rotate(), Zoom(), Warp(), Brightness(), Flip(), Contrast()]
  2. comp = setup_aug_tfms(tfms)
  1. aff_tfm,lig_tfm = comp
  2. test_eq(len(aff_tfm.aff_fs+aff_tfm.coord_fs+comp[1].fs), 6)
  3. test_eq(len(aff_tfm.aff_fs), 3)
  4. test_eq(len(aff_tfm.coord_fs), 1)
  5. test_eq(len(lig_tfm.fs), 2)

aug_transforms[source]

aug_transforms(mult=1.0, do_flip=True, flip_vert=False, max_rotate=10.0, min_zoom=1.0, max_zoom=1.1, max_lighting=0.2, max_warp=0.2, p_affine=0.75, p_lighting=0.75, xtra_tfms=None, size=None, mode='bilinear', pad_mode='reflection', align_corners=True, batch=False, min_scale=1.0)

Utility func to easily create a list of flip, rotate, zoom, warp, lighting transforms.

Random flip (or dihedral if flip_vert=True) with p=0.5 is added when do_flip=True. With p_affine we apply a random rotation of max_rotate degrees, a random zoom between min_zoom and max_zoom and a perspective warping of max_warp. With p_lighting we apply a change in brightness and contrast of max_lighting. Custon xtra_tfms can be added. size, mode and pad_mode will be used for the interpolation. max_rotate,max_lighting,max_warp are multiplied by mult so you can more easily increase or decrease augmentation with a single parameter.

  1. tfms = aug_transforms(pad_mode='zeros', mult=2, min_scale=0.5)
  2. y = _batch_ex(9)
  3. for t in tfms: y = t(y, split_idx=0)
  4. _,axs = plt.subplots(1,3, figsize=(12,3))
  5. for i,ax in enumerate(axs.flatten()): show_image(y[i], ctx=ax)

Data Augmentation - 图52

  1. tfms = aug_transforms(pad_mode='zeros', mult=2, batch=True)
  2. y = _batch_ex(9)
  3. for t in tfms: y = t(y, split_idx=0)
  4. _,axs = plt.subplots(1,3, figsize=(12,3))
  5. for i,ax in enumerate(axs.flatten()): show_image(y[i], ctx=ax)

Data Augmentation - 图53

Integration tests

Segmentation

  1. camvid = untar_data(URLs.CAMVID_TINY)
  2. fns = get_image_files(camvid/'images')
  3. cam_fn = fns[0]
  4. mask_fn = camvid/'labels'/f'{cam_fn.stem}_P{cam_fn.suffix}'
  5. def _cam_lbl(fn): return mask_fn
  1. cam_dsrc = Datasets([cam_fn]*10, [PILImage.create, [_cam_lbl, PILMask.create]])
  2. cam_tdl = TfmdDL(cam_dsrc.train, after_item=ToTensor(),
  3. after_batch=[IntToFloatTensor(), *aug_transforms()], bs=9)
  4. cam_tdl.show_batch(max_n=9, vmin=1, vmax=30)

Data Augmentation - 图54

Point targets

  1. mnist = untar_data(URLs.MNIST_TINY)
  2. mnist_fn = 'images/mnist3.png'
  3. pnts = np.array([[0,0], [0,35], [28,0], [28,35], [9, 17]])
  4. def _pnt_lbl(fn)->None: return TensorPoint.create(pnts)
  1. pnt_dsrc = Datasets([mnist_fn]*10, [[PILImage.create, Resize((35,28))], _pnt_lbl])
  2. pnt_tdl = TfmdDL(pnt_dsrc.train, after_item=[PointScaler(), ToTensor()],
  3. after_batch=[IntToFloatTensor(), *aug_transforms(max_warp=0)], bs=9)
  4. pnt_tdl.show_batch(max_n=9)

Data Augmentation - 图55

Bounding boxes

  1. coco = untar_data(URLs.COCO_TINY)
  2. images, lbl_bbox = get_annotations(coco/'train.json')
  3. idx=2
  4. coco_fn,bbox = coco/'train'/images[idx],lbl_bbox[idx]
  5. def _coco_bb(x): return TensorBBox.create(bbox[0])
  6. def _coco_lbl(x): return bbox[1]
  1. coco_dsrc = Datasets([coco_fn]*10, [PILImage.create, [_coco_bb], [_coco_lbl, MultiCategorize(add_na=True)]], n_inp=1)
  2. coco_tdl = TfmdDL(coco_dsrc, bs=9, after_item=[BBoxLabeler(), PointScaler(), ToTensor(), Resize(256)],
  3. after_batch=[IntToFloatTensor(), *aug_transforms()])
  4. coco_tdl.show_batch(max_n=9)

Data Augmentation - 图56


Company logo

©2021 fast.ai. All rights reserved.
Site last generated: Mar 31, 2021