Centering an Image

Hello,

I have implemented the following code to move the center of gravity to the center of the image. The resulting image does not appear to be properly centered as expected.

import itk
import SimpleITK as sitk

common_path = "/home/Dataset/Lung"

# Load the lung CT image
lung_image = sitk.ReadImage(f"{common_path}/mr.nii.gz")

# Compute the moments and get the center of gravity
lung = itk.imread(f"{common_path}/mr.nii.gz")
moments = itk.ImageMomentsCalculator.New(lung)
moments.Compute()
center_of_gravity = moments.GetCenterOfGravity()

# Print the center of gravity
print(f"Center of gravity: {center_of_gravity}")

# Calculate the translation to move the center of gravity to the center of the image
size_x, size_y, size_z = lung_image.GetSize()
translation = [size_x // 2 - int(center_of_gravity[0]),
               size_y // 2 - int(center_of_gravity[1]),
               size_z // 2 - int(center_of_gravity[2])]

# Create a translation transform
translation_transform = sitk.TranslationTransform(3)
translation_transform.SetOffset(translation)

# Apply the translation transform to the image to center it
centered_lung_image = sitk.Resample(lung_image, translation_transform, sitk.sitkLinear, 0.0, lung_image.GetPixelID())

output_path = f"{common_path}/centered.nii.gz"
sitk.WriteImage(centered_lung_image, output_path)

Hello @VHK,

Generally speaking, not recommended to mix and match SimpleITK and ITK till you are proficient with the concepts underlying them.

A key concept which you are missing is that computations are usually done in physical space, images are treated as physical objects. This means you are working with metric units and not in pixel/voxel space which is unitless. For more about these fundamental concepts see the SimpleITK read-the-docs or the ITK book sec. 2.9 Geometric Transformations.

The translation is expected to be in metric units and the code above mixes pixel/voxel (size_x//2) and metric units (center_of_gravity[0]). You need to convert the image center to physical coordinates lung_image.TransformContinuousIndexToPhysicalPoint([sz/2 for sz in lung_image.GetSize()]) and subtract that from the center of gravity.

2 Likes

Many thanks!