class_docstr: Class for masking of Niimg-like objects.
  
  NiftiLabelsMasker is useful when data from non-overlapping volumes should
  be extracted (contrarily to :class:`nilearn.maskers.NiftiMapsMasker`).
  Use case: Summarize brain signals from clusters that were obtained by prior
  K-means or Ward clustering.
  
  Parameters
  ----------
  labels_img : Niimg-like object
      See :ref:`extracting_data`.
      Region definitions, as one image of labels.
  
  labels : :obj:`list` of :obj:`str`, optional
      Full labels corresponding to the labels image. This is used
      to improve reporting quality if provided.
      Warning: The labels must be consistent with the label
      values provided through `labels_img`.
  
  background_label : :obj:`int` or :obj:`float`, default=0
      Label used in labels_img to represent background.
      Warning: This value must be consistent with label values and
      image provided.
  
  mask_img : Niimg-like object, optional
      See :ref:`extracting_data`.
      Mask to apply to regions before extracting signals.
  %(smoothing_fwhm)s
  %(standardize_maskers)s
  %(standardize_confounds)s
  high_variance_confounds : :obj:`bool`, default=False
      If True, high variance confounds are computed on provided image with
      :func:`nilearn.image.high_variance_confounds` and default parameters
      and regressed out.
  %(detrend)s
  %(low_pass)s
  %(high_pass)s
  %(t_r)s
  dtype : {dtype, "auto"}, optional
      Data type toward which the data should be converted. If "auto", the
      data will be converted to int32 if dtype is discrete and float32 if it
      is continuous.
  
  resampling_target : {"data", "labels", None}, default="data"
      Gives which image gives the final shape/size. For example, if
      `resampling_target` is "data", the atlas is resampled to the
      shape of the data if needed. If it is "labels" then mask_img
      and images provided to fit() are resampled to the shape and
      affine of maps_img. "None" means no resampling: if shapes and
      affines do not match, a ValueError is raised.
  %(memory)s
  %(memory_level1)s
  %(verbose0)s
  strategy : :obj:`str`, default='mean'
      The name of a valid function to reduce the region with.
      Must be one of: sum, mean, median, minimum, maximum, variance,
      standard_deviation.
  %(keep_masked_labels)s
  reports : :obj:`bool`, default=True
      If set to True, data is saved in order to produce a report.
  
  %(masker_kwargs)s
  
  Attributes
  ----------
  mask_img_ : :obj:`nibabel.nifti1.Nifti1Image`
      The mask of the data, or the computed one.
  
  labels_img_ : :obj:`nibabel.nifti1.Nifti1Image`
      The labels image.
  
  n_elements_ : :obj:`int`
      The number of discrete values in the mask.
      This is equivalent to the number of unique values in the mask image,
      ignoring the background value.
  
      .. versionadded:: 0.9.2
  
  region_ids_ : dict
      A dictionary containing the region ids corresponding
      to each column in region_signal.
      The region id corresponding to ``region_signal[:,i]``
      is ``region_ids_[i]``.
      ``region_ids_['background']`` is the background label.
  
      .. versionadded:: 0.11.0.dev
  
  region_names_ : dict
      A dictionary containing the region names corresponding
      to each column in region_signal.
      The region names correspond to the labels provided
      in labels in input.
      The region name corresponding to ``region_signal[:,i]``
      is ``region_names_[i]``.
  
      .. versionadded:: 0.11.0.dev
  
  region_atlas_ : Niimg-like object
      Regions definition as labels.
      The labels correspond to the indices in ``region_ids_``.
      The region in ``region_atlas_`` that takes the value ``region_ids_[i]``
      is used to compute the signal in ``region_signal[:,i]``.
  
      .. versionadded:: 0.11.0.dev
  
  See Also
  --------
  nilearn.maskers.NiftiMasker
class_docstr_tok: ["Class","for","masking","of","Niimg-like","objects",".","NiftiLabelsMasker","is","useful","when","data","from","non-overlapping","volumes","should","be","extracted","(","contrarily","to",":","class",":","`","nilearn.maskers.NiftiMapsMasker","`",")",".","Use","case",":","Summarize","brain","signals","from","clusters","that","were","obtained","by","prior","K-means","or","Ward","clustering",".","Parameters","--","--","--","--","--","labels_img",":","Niimg-like","object","See",":","ref",":","`","extracting_data","`",".","Region","definitions",",","as","one","image","of","labels",".","labels",":",":","obj",":","`","list","`","of",":","obj",":","`","str","`",",","optional","Full","labels","corresponding","to","the","labels","image",".","This","is","used","to","improve","reporting","quality","if","provided",".","Warning",":","The","labels","must","be","consistent","with","the","label","values","provided","through","`","labels_img","`",".","background_label",":",":","obj",":","`","int","`","or",":","obj",":","`","float","`",",","default=0","Label","used","in","labels_img","to","represent","background",".","Warning",":","This","value","must","be","consistent","with","label","values","and","image","provided",".","mask_img",":","Niimg-like","object",",","optional","See",":","ref",":","`","extracting_data","`",".","Mask","to","apply","to","regions","before","extracting","signals",".","%","(","smoothing_fwhm",")","s","%","(","standardize_maskers",")","s","%","(","standardize_confounds",")","s","high_variance_confounds",":",":","obj",":","`","bool","`",",","default=False","If","True",",","high","variance","confounds","are","computed","on","provided","image","with",":","func",":","`","nilearn.image.high_variance_confounds","`","and","default","parameters","and","regressed","out",".","%","(","detrend",")","s","%","(","low_pass",")","s","%","(","high_pass",")","s","%","(","t_r",")","s","dtype",":","{","dtype",",","``","auto","''","}",",","optional","Data","type","toward","which","the","data","should","be","converted",".","If","``","auto","''",",","the","data","will","be","converted","to","int32","if","dtype","is","discrete","and","float32","if","it","is","continuous",".","resampling_target",":","{","``","data","''",",","``","labels","''",",","None","}",",","default=","''","data","''","Gives","which","image","gives","the","final","shape\/size",".","For","example",",","if","`","resampling_target","`","is","``","data","''",",","the","atlas","is","resampled","to","the","shape","of","the","data","if","needed",".","If","it","is","``","labels","''","then","mask_img","and","images","provided","to","fit","(",")","are","resampled","to","the","shape","and","affine","of","maps_img",".","``","None","''","means","no","resampling",":","if","shapes","and","affines","do","not","match",",","a","ValueError","is","raised",".","%","(","memory",")","s","%","(","memory_level1",")","s","%","(","verbose0",")","s","strategy",":",":","obj",":","`","str","`",",","default='mean'","The","name","of","a","valid","function","to","reduce","the","region","with",".","Must","be","one","of",":","sum",",","mean",",","median",",","minimum",",","maximum",",","variance",",","standard_deviation",".","%","(","keep_masked_labels",")","s","reports",":",":","obj",":","`","bool","`",",","default=True","If","set","to","True",",","data","is","saved","in","order","to","produce","a","report",".","%","(","masker_kwargs",")","s","Attributes","--","--","--","--","--","mask_img_",":",":","obj",":","`","nibabel.nifti1.Nifti1Image","`","The","mask","of","the","data",",","or","the","computed","one",".","labels_img_",":",":","obj",":","`","nibabel.nifti1.Nifti1Image","`","The","labels","image",".","n_elements_",":",":","obj",":","`","int","`","The","number","of","discrete","values","in","the","mask",".","This","is","equivalent","to","the","number","of","unique","values","in","the","mask","image",",","ignoring","the","background","value",".","..","versionadded",":",":","0.9.2","region_ids_",":","dict","A","dictionary","containing","the","region","ids","corresponding","to","each","column","in","region_signal",".","The","region","id","corresponding","to","``","region_signal","[",":",",i","]","``","is","``","region_ids_","[","i","]","``",".","``","region_ids_","[","'background","'","]","``","is","the","background","label",".","..","versionadded",":",":","0.11.0.dev","region_names_",":","dict","A","dictionary","containing","the","region","names","corresponding","to","each","column","in","region_signal",".","The","region","names","correspond","to","the","labels","provided","in","labels","in","input",".","The","region","name","corresponding","to","``","region_signal","[",":",",i","]","``","is","``","region_names_","[","i","]","``",".","..","versionadded",":",":","0.11.0.dev","region_atlas_",":","Niimg-like","object","Regions","definition","as","labels",".","The","labels","correspond","to","the","indices","in","``","region_ids_","``",".","The","region","in","``","region_atlas_","``","that","takes","the","value","``","region_ids_","[","i","]","``","is","used","to","compute","the","signal","in","``","region_signal","[",":",",i","]","``",".","..","versionadded",":",":","0.11.0.dev","See","Also","--","--","--","--","nilearn.maskers.NiftiMasker"]
docstr: Extract signals from a single 4D niimg.
  
  Parameters
  ----------
  imgs : 3D/4D Niimg-like object
      See :ref:`extracting_data`.
      Images to process.
      If a 3D niimg is provided, a singleton dimension will be added to
      the output to represent the single scan in the niimg.
  
  confounds : CSV file or array-like or :obj:`pandas.DataFrame`, optional
      This parameter is passed to signal.clean. Please see the related
      documentation for details.
      shape: (number of scans, number of confounds)
  
  sample_mask : Any type compatible with numpy-array indexing, optional
      shape: (number of scans - number of volumes removed, )
      Masks the niimgs along time/fourth dimension to perform scrubbing
      (remove volumes with high motion) and/or non-steady-state volumes.
      This parameter is passed to signal.clean.
  
          .. versionadded:: 0.8.0
  
  Returns
  -------
  region_signals : 2D numpy.ndarray
      Signal for each label.
      shape: (number of scans, number of labels)
  
  Warns
  -----
  DeprecationWarning
      If a 3D niimg input is provided, the current behavior
      (adding a singleton dimension to produce a 2D array) is deprecated.
      Starting in version 0.12, a 1D array will be returned for 3D
      inputs.
docstr_tok: ["Extract","signals","from","a","single","4D","niimg",".","Parameters","--","--","--","--","--","imgs",":","3D\/4D","Niimg-like","object","See",":","ref",":","`","extracting_data","`",".","Images","to","process",".","If","a","3D","niimg","is","provided",",","a","singleton","dimension","will","be","added","to","the","output","to","represent","the","single","scan","in","the","niimg",".","confounds",":","CSV","file","or","array-like","or",":","obj",":","`","pandas.DataFrame","`",",","optional","This","parameter","is","passed","to","signal.clean",".","Please","see","the","related","documentation","for","details",".","shape",":","(","number","of","scans",",","number","of","confounds",")","sample_mask",":","Any","type","compatible","with","numpy-array","indexing",",","optional","shape",":","(","number","of","scans","-","number","of","volumes","removed",",",")","Masks","the","niimgs","along","time\/fourth","dimension","to","perform","scrubbing","(","remove","volumes","with","high","motion",")","and\/or","non-steady-state","volumes",".","This","parameter","is","passed","to","signal.clean",".","..","versionadded",":",":","0.8.0","Returns","--","--","--","-","region_signals",":","2D","numpy.ndarray","Signal","for","each","label",".","shape",":","(","number","of","scans",",","number","of","labels",")","Warns","--","--","-","DeprecationWarning","If","a","3D","niimg","input","is","provided",",","the","current","behavior","(","adding","a","singleton","dimension","to","produce","a","2D","array",")","is","deprecated",".","Starting","in","version","0.12",",","a","1D","array","will","be","returned","for","3D","inputs","."]
code: def transform_single_imgs(
      self, imgs, confounds=None, sample_mask=None
  ):
      """Extract signals from a single 4D niimg.
  
      Parameters
      ----------
      imgs : 3D/4D Niimg-like object
          See :ref:`extracting_data`.
          Images to process.
          If a 3D niimg is provided, a singleton dimension will be added to
          the output to represent the single scan in the niimg.
  
      confounds : CSV file or array-like or :obj:`pandas.DataFrame`, optional
          This parameter is passed to signal.clean. Please see the related
          documentation for details.
          shape: (number of scans, number of confounds)
  
      sample_mask : Any type compatible with numpy-array indexing, optional
          shape: (number of scans - number of volumes removed, )
          Masks the niimgs along time/fourth dimension to perform scrubbing
          (remove volumes with high motion) and/or non-steady-state volumes.
          This parameter is passed to signal.clean.
  
              .. versionadded:: 0.8.0
  
      Returns
      -------
      region_signals : 2D numpy.ndarray
          Signal for each label.
          shape: (number of scans, number of labels)
  
      Warns
      -----
      DeprecationWarning
          If a 3D niimg input is provided, the current behavior
          (adding a singleton dimension to produce a 2D array) is deprecated.
          Starting in version 0.12, a 1D array will be returned for 3D
          inputs.
  
      """
      # We handle the resampling of labels separately because the affine of
      # the labels image should not impact the extraction of the signal.
  
      if not hasattr(self, "_resampled_labels_img_"):
          self._resampled_labels_img_ = self.labels_img_
  
      if not hasattr(self, "_resampled_mask_img"):
          self._resampled_mask_img = self.mask_img_
  
      if self.resampling_target == "data":
          imgs_ = _utils.check_niimg(imgs, atleast_4d=True)
          if not _utils.niimg_conversions.check_same_fov(
              imgs_,
              self._resampled_labels_img_,
          ):
              if self.verbose > 0:
                  print("Resampling labels")
              labels_before_resampling = set(
                  np.unique(
                      _utils.niimg.safe_get_data(
                          self._resampled_labels_img_,
                      )
                  )
              )
              self._resampled_labels_img_ = self._cache(
                  image.resample_img, func_memory_level=2
              )(
                  self.labels_img_,
                  interpolation="nearest",
                  target_shape=imgs_.shape[:3],
                  target_affine=imgs_.affine,
              )
              labels_after_resampling = set(
                  np.unique(
                      _utils.niimg.safe_get_data(
                          self._resampled_labels_img_,
                      )
                  )
              )
              labels_diff = labels_before_resampling.difference(
                  labels_after_resampling
              )
              if len(labels_diff) > 0:
                  warnings.warn(
                      "After resampling the label image to the "
                      "data image, the following labels were "
                      f"removed: {labels_diff}. "
                      "Label image only contains "
                      f"{len(labels_after_resampling)} labels "
                      "(including background)."
                  )
  
          if (self.mask_img is not None) and (
              not _utils.niimg_conversions.check_same_fov(
                  imgs_,
                  self._resampled_mask_img,
              )
          ):
              if self.verbose > 0:
                  print("Resampling mask")
              self._resampled_mask_img = self._cache(
                  image.resample_img, func_memory_level=2
              )(
                  self.mask_img_,
                  interpolation="nearest",
                  target_shape=imgs_.shape[:3],
                  target_affine=imgs_.affine,
              )
  
          # Remove imgs_ from memory before loading the same image
          # in filter_and_extract.
          del imgs_
  
      target_shape = None
      target_affine = None
      if self.resampling_target == "labels":
          target_shape = self._resampled_labels_img_.shape[:3]
          target_affine = self._resampled_labels_img_.affine
  
      params = _utils.class_inspect.get_params(
          NiftiLabelsMasker,
          self,
          ignore=["resampling_target"],
      )
      params["target_shape"] = target_shape
      params["target_affine"] = target_affine
      params["clean_kwargs"] = self.clean_kwargs
  
      region_signals, (ids, masked_atlas) = self._cache(
          _filter_and_extract,
          ignore=["verbose", "memory", "memory_level"],
      )(
          # Images
          imgs,
          _ExtractionFunctor(
              self._resampled_labels_img_,
              self.background_label,
              self.strategy,
              self.keep_masked_labels,
              self._resampled_mask_img,
          ),
          # Pre-processing
          params,
          confounds=confounds,
          sample_mask=sample_mask,
          dtype=self.dtype,
          # Caching
          memory=self.memory,
          memory_level=self.memory_level,
          verbose=self.verbose,
      )
  
      self.labels_ = ids
  
      # defining a dictionary containing regions ids
      region_ids = {"background": self.background_label}
      for i in range(region_signals.shape[1]):
          # ids does not include background label
          region_ids[i] = ids[i]
  
      if self.labels is not None:
          self.region_names_ = {
              key: self.labels[region_id]
              for key, region_id in region_ids.items()
              if region_id != self.background_label
          }
      else:
          self.region_names_ = None
      self.region_ids_ = region_ids
      self.region_atlas_ = masked_atlas
  
      return region_signals
  
file_path: nilearn/nilearn/maskers/nifti_labels_masker.py
imports: import warnings
  import numpy
  from joblib import Memory
  from nilearn import _utils, image, masking
  from nilearn.maskers._utils import compute_middle_image
  from nilearn.maskers.base_masker import BaseMasker, _filter_and_extract
label_desc: Use image node_id 7 for calling the NiftiLabelsMasker obj's underlying member method code with example usage: obj.transform_single_imgs(imgs, confounds, sample_mask) and returns: region_signals