Range indexing an ITK image by variables

I’m trying to slice an sitk image in 3D but having trouble. The following code doesn’t work for some reason

Does not work

image = sitk.ReadImage('./myImage.nrrd')

i_indices = np.arange(100,164) // or range(100,164)
j_indices = np.arange(100,164)
z_indices = 100

image[i_indices, j_indices, z_indices]


image[100:164, 100:164, 100]

The error is

~/.../python3.8/site-packages/SimpleITK/SimpleITK.py in __getitem__(self, idx)
   4139             idx = (idx, Ellipsis)
-> 4141         if len(idx) > dim + (Ellipsis in idx):
   4142           raise IndexError("too many indices for image")
   4143         if (len(idx) < dim) and Ellipsis not in idx:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I tried np.ix_ approach in numpy too but no success.

How can I not go to Array (sitk.GetArrayFromImage), and still be able to slice a range in sitk image by indexing via variables? I think I’m missing something obvious but googling for a good amount of time didn’t result in a solution.


Hello @sedghi,

SimpleITK does not support that type for indexing. You can use slice:

import SimpleITK as sitk

image = sitk.ReadImage('./myImage.nrrd')

i_indices = slice(100,164)
j_indices = slice(100,164)
z_indices = 100

image[i_indices, j_indices, z_indices]
1 Like

Thanks a lot, it worked