Different Data Augmentation techniques in Python

In this tutorial, we are going to see the different data augmentation techniques in Python, with the help of a simple example.

imgaug in Python

Data augmentation is a process, where we process and modify data to make it useful for further operations. Here, we are going to see different techniques used for image augmentation. In Python, we have a library, imgaug which can perform various image augmentation techniques efficiently.  Let us first install this library.

pip install imgaug

Once we have installed the library, let us import it into our IDE.

import imagaug as ia
import imgaug.augmenters as iaa        #To apply the augmentation techniques
import imageio                         #To read the image

Now we are ready use these libraries. Image augmentation techniques are used during the pre-processing stage of training a model in data science projects. These techniques are generally used to increase the size of the data set. This increased dataset can train better models and give more accurate predictions in the testing phase.

These are the basic image augmentation techniques.

  1. Rotation – The image can be rotated wrt to x or y axis.
  2. Cropping – The image can be cropped at any position.
  3. Flipping – The image can be flipped vertically or horizontally.
  4. Shearing – The position of the image is shifted to form a paralellogram.
  5. Zooming- The image can be zoomed in or out.
  6. Changing the brightness of the image

Let us see these methods one by one. First, we have to get an image we want to augment.

#Original image
image = imageio.imread('baloon.jfif')
ia.imshow(image)

Now, we can apply the techniques.

Rotation

#Rotating the image
rotate=iaa.Affine(rotate=(-50, 30))
rotated_img=rotate.augment_image(image)
ia.imshow(rotated_img)

Cropping

#cropped image
crop = iaa.Crop(percent=(0, 0.3)) # crop image
corp_img=crop.augment_image(image)
ia.imshow(corp_img)

Flipping

#flipping image horizontally
flip_hr=iaa.Fliplr(p=1.0)
flip_hor_img= flip_hr.augment_image(image)
ia.imshow(flip_hor_img)

#Flipping image vertically
flip_vr=iaa.Flipud(p=1.0)
flip_vrt_img= flip_vr.augment_image(image)
ia.imshow(flip_vrt_img)

Shearing

#Shearing the image
shear = iaa.Affine(shear=(0,40))
shear_img=shear.augment_image(image)
ia.imshow(shear_img)

Zooming

#Scaling the image
scale_im=iaa.Affine(scale={"x": (1.8, 1.2), "y": (1.9, 1.4)})
scale_img =scale_im.augment_image(image)
ia.imshow(scale_img)

Brightness

#Changing the contrast/brightness of the image
contrast=iaa.GammaContrast(gamma=2.0)
contrast_img =contrast.augment_image(image)
ia.imshow(contrast_img)

So using these methods, we can augment an image in Python.

Also read: Data Types in Python

Leave a Reply