@preserve_shape<EOL>def elastic_transform(image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR,<EOL>border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, approximate=False):
if random_state is None:<EOL><INDENT>random_state = np.random.RandomState(<NUM_LIT>)<EOL><DEDENT>height, width = image.shape[:<NUM_LIT:2>]<EOL>center_square = np.float32((height, width)) // <NUM_LIT:2><EOL>square_size = min((height, width)) // <NUM_LIT:3><EOL>alpha = float(alpha)<EOL>sigma = float(sigma)<EOL>alpha_affine = float(alpha_affine)<EOL>pts1 = np.float32([center_square + square_size, [center_square[<NUM_LIT:0>] + square_size, center_square[<NUM_LIT:1>] - square_size],<EOL>center_square - square_size])<EOL>pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32)<EOL>matrix = cv2.getAffineTransform(pts1, pts2)<EOL>image = cv2.warpAffine(image, matrix, (width, height), flags=interpolation, borderMode=border_mode,<EOL>borderValue=value)<EOL>if approximate:<EOL><INDENT>dx = (random_state.rand(height, width).astype(np.float32) * <NUM_LIT:2> - <NUM_LIT:1>)<EOL>cv2.GaussianBlur(dx, (<NUM_LIT>, <NUM_LIT>), sigma, dst=dx)<EOL>dx *= alpha<EOL>dy = (random_state.rand(height, width).astype(np.float32) * <NUM_LIT:2> - <NUM_LIT:1>)<EOL>cv2.GaussianBlur(dy, (<NUM_LIT>, <NUM_LIT>), sigma, dst=dy)<EOL>dy *= alpha<EOL><DEDENT>else:<EOL><INDENT>dx = np.float32(gaussian_filter((random_state.rand(height, width) * <NUM_LIT:2> - <NUM_LIT:1>), sigma) * alpha)<EOL>dy = np.float32(gaussian_filter((random_state.rand(height, width) * <NUM_LIT:2> - <NUM_LIT:1>), sigma) * alpha)<EOL><DEDENT>x, y = np.meshgrid(np.arange(width), np.arange(height))<EOL>mapx = np.float32(x + dx)<EOL>mapy = np.float32(y + dy)<EOL>return cv2.remap(image, mapx, mapy, interpolation, borderMode=border_mode)<EOL>
Elastic deformation of images as described in [Simard2003]_ (with modifications).
    Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5

    .. [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.