Beispiel #1
0
def samples_npy_to_nifti(samples_npy_fname,
                         used_mask,
                         nifti_header,
                         nifti_fname=None):
    """Convert a npy file containing sample results to a nifti file.

    Since the sample npy files are stored as a two dimensional matrix (with on the first axis the ROI index number
    and on the second the samples), we need to have the lookup table for the spatial information about the samples.

    Args:
        samples_npy_fname (str): the filename of the samples file to convert
        used_mask (ndarray or str): either an three dimensional matrix with the mask or a path to a nifti file.
        nifti_header (nibabel header): the header to use for writing the nifti file
        nifti_fname (str): the filename of the nifti file. If not given it defaults to the same directory as the
            samples file.
    """
    samples = np.load(samples_npy_fname, mmap_mode='r')

    if isinstance(used_mask, str):
        used_mask = load_nifti(used_mask).get_data()

    if np.count_nonzero(used_mask) != samples.shape[0]:
        raise ValueError(
            'The number of voxels in the mask ({}) does not correspond '
            'with the number of voxels in the samples file ({})'.format(
                np.count_nonzero(used_mask), samples.shape[0]))

    if nifti_fname is None:
        nifti_fname = os.path.join(
            os.path.dirname(samples_npy_fname),
            os.path.splitext(os.path.basename(samples_npy_fname))[0] +
            '.nii.gz')

    volume = restore_volumes(samples, used_mask)
    write_nifti(volume, nifti_fname, nifti_header)
Beispiel #2
0
def create_write_median_otsu_brain_mask(dwi_info, protocol, output_fname,
                                        **kwargs):
    """Write a brain mask using the given volume and output as the given volume.

    Args:
        dwi_info (string or tuple or ndarray): the filename of the input file or a tuple with as
            first index a ndarray with the DWI and as second index the header or only the image.
        protocol (string or :class:`~mdt.protocols.Protocol`): The filename of the protocol file or a Protocol object
        output_fname (string): the filename of the output file (the extracted brain mask)
            If None, no output is written. If ``dwi_info`` is an ndarray also no file is written
            (we don't have the header).

    Returns:
        ndarray: The created brain mask
    """
    if isinstance(dwi_info, str):
        signal_img = load_nifti(dwi_info)
        dwi = signal_img.get_data()
        header = signal_img.get_header()
    else:
        dwi = dwi_info[0]
        header = dwi_info[1]

    mask = create_median_otsu_brain_mask(dwi, protocol, **kwargs)
    write_nifti(mask, output_fname, header)

    return mask
Beispiel #3
0
def generate_simple_wm_mask(fa_fname,
                            brain_mask_fname,
                            out_fname,
                            fa_threshold=0.3,
                            median_radius=1,
                            numpass=2):
    """Generate a simple white matter mask by thresholding the given FA map.

    Everything below the given FA threshold will be masked (not used). It also applies the regular brain mask to
    only retain values inside the brain.

    Args:
        fa_fname (str): the path to the FA file
        brain_mask_fname (str): the path to the general brain mask in use
        out_fname (str): where to write the outfile.
        fa_threshold (double): the FA threshold. Everything below this threshold is masked (set to 0). To be precise:
            where fa_data < fa_threshold set the value to 0.
        median_radius (int): the radius of the median filter
        numpass (int): the number of passes we apply the median filter
    """
    logger = logging.getLogger(__name__)
    logger.info('Starting calculating a white matter mask using FA.')

    nib_container = load_nifti(fa_fname)
    fa_data = nib_container.get_data()

    fa_data[fa_data < fa_threshold] = 0
    fa_data[fa_data > 0] = 1

    if len(fa_data.shape) > 3:
        fa_data = fa_data[:, :, :, 0]

    filter_footprint = np.zeros((1 + 2 * median_radius, ) * 3)
    filter_footprint[median_radius, median_radius, median_radius] = 1
    filter_footprint[:, median_radius, median_radius] = 1
    filter_footprint[median_radius, :, median_radius] = 1
    filter_footprint[median_radius, median_radius, :] = 1

    mask = load_brain_mask(brain_mask_fname)

    fa_data_masked = np.ma.masked_array(fa_data, mask=mask)
    for ind in range(numpass):
        fa_data_masked = median_filter(fa_data_masked,
                                       footprint=filter_footprint,
                                       mode='constant')

    write_nifti(fa_data_masked, out_fname, nib_container.get_header())
    logger.info('Finished calculating a white matter mask.')
Beispiel #4
0
def volume_map_npy_to_nifti(npy_fname, nifti_header, nifti_fname=None):
    """Convert a volume-map npy file to a nifti file.

    Args:
        npy_fname (str): the filename of the npy file to load
        nifti_header (nibabel header): the header file for the nifti
        nifti_fname (str): the filename of the nifti file. If not given it defaults to the same directory as the
            npy file.
    """
    data = np.load(npy_fname, mmap_mode='r')

    if nifti_fname is None:
        nifti_fname = os.path.join(
            os.path.dirname(npy_fname),
            os.path.splitext(os.path.basename(npy_fname))[0] + '.nii.gz')
    write_nifti(data, nifti_fname, nifti_header)