Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Elastic transformation of an image in Python
import numpy
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
def elastic_transform(image, alpha, sigma, random_state=None):
"""Elastic deformation of images as described in [Simard2003]_.
.. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for
Convolutional Neural Networks applied to Visual Document Analysis", in
Proc. of the International Conference on Document Analysis and
Recognition, 2003.
"""
if random_state is None:
random_state = numpy.random.RandomState(None)
shape = image.shape
dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
x, y = numpy.meshgrid(numpy.arange(shape[0]), numpy.arange(shape[1]))
indices = numpy.reshape(y+dy, (-1, 1)), numpy.reshape(x+dx, (-1, 1))
return map_coordinates(image, indices, order=1).reshape(shape)
@pengpaiSH

This comment has been minimized.

Copy link

commented Jun 16, 2016

   indices = numpy.reshape(y+dy, (-1, 1)), numpy.reshape(x+dx, (-1, 1))
ValueError: operands could not be broadcast together with shapes (580,420) (420,580) 

It seems that we cannot do y+dy since shape does not match?

@Graydyn

This comment has been minimized.

Copy link

commented Jul 13, 2016

I do believe line 24 has it's shape values reversed. Should be:
x, y = numpy.meshgrid(numpy.arange(shape[1]), numpy.arange(shape[0]))

Unless the image is square in which case it doesn't matter.

@chsasank

This comment has been minimized.

Copy link

commented Jul 27, 2016

Above script doesn't work if image is not a square.
Here's a working script: https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a

@chethanjjj

This comment has been minimized.

Copy link

commented Mar 15, 2017

what code did you use to load in the "image"?

@ZY0422

This comment has been minimized.

Copy link

commented Jul 22, 2017

@chethanjjj I use Image from PIL
You can install it with
pip install Pillow=4.2.1

@Abe404

This comment has been minimized.

Copy link

commented Jul 22, 2018

Thanks for sharing this.

Any possibility you could use a license so I know if and how I can use it?

@MohammadSalehi72

This comment has been minimized.

Copy link

commented Sep 28, 2018

thanks for sharing.
Is it code working with dicom images?

@developer0hye

This comment has been minimized.

Copy link

commented Oct 19, 2018

A c++ implementation can be found here Implementation of elastic distortion algorithm in C++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.