How to use the nilearn._utils.check_niimg_3d function in nilearn

To help you get started, we’ve selected a few nilearn examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github photon-team / photon / photonai / neuro / brain_atlas.py View on Github external
def apply_mask(self, series, mask_img):
        mask_img = _utils.check_niimg_3d(mask_img)
        mask, mask_affine = masking._load_mask_img(mask_img)
        mask_img = image.new_img_like(mask_img, mask, mask_affine)
        mask_data = _utils.as_ndarray(mask_img.get_data(),
                                      dtype=np.bool)
        return series[mask_data].T
github nilearn / nilearn / nilearn / plotting / img_plotting.py View on Github external
if anat_img is False or anat_img is None:
        if black_bg == 'auto':
            # No anatomy given: no need to turn black_bg on
            black_bg = False
        return anat_img, black_bg, vmin, vmax

    if anat_img is MNI152TEMPLATE:
        anat_img.load()
        # We special-case the 'canonical anat', as we don't need
        # to do a few transforms to it.
        vmin = 0
        vmax = anat_img.vmax
        if black_bg == 'auto':
            black_bg = False
    else:
        anat_img = _utils.check_niimg_3d(anat_img)
        # Clean anat_img for non-finite values to avoid computing unnecessary
        # border data values.
        data = _safe_get_data(anat_img, ensure_finite=True)
        anat_img = new_img_like(anat_img, data, affine=anat_img.affine)
        if dim or black_bg == 'auto':
            # We need to inspect the values of the image
            vmin = np.nanmin(data)
            vmax = np.nanmax(data)
        if black_bg == 'auto':
            # Guess if the background is rather black or light based on
            # the values of voxels near the border
            background = np.median(get_border_data(data, 2))
            if background > .5 * (vmin + vmax):
                black_bg = False
            else:
                black_bg = True
github nilearn / nilearn / nilearn / plotting / find_cuts.py View on Github external
Label regions cut coordinates in image space (mm).

    labels_list: list, optional
        Label region. Returned only when return_label_names is True.

    See Also
    --------
    nilearn.plotting.find_probabilistic_atlas_cut_coords : For coordinates
        extraction on probabilistic atlases (4D) (Eg. MSDL atlas)
    """
    # check label_hemisphere input
    if label_hemisphere not in ['left', 'right']:
        raise ValueError("Invalid label_hemisphere name:{0}. Should be one "
                         "of these 'left' or 'right'.".format(label_hemisphere))
    # Grab data and affine
    labels_img = reorder_img(check_niimg_3d(labels_img))
    labels_data = labels_img.get_data()
    labels_affine = labels_img.affine

    # Grab number of unique values in 3d image
    unique_labels = set(np.unique(labels_data)) - set([background_label])

    # Loop over parcellation labels, grab center of mass and dump into coords
    # list
    coord_list = []
    label_list = []

    for cur_label in unique_labels:
        cur_img = labels_data == cur_label

        # Grab hemispheres separately
        x, y, z = coord_transform(0, 0, 0, np.linalg.inv(labels_affine))
github nilearn / nilearn / nilearn / regions / signal_extraction.py View on Github external
maps_img = _utils.check_niimg_4d(maps_img)
    imgs = _utils.check_niimg_4d(imgs)
    affine = imgs.affine
    shape = imgs.shape[:3]

    # Check shapes and affines.
    if maps_img.shape[:3] != shape:
        raise ValueError("maps_img and imgs shapes must be identical.")
    if abs(maps_img.affine - affine).max() > 1e-9:
        raise ValueError("maps_img and imgs affines must be identical")

    maps_data = _safe_get_data(maps_img, ensure_finite=True)

    if mask_img is not None:
        mask_img = _utils.check_niimg_3d(mask_img)
        if mask_img.shape != shape:
            raise ValueError("mask_img and imgs shapes must be identical.")
        if abs(mask_img.affine - affine).max() > 1e-9:
            raise ValueError("mask_img and imgs affines must be identical")
        maps_data, maps_mask, labels = \
                   _trim_maps(maps_data,
                              _safe_get_data(mask_img, ensure_finite=True),
                              keep_empty=True)
        maps_mask = _utils.as_ndarray(maps_mask, dtype=np.bool)
    else:
        maps_mask = np.ones(maps_data.shape[:3], dtype=np.bool)
        labels = np.arange(maps_data.shape[-1], dtype=np.int)

    data = _safe_get_data(imgs, ensure_finite=True)
    region_signals = linalg.lstsq(maps_data[maps_mask, :],
                                  data[maps_mask, :])[0].T
github nilearn / nilearn / nilearn / input_data / nifti_masker.py View on Github external
if self.mask_strategy == 'background':
                compute_mask = masking.compute_background_mask
            elif self.mask_strategy == 'epi':
                compute_mask = masking.compute_epi_mask
            elif self.mask_strategy == 'template':
                compute_mask = masking.compute_gray_matter_mask
            else:
                raise ValueError("Unknown value of mask_strategy '%s'. "
                                 "Acceptable values are 'background', "
                                 "'epi' and 'template'." % self.mask_strategy)
            if self.verbose > 0:
                print("[%s.fit] Computing the mask" % self.__class__.__name__)
            self.mask_img_ = self._cache(compute_mask, ignore=['verbose'])(
                imgs, verbose=max(0, self.verbose - 1), **mask_args)
        else:
            self.mask_img_ = _utils.check_niimg_3d(self.mask_img)

        if self.reports:  # save inputs for reporting
            self._reporting_data = {'images': imgs, 'mask': self.mask_img_}
        else:
            self._reporting_data = None

        # If resampling is requested, resample also the mask
        # Resampling: allows the user to change the affine, the shape or both
        if self.verbose > 0:
            print("[%s.fit] Resampling mask" % self.__class__.__name__)
        self.mask_img_ = self._cache(image.resample_img)(
            self.mask_img_,
            target_affine=self.target_affine,
            target_shape=self.target_shape,
            copy=False, interpolation='nearest')
        if self.target_affine is not None:  # resample image to target affine
github nilearn / nilearn / nilearn / plotting / img_plotting.py View on Github external
show_nan_msg = True
    if show_nan_msg:
        nan_msg = ('NaN is not permitted for the vmax and vmin arguments.\n'
                   'Tip: Use np.nanmax() instead of np.max().')
        warnings.warn(nan_msg)

    if (isinstance(cut_coords, numbers.Number) and
            (display_mode == 'ortho' or display_mode == 'tiled')):
        raise ValueError(
            "The input given for display_mode='{0}' needs to be "
            "a list of 3d world coordinates in (x, y, z). "
            "You provided single cut, "
            "cut_coords={1}".format(display_mode, cut_coords))

    if img is not False and img is not None:
        img = _utils.check_niimg_3d(img, dtype='auto')
        data = _safe_get_data(img, ensure_finite=True)
        affine = img.affine

        if np.isnan(np.sum(data)):
            data = np.nan_to_num(data)

        # Deal with automatic settings of plot parameters
        if threshold == 'auto':
            # Threshold epsilon below a percentile value, to be sure that some
            # voxels pass the threshold
            threshold = fast_abs_percentile(data) - 1e-5

        img = new_img_like(img, as_ndarray(data), affine)

    display = display_factory(display_mode)(
        img,
github nilearn / nilearn / nilearn / masking.py View on Github external
def _apply_mask_fmri(imgs, mask_img, dtype='f',
                     smoothing_fwhm=None, ensure_finite=True):
    """Same as apply_mask().

    The only difference with apply_mask is that some costly checks on mask_img
    are not performed: mask_img is assumed to contain only two different
    values (this is checked for in apply_mask, not in this function).
    """

    mask_img = _utils.check_niimg_3d(mask_img)
    mask_affine = mask_img.get_affine()
    mask_data = _utils.as_ndarray(mask_img.get_data(),
                                  dtype=np.bool)

    if smoothing_fwhm is not None:
        ensure_finite = True

    imgs_img = _utils.check_niimg(imgs)
    affine = imgs_img.get_affine()[:3, :3]

    if not np.allclose(mask_affine, imgs_img.get_affine()):
        raise ValueError('Mask affine: \n%s\n is different from img affine:'
                         '\n%s' % (str(mask_affine),
                                   str(imgs_img.get_affine())))

    if not mask_data.shape == imgs_img.shape[:3]:
github nilearn / nilearn / nilearn / plotting / displays.py View on Github external
def init_with_figure(cls, img, threshold=None,
                         cut_coords=None, figure=None, axes=None,
                         black_bg=False, leave_space=False, colorbar=False,
                         brain_color=(0.5, 0.5, 0.5), **kwargs):
        "Initialize the slicer with an image"
        # deal with "fake" 4D images
        if img is not None and img is not False:
            img = _utils.check_niimg_3d(img)

        cut_coords = cls.find_cut_coords(img, threshold, cut_coords)

        if isinstance(axes, plt.Axes) and figure is None:
            figure = axes.figure

        if not isinstance(figure, plt.Figure):
            # Make sure that we have a figure
            figsize = cls._default_figsize[:]

            # Adjust for the number of axes
            figsize[0] *= len(cut_coords)

            # Make space for the colorbar
            if colorbar:
                figsize[0] += .7
github nilearn / nilearn / nilearn / masking.py View on Github external
if grp_mask is None:
            # We use int here because there may be a lot of masks to merge
            grp_mask = _utils.as_ndarray(mask, dtype=int)
        else:
            # If this_mask is floating point and grp_mask is integer, numpy 2
            # casting rules raise an error for in-place addition. Hence we do
            # it long-hand.
            # XXX should the masks be coerced to int before addition?
            grp_mask += mask

    grp_mask = grp_mask > (threshold * len(list(mask_imgs)))

    if np.any(grp_mask > 0) and connected:
        grp_mask = largest_connected_component(grp_mask)
    grp_mask = _utils.as_ndarray(grp_mask, dtype=np.int8)
    return new_img_like(_utils.check_niimg_3d(mask_imgs[0]), grp_mask, ref_affine)