3

I have a 3D image read in to SimpleITK (using python) from a NIfTI file, take each axial slice, do something with it and re-insert the new 2D slice into a 3D volume with the (hopefully) appropriate dimensions. For example,

output = sitk.Image(original.GetSize(), sitk.sitkFloat32)
output.CopyInformation(original)
for z in numpy.arange(original.GetDepth()):
    image = original[:,:,z]
    << Do Something in SimpleITK>>
    << Produce a new 2D image = newimage >>
    output[:,:,z] = newimage

The final step is throwing an error

In [???]: (executing line ??? of "code.py")
Traceback (most recent call last):
  File "code.py", line ???, in <module>
    output[:,:,z] = newimage
  File "/Library/Python/2.7/site-packages/SimpleITK-0.8.1-py2.7-macosx-10.10-intel.egg/SimpleITK/SimpleITK.py", line 3894, in __setitem__
    raise IndexError("invalid index")
IndexError: invalid index

What is the correct syntax (or set of commands) to complete the final step in my for loop?

B. Whitcher
  • 366
  • 2
  • 5

2 Answers2

7

Use the Paste function to paste your slice image into the volume. The only slight trick is that the Paste function assumes both images are 3d. So you need to convert your 2d image into a 3d image (with z size of 1). You can do this with the JoinSeries function.

Here is an example python script to show how this would work

#! /usr/bin/env python

import SimpleITK as sitk

# make a black volume
vol_img = sitk.Image(100,100,100,sitk.sitkUInt8)

# make a white slice
slice_img = sitk.Image(100,100,sitk.sitkUInt8)
slice_img = slice_img + 200

# convert the 2d slice into a 3d volume
slice_vol = sitk.JoinSeries(slice_img)

# z insertion location
z = 42

# paste the 3d white slice into the black volume
pasted_img = sitk.Paste(vol_img, slice_vol, slice_vol.GetSize(), destinationIndex=[0,0,z])

sitk.Show(pasted_img)
Dave Chen
  • 1,905
  • 1
  • 12
  • 18
0

I haven't experience with simpleITK, but it seems they provide a Paste method (example)

lib
  • 2,918
  • 3
  • 27
  • 53