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 as np
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.
"""
assert len(image.shape)==2
if random_state is None:
random_state = np.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 = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij')
indices = np.reshape(x+dx, (-1, 1)), np.reshape(y+dy, (-1, 1))
return map_coordinates(image, indices, order=1).reshape(shape)
@chethanjjj

This comment has been minimized.

Copy link

commented Mar 15, 2017

hey, just wondering what code did you use to load in the image?

@chsasank

This comment has been minimized.

Copy link
Owner Author

commented Apr 17, 2017

You can load using

from skiamge import io
img = io.imread(filename)
@askerlee

This comment has been minimized.

Copy link

commented Oct 14, 2017

Thanks for sharing. However an image is usually a 3-d array. This code seems to require the image is a 2-d array?

@EmmaW8

This comment has been minimized.

Copy link

commented Dec 18, 2017

You can add a loop to achieve 3-D image.

@pedroortizordep

This comment has been minimized.

Copy link

commented Jul 6, 2018

Sorry about my poor knowledge, but you are using gaussian filter for what exactly?

@developer0hye

This comment has been minimized.

Copy link

commented Oct 19, 2018

Sorry about my poor knowledge, but you are using gaussian filter for what exactly?

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

I wrote the reason why we use gaussian filter.

@lequocgiom

This comment has been minimized.

Copy link

commented Mar 19, 2019

Sorry about my question, but how to show the transformed image ?

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.