# How to use a deformationField to deform a new volume?

**URL:** https://discourse.itk.org/t/how-to-use-a-deformationfield-to-deform-a-new-volume/6294
**Category:** Beginner Questions
**Tags:** registration, python, simpleitk
**Created:** [November 8, 2023, 8:11pm UTC](https://discourse.itk.org/t/how-to-use-a-deformationfield-to-deform-a-new-volume/6294 "2023-11-08T20:11:02Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![PolarBean](https://discourse.itk.org/user_avatar/discourse.itk.org/polarbean/32/3762_2.png) [@PolarBean](https://discourse.itk.org/u/PolarBean)
#### Post date: [November 8, 2023, 8:11pm UTC](https://discourse.itk.org/t/how-to-use-a-deformationfield-to-deform-a-new-volume/6294/1 "2023-11-08T20:11:02Z")

</div>

Hi,

Thank you for working on this package. I am using [GitHub - SuperElastix/SimpleElastix: Multi-lingual medical image registration library](https://github.com/SuperElastix/SimpleElastix) which has now been integrated into SimpleITK.

I have generated a deformation field in SimpleItk (see [https://github.com/ingvildeb/DeMBA\_scripts/blob/main/DeMBA\_functions.py#L122-L129](https://github.com/ingvildeb/DeMBA_scripts/blob/main/DeMBA_functions.py#L122-L129)). I now have a nii volume with 3 dimensions. How can i then take this and apply it to a new image?  
Here is my current unsuccesful attempt.

```python
import nibabel as nib
from scipy.ndimage import map_coordinates
from skimage.transform import resize
import numpy as np
import SimpleITK as sitk
import nibabel as nib
import nrrd

# Load the image to be deformed
image_basepath = r"reoriented_data\\"
template_path = rf"{image_basepath}/average_template_10_reoriented.nii.gz"
# Load the nii.gz file
template_img = sitk.ReadImage(template_path)
template_arr = sitk.GetArrayFromImage(template_img)
# Load the deformation field
deformation_basepath = r"deformation_matrices\original\forward\\"
deformation_path = rf"{deformation_basepath}p56_to_p28_deformation_field.nii"
deformation_img = sitk.ReadImage(deformation_path)
deform_arr = sitk.GetArrayFromImage(deformation_img)
voxel_size = deformation_img.GetSpacing()
#since indices needs the number of dimensions first we transpose
deform_arr = np.transpose(deform_arr, (3, 0, 1, 2))
#the voxels are isotropic so we can use the same voxel size for all dimensions
indices = (deform_arr / voxel_size[0]) + np.indices(deform_arr.shape[1:])
temlpate_resized = resize(template_arr, deform_arr.shape[1:], order=0)
deformed_volume_data = map_coordinates(temlpate_resized, indices, order=0, prefilter=False)

```

The original run in elastix produces a good result, but when applying the deformation matrices to the same template it does not reproduce. Any help you can provide would be most appreciated.
