ITK: ResampleImageFilter and ImageFileWriter compatible with dask?

Hi @matt.mccormick,

Excellent that you like the idea and are willing to write a post about it! I am looking forward to it.

In the meantime, I tried to implement a resampler with dask and resorted to scipy as a resampling strategy. The sample code is below. Maybe someone might find it useful.

def resample_scipy(image_chunk, input_spacing: list, output_spacing: list = [1.5, 1.5, 1.5]):
    input_size = image_chunk.shape
    zoom_factors = [(input_spacing[i] / output_spacing[i]) for i in reversed(range(len(input_size)))]
    new_array = zoom(image_chunk, zoom_factors, order=3)
    return new_array


if __name__ == '__main__':
    working_directory = './images'
    input_image_path = os.path.join(working_directory, 'ct.nii.gz')
    
    # Read the image
    itk_image = itk.imread(input_image_path)

    # Calculate chunk size and set up dask computation
    input_spacing = itk.spacing(itk_image)
    input_size = itk.size(itk_image)
    chunk_size = (input_size[2] / 4, input_size[0] / 4, input_size[1] / 4)
    print(chunk_size)
    image_dask = da.from_array(itk_image, chunks=chunk_size)
    result = da.map_blocks(resample_scipy, image_dask, input_spacing)

    # Invoke dask computation and write image
    output_image_path = os.path.join(working_directory, 'dask_scipy_resampled_itk_ct.nii.gz')
    itk.imwrite(itk.image_from_array(result), os.path.join(output_image_path))

    # If the image needs to be further processed, make sure to convert the dask array to numpy array to not invoke the computation again

1 Like