import numpy as np
from scipy.ndimage import gaussian_filter, map_coordinates
def elastic_distortion(image, alpha=34, sigma=4):
"""
image: 2D numpy array (H, W), 0〜1のfloat想定
alpha: 変形の強さ(大きいほど強く変形)
sigma: 変形フィールドにかけるガウスぼかしの標準偏差
"""
shape = image.shape
# ランダムな変形フィールドを作成
dx = gaussian_filter(np.random.uniform(-1, 1, shape), sigma) * alpha
dy = gaussian_filter(np.random.uniform(-1, 1, shape), sigma) * alpha
# 元の座標
x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
# 変形後の座標
indices = (y + dy).reshape(-1), (x + dx).reshape(-1)
# map_coordinates で補間付きでサンプリング
return map_coordinates(image, indices, order=1).reshape(shape)