RuntimeError with number of expected elements for DisplacementFieldTransform

I’m trying to create a DisplacementFieldTransform using a MetaImage that I’ve saved, but I’m getting a runtime error and I haven’t found anything online related to it. This is what the error says:

RuntimeError: Exception thrown in SimpleITK new_DisplacementFieldTransform: D:\a\1\sitk\Code\Common\include\sitkImageConvert.hxx:45:
sitk::ERROR: Expected number of elements in vector image to be the same as the dimension!

The MetaImage that I’m using is a .mhd file that represents a deformation vector field. My goal is to apply the deformation field to an image to see how the image changes. A simplified version of my Python code is pasted below.

ref_img = sitk.ReadImage('\path\to\ref_img.mhd')
dvf_img = sitk.ReadImage('\path\to\dvf_img.mhd', sitk.sitkVectorFloat64)
displacementTx = sitk.DisplacementFieldTransform(dvf_img)  # the code is breaking on this line
displacementTx.SetInterpolator(sitk.sitkNearestNeighbor)
resampler = sitk.ResampleImageFilter()
resampler.SetTransform(displacementTx)
resampler.SetReferenceImage(ref_img)
deformed = resampler.Execute(ref_img)

I’ve looked at the size of the array that I get from the .mhd file and compared it to the original Image, and they have the same number of elements. The number of components per pixel is also 1 for the image. I’m very new to SITK so maybe it’s a simple solution that I haven’t thought of, but I haven’t been able to find any sort of documentation on this error. Any help would be greatly appreciated!

Hello @rtlim,

The error is not with respect to the image size, it is referring to the image dimensionality. An nD displacement field is expected to have values that are nD vectors. Code below recreates the issue (change the number_of_elements_in_vector to match dim and the error is resolved):

import SimpleITK as sitk

dim = 2
number_of_elements_in_vector = 3
dvf_img = sitk.Image([2]*dim, sitk.sitkVectorFloat64, number_of_elements_in_vector)

print(f"Number of elements in vector: {dvf_img.GetNumberOfComponentsPerPixel()}")
print(f"Vector field dimension: {dvf_img.GetDimension()}")

displacementTx = sitk.DisplacementFieldTransform(dvf_img)

You will need to print the information for the dvf_img to see what exactly is causing the mismatch in your case.