Closed
Description
hi nibabel devs, i would like to replicate freesurfer's mri_convert --conform
functionality, as described in neuronets/kwyk#5. I have the code for it below. It does the following:
- Resize to (256mm)^3 bounding box
- resample to (1mm)^3 voxels
- rescale to 0-255
- reorients to RAS
mri_convert --conform
reorients to LIA but RAS is cooler imho.
i made this an issue instead of a pr because i don't know where this sort of thing should go in the code base. @effigies suggested nibabel.cmdline
but i'm not sure.
from pathlib import Path
import nibabel as nib
import nibabel.processing
import numpy as np
def transform_range(x, new_min, new_max):
x = np.asarray(x)
x_min, x_max = x.min(), x.max()
return (((x - x_min) * (new_max - new_min)) / (x_max - x_min)) + new_min
def conform(from_img, out_shape=(256, 256, 256),
voxel_size=(1.0, 1.0, 1.0), order=3, cval=0.0):
# Create fake image of the image we want to resample to.
hdr = nib.Nifti1Header()
hdr.set_data_shape(out_shape)
hdr.set_zooms(voxel_size)
dst_aff = hdr.get_best_affine()
to_img = nib.Nifti1Image(np.empty(out_shape), affine=dst_aff, header=hdr)
# Resample input image.
out_img = nib.processing.resample_from_to(
from_img=small, to_vox_map=to_img, order=order, cval=cval)
# Cast to uint8.
data = out_img.get_fdata()
data = transform_range(data, new_min=0.0, new_max=255.0)
data = data.round(out=data).astype(np.uint8)
out_img._dataobj = data
out_img.set_data_dtype(np.uint8)
# Reorient to RAS.
out_img = nib.as_closest_canonical(out_img)
return out_img
filename = str(Path(nib.testing.data_path) / 'anatomical.nii')
small = nib.load(filename)
out_img = conform(small)
Metadata
Metadata
Assignees
Labels
No labels