1

I would like to crop a 3D image using simpleItk in Python3

first, loading the image and get numpy array

image_ct = sitk.ReadImage(path_ct, sitk.sitkInt16)
array_ct = sitk.GetArrayFromImage(image_ct)

then I do a crop on array data

center = (200, 200, 200)
array_gt = array_gt[center[0]-50:center[0]+51, center[1]-50:center[1]+51, center[2]-40:center[2]+41]

now I wanna create an sitk.Image from the array and save the result

def create_ref_image(image, size=(101, 101, 81), spacing=(0.97, 0.97, 0.97), dimension=3):

    ref_origin = np.zeros(dimension)
    ref_direction = np.identity(dimension).flatten()
    ref_image = sitk.Image(size, image.GetPixelIDValue())
    ref_image.SetOrigin(ref_origin)
    ref_image.SetSpacing(spacing)
    ref_image.SetDirection(ref_direction)

    return ref_image

ref_img = create_ref_image(image_ct)
cropped_img = sitk._SimpleITK._SetImageFromArray(np.ascontiguousarray(array_gt), ref_img)
sitk.WriteImage(cropped_img, "/DATA/exemple.nii")

but then I get this error

File ".../anaconda3/envs/objD/lib/python3.6/site-packages/SimpleITK/SimpleITK.py", line 8207, in WriteImage return _SimpleITK.WriteImage(*args) ValueError: invalid null reference in method 'WriteImage', argument 1 of type 'itk::simple::Image const &'

How can I crop an image using SimpleItk (in python) ?

Chopin
  • 188
  • 1
  • 10

2 Answers2

2

Turn out you can simply use slicing operator directly on sitk.Image;

image_ct = image_ct[center[0]-50:center[0]+51, center[1]-50:center[1]+51, center[2]-40:center[2]+41]

sitk.WriteImage(image_ct, "/DATA/exemple.nii")
Chopin
  • 188
  • 1
  • 10
1

In addition to cropping via Python slicing, SimpleITK has a Crop function and a CropImageFilter.

Here's the doc for the Crop function:

https://itk.org/SimpleITKDoxygen/html/namespaceitk_1_1simple.html#a4458c40720e7d78ace07181e13064865

and the CropImageFilter:

https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1CropImageFilter.html

The functionality is the same as slicing, but if you need to crop a number of images the same way it may be convenient to have a CropImageFilter object that is executed for all the images.

Dave Chen
  • 1,905
  • 1
  • 12
  • 18