[docs]defnifti_image_input(image):""" Test if an input is a path or a nifti.image and the image loaded through nibabel Parameters ---------- image : str or nibabel.nifti1.Nifti1Image path to the nifti file or the image already loaded through nibabel Returns ------- img : nibabel.nifti1.Nifti1Image load and return the nifti image if image is a path, otherwise simply return image """ifisinstance(image,nib.nifti1.Nifti1Image):img=imageelifisinstance(image,six.string_types):ifnotos.path.exists(image):raiseValueError(str(image)+" does not exist.")else:img=nib.load(image)else:raiseTypeError("Image can be either a string or a nifti1.Nifti1Image")returnimg
[docs]defmore_zeros_than_ones(image):""" Return True is there is more zeros than other values in a given nifti image. Parameters ---------- image : str or nibabel.nifti1.Nifti1Image path to the nifti file to be inverted or the image already loaded through nibabel Returns ------- more_zeros : boolean """ifisinstance(image,nib.nifti1.Nifti1Image):img=imageelifisinstance(image,six.string_types):ifnotos.path.exists(image):raiseValueError(str(image)+" does not exist.")else:img=nib.load(image)else:raiseTypeError("Image can be either a string or a nifti1.Nifti1Image")data=img.get_fdata()nb_zeros=len(np.where(data==0)[0])size=data.sizemore_zeros=nb_zeros>size-nb_zerosreturnmore_zeros
[docs]definverse_nifti_values(image):""" Replace zeros by ones and non-zero values by 1 Parameters ---------- image : str or nibabel.nifti1.Nifti1Image path to the nifti file to be inverted or the image already loaded through nibabel Returns ------- output : Nibabel Nifti1Image """ifisinstance(image,nib.nifti1.Nifti1Image):img=imageelifisinstance(image,six.string_types):ifnotos.path.exists(image):raiseValueError(str(image)+" does not exist.")else:img=nib.load(image)else:raiseTypeError("Image can be either a string or a nifti1.Nifti1Image")data=img.get_fdata()zeros=np.where(data)out_data=np.ones(data.shape)out_data[zeros]=0returnnib.nifti1.Nifti1Image(out_data,img.affine)