Skip to content

Instantly share code, notes, and snippets.

@nasimrahaman
Last active January 16, 2024 12:53
Show Gist options
  • Save nasimrahaman/8ed04be1088e228c21d51291f47dd1e6 to your computer and use it in GitHub Desktop.
Save nasimrahaman/8ed04be1088e228c21d51291f47dd1e6 to your computer and use it in GitHub Desktop.
Random elastic transformations for data augmentation
import numpy as np
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
# Elastic transform
def elastic_transformations(alpha, sigma, rng=np.random.RandomState(42),
interpolation_order=1):
"""Returns a function to elastically transform multiple images."""
# Good values for:
# alpha: 2000
# sigma: between 40 and 60
def _elastic_transform_2D(images):
"""`images` is a numpy array of shape (K, M, N) of K images of size M*N."""
# Take measurements
image_shape = images[0].shape
# Make random fields
dx = rng.uniform(-1, 1, image_shape) * alpha
dy = rng.uniform(-1, 1, image_shape) * alpha
# Smooth dx and dy
sdx = gaussian_filter(dx, sigma=sigma, mode='reflect')
sdy = gaussian_filter(dy, sigma=sigma, mode='reflect')
# Make meshgrid
x, y = np.meshgrid(np.arange(image_shape[1]), np.arange(image_shape[0]))
# Distort meshgrid indices
distorted_indices = (y + sdy).reshape(-1, 1), \
(x + sdx).reshape(-1, 1)
# Map cooordinates from image to distorted index set
transformed_images = [map_coordinates(image, distorted_indices, mode='reflect',
order=interpolation_order).reshape(image_shape)
for image in images]
return transformed_images
return _elastic_transform_2D
@Rishav09
Copy link

Rishav09 commented Sep 3, 2019

How to modify this if we need nearest or bilinear interpolation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment