# Range indexing an ITK image by variables

**URL:** https://discourse.itk.org/t/range-indexing-an-itk-image-by-variables/4557
**Category:** Engineering
**Tags:** simpleitk, python
**Created:** [November 6, 2021, 2:52pm UTC](https://discourse.itk.org/t/range-indexing-an-itk-image-by-variables/4557 "2021-11-06T14:52:48Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![sedghi](https://discourse.itk.org/user_avatar/discourse.itk.org/sedghi/32/317_2.png) [@sedghi](https://discourse.itk.org/u/sedghi)
#### Post date: [November 6, 2021, 2:52pm UTC](https://discourse.itk.org/t/range-indexing-an-itk-image-by-variables/4557/1 "2021-11-06T14:52:48Z")

</div>

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

```python
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]

```

#### Works

```auto
image[100:164, 100:164, 100]

```

The error is

```auto
~/.../python3.8/site-packages/SimpleITK/SimpleITK.py in __getitem__ (self, idx)
   4139 idx = (idx, Ellipsis)
   4140 
-> 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](https://stackoverflow.com/questions/13598646/numpy-multiple-slicing-booleans/13599843#13599843) 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.

Thanks

---

<div class="post-metadata">

### Author: ![zivy](https://discourse.itk.org/user_avatar/discourse.itk.org/zivy/32/1726_2.png) [@zivy](https://discourse.itk.org/u/zivy)
#### Post date: [November 6, 2021, 3:44pm UTC](https://discourse.itk.org/t/range-indexing-an-itk-image-by-variables/4557/2 "2021-11-06T15:44:35Z")

</div>

Hello @sedghi,

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

```auto
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]

```

---

<div class="post-metadata">

### Author: ![sedghi](https://discourse.itk.org/user_avatar/discourse.itk.org/sedghi/32/317_2.png) [@sedghi](https://discourse.itk.org/u/sedghi)
#### Post date: [November 8, 2021, 3:16am UTC](https://discourse.itk.org/t/range-indexing-an-itk-image-by-variables/4557/3 "2021-11-08T03:16:01Z")

</div>

Thanks a lot, it worked
