Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: implement mri_convert --conform functionality #851

Closed
kaczmarj opened this issue Dec 11, 2019 · 1 comment · Fixed by #853
Closed

ENH: implement mri_convert --conform functionality #851

kaczmarj opened this issue Dec 11, 2019 · 1 comment · Fixed by #853

Comments

@kaczmarj
Copy link
Contributor

kaczmarj commented Dec 11, 2019

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)
@effigies
Copy link
Member

It would make sense for the function to go in nibabel.processing, but a command-line interface also seems useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants