Skip to content

Instantly share code, notes, and snippets.

@mpaquette
Created August 30, 2018 12:17
Show Gist options
  • Save mpaquette/dcb384a4ca5fe5fa36de64e537bb403b to your computer and use it in GitHub Desktop.
Save mpaquette/dcb384a4ca5fe5fa36de64e537bb403b to your computer and use it in GitHub Desktop.
Simple script to downsample niftis.
#!/usr/bin/env python
import numpy as np
import nibabel as nib
import sys
def main(input, output, dx, dy, dz):
img = nib.load(input)
data = img.get_data()
downsampling_factor = np.array([int(dx), int(dy), int(dz)])
print('Input image is size {} {} {}'.format(data.shape[0], data.shape[1], data.shape[2]))
new_data = np.zeros([int(np.ceil(data.shape[0]/float(downsampling_factor[0]))), int(np.ceil(data.shape[1]/float(downsampling_factor[1]))), int(np.ceil(data.shape[2]/float(downsampling_factor[2])))])
print('Downsampling to size {} {} {}'.format(new_data.shape[0], new_data.shape[1], new_data.shape[2]))
for ix in range(new_data.shape[0]):
min_x = ix*downsampling_factor[0]
max_x = (ix+1)*downsampling_factor[0]
if ix == new_data.shape[0]-1:
max_x = min_x + (data.shape[0] - downsampling_factor[0]*ix)
for iy in range(new_data.shape[1]):
min_y = iy*downsampling_factor[1]
max_y = (iy+1)*downsampling_factor[1]
if iy == new_data.shape[1]-1:
max_y = min_y + (data.shape[1] - downsampling_factor[1]*iy)
for iz in range(new_data.shape[2]):
min_z = iz*downsampling_factor[2]
max_z = (iz+1)*downsampling_factor[2]
if iz == new_data.shape[2]-1:
max_z = min_z + (data.shape[2] - downsampling_factor[2]*iz)
new_data[ix, iy, iz] = data[min_x:max_x, min_y:max_y, min_z:max_z].mean()
new_image = nib.nifti1.Nifti1Image(new_data, img.affine)
nib.save(new_image, output)
if __name__ == "__main__":
main(*sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment