-
Paul McCarthy authoredPaul McCarthy authored
feedsRun 1.37 KiB
#!/usr/bin/env fslpython
import os
import sys
import subprocess as sp
import numpy as np
import nibabel as nib
def create_image(shape, pixdim):
pixdim = list(pixdim)
data = np.random.random(shape).astype(np.float32)
hdr = nib.Nifti1Header()
hdr.set_data_dtype(np.float32)
hdr.set_data_shape(shape)
hdr.set_zooms(pixdim[:len(shape)])
return nib.Nifti1Image(data, np.eye(4), hdr)
def check_image(origimg, changedimg, exppixdim):
gotshape = changedimg.shape
gotpixdim = list(changedimg.header.get_zooms())
gotdata = changedimg.get_fdata()
assert origimg.shape == gotshape
assert gotpixdim == exppixdim
assert np.all(origimg.get_fdata() == gotdata)
def run_tests():
# (image shape, command, exppixdims)
tests = [
((5, 5, 5), '2 2 2', (2, 2, 2)),
((5, 5, 5), '2 2 2 2', (2, 2, 2)),
((5, 5, 5, 5), '2 2 2', (2, 2, 2, 1)),
((5, 5, 5, 5), '2 2 2 2', (2, 2, 2, 2)),
]
for shape, cmd, exppixdim in tests:
imgfile = 'image.nii.gz'
img = create_image(shape, [1] * len(shape))
img.to_filename(imgfile)
try:
sp.run(['fslchpixdim', imgfile] + list(cmd.split()))
check_image(img, nib.load(imgfile), list(exppixdim))
finally:
os.remove(imgfile)
if __name__ == '__main__':
sys.exit(run_tests())