We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
NiftiMasker with target_affine throws exception.
I am using the NifitiMasker in a sklearn pipeline. Everythings works fine until i try to reshape the images:

`nifti_masker = NiftiMasker(target_affine=np.eye(3)*3)`

The error i got was:

`File "/anaconda3/envs/toolbox/lib/python3.6/site-packages/nilearn/masking.py", line 62, in _load_mask_img
    % values)
ValueError: Given mask is not made of 2 values: [-0.0000000e+00  1.4012985e-45  2.8025969e-45 ...  5.1444152e-15
  5.3116801e-15  1.0000000e+00]. Cannot interpret as true or false`

I unsing nilearn version 0.4.2 .

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nilearn/input_data/nifti_masker.py`
Content:
```
1 """
2 Transformer used to apply basic transformations on MRI data.
3 """
4 # Author: Gael Varoquaux, Alexandre Abraham
5 # License: simplified BSD
6 
7 from copy import copy as copy_object
8 
9 from sklearn.externals.joblib import Memory
10 
11 from .base_masker import BaseMasker, filter_and_extract
12 from .. import _utils
13 from .. import image
14 from .. import masking
15 from .._utils import CacheMixin
16 from .._utils.class_inspect import get_params
17 from .._utils.niimg_conversions import _check_same_fov
18 
19 
20 class _ExtractionFunctor(object):
21     func_name = 'nifti_masker_extractor'
22 
23     def __init__(self, mask_img_):
24         self.mask_img_ = mask_img_
25 
26     def __call__(self, imgs):
27         return(masking.apply_mask(imgs, self.mask_img_,
28                                   dtype=imgs.get_data_dtype()), imgs.affine)
29 
30 
31 def filter_and_mask(imgs, mask_img_, parameters,
32                     memory_level=0, memory=Memory(cachedir=None),
33                     verbose=0,
34                     confounds=None,
35                     copy=True,
36                     dtype=None):
37     imgs = _utils.check_niimg(imgs, atleast_4d=True, ensure_ndim=4)
38 
39     # Check whether resampling is truly necessary. If so, crop mask
40     # as small as possible in order to speed up the process
41 
42     if not _check_same_fov(imgs, mask_img_):
43         parameters = copy_object(parameters)
44         # now we can crop
45         mask_img_ = image.crop_img(mask_img_, copy=False)
46         parameters['target_shape'] = mask_img_.shape
47         parameters['target_affine'] = mask_img_.affine
48 
49     data, affine = filter_and_extract(imgs, _ExtractionFunctor(mask_img_),
50                                       parameters,
51                                       memory_level=memory_level,
52                                       memory=memory,
53                                       verbose=verbose,
54                                       confounds=confounds, copy=copy,
55                                       dtype=dtype)
56 
57     # For _later_: missing value removal or imputing of missing data
58     # (i.e. we want to get rid of NaNs, if smoothing must be done
59     # earlier)
60     # Optionally: 'doctor_nan', remove voxels with NaNs, other option
61     # for later: some form of imputation
62     return data
63 
64 
65 class NiftiMasker(BaseMasker, CacheMixin):
66     """Applying a mask to extract time-series from Niimg-like objects.
67 
68     NiftiMasker is useful when preprocessing (detrending, standardization,
69     resampling, etc.) of in-mask voxels is necessary. Use case: working with
70     time series of resting-state or task maps.
71 
72     Parameters
73     ----------
74     mask_img : Niimg-like object, optional
75         See http://nilearn.github.io/manipulating_images/input_output.html
76         Mask for the data. If not given, a mask is computed in the fit step.
77         Optional parameters (mask_args and mask_strategy) can be set to
78         fine tune the mask extraction.
79 
80     sessions : numpy array, optional
81         Add a session level to the preprocessing. Each session will be
82         detrended independently. Must be a 1D array of n_samples elements.
83 
84     smoothing_fwhm : float, optional
85         If smoothing_fwhm is not None, it gives the full-width half maximum in
86         millimeters of the spatial smoothing to apply to the signal.
87 
88     standardize : boolean, optional
89         If standardize is True, the time-series are centered and normed:
90         their mean is put to 0 and their variance to 1 in the time dimension.
91 
92     detrend : boolean, optional
93         This parameter is passed to signal.clean. Please see the related
94         documentation for details
95 
96     low_pass: None or float, optional
97         This parameter is passed to signal.clean. Please see the related
98         documentation for details
99 
100     high_pass: None or float, optional
101         This parameter is passed to signal.clean. Please see the related
102         documentation for details
103 
104     t_r : float, optional
105         This parameter is passed to signal.clean. Please see the related
106         documentation for details
107 
108     target_affine : 3x3 or 4x4 matrix, optional
109         This parameter is passed to image.resample_img. Please see the
110         related documentation for details.
111 
112     target_shape : 3-tuple of integers, optional
113         This parameter is passed to image.resample_img. Please see the
114         related documentation for details.
115 
116     mask_strategy: {'background', 'epi' or 'template'}, optional
117         The strategy used to compute the mask: use 'background' if your
118         images present a clear homogeneous background, 'epi' if they
119         are raw EPI images, or you could use 'template' which will
120         extract the gray matter part of your data by resampling the MNI152
121         brain mask for your data's field of view.
122         Depending on this value, the mask will be computed from
123         masking.compute_background_mask, masking.compute_epi_mask or
124         masking.compute_gray_matter_mask. Default is 'background'.
125 
126     mask_args : dict, optional
127         If mask is None, these are additional parameters passed to
128         masking.compute_background_mask or masking.compute_epi_mask
129         to fine-tune mask computation. Please see the related documentation
130         for details.
131 
132     sample_mask : Any type compatible with numpy-array indexing
133         Masks the niimgs along time/fourth dimension. This complements
134         3D masking by the mask_img argument. This masking step is applied
135         before data preprocessing at the beginning of NiftiMasker.transform.
136         This is useful to perform data subselection as part of a scikit-learn
137         pipeline.
138 
139     `dtype: {dtype, "auto"}
140         Data type toward which the data should be converted. If "auto", the
141         data will be converted to int32 if dtype is discrete and float32 if it
142         is continuous.
143 
144     memory : instance of joblib.Memory or string
145         Used to cache the masking process.
146         By default, no caching is done. If a string is given, it is the
147         path to the caching directory.
148 
149     memory_level : integer, optional
150         Rough estimator of the amount of memory used by caching. Higher value
151         means more memory for caching.
152 
153     verbose : integer, optional
154         Indicate the level of verbosity. By default, nothing is printed
155 
156     Attributes
157     ----------
158     `mask_img_` : nibabel.Nifti1Image
159         The mask of the data, or the computed one.
160 
161     `affine_` : 4x4 numpy array
162         Affine of the transformed image.
163 
164     See also
165     --------
166     nilearn.masking.compute_background_mask
167     nilearn.masking.compute_epi_mask
168     nilearn.image.resample_img
169     nilearn.masking.apply_mask
170     nilearn.signal.clean
171     """
172 
173     def __init__(self, mask_img=None, sessions=None, smoothing_fwhm=None,
174                  standardize=False, detrend=False,
175                  low_pass=None, high_pass=None, t_r=None,
176                  target_affine=None, target_shape=None,
177                  mask_strategy='background',
178                  mask_args=None, sample_mask=None, dtype=None,
179                  memory_level=1, memory=Memory(cachedir=None),
180                  verbose=0
181                  ):
182         # Mask is provided or computed
183         self.mask_img = mask_img
184 
185         self.sessions = sessions
186         self.smoothing_fwhm = smoothing_fwhm
187         self.standardize = standardize
188         self.detrend = detrend
189         self.low_pass = low_pass
190         self.high_pass = high_pass
191         self.t_r = t_r
192         self.target_affine = target_affine
193         self.target_shape = target_shape
194         self.mask_strategy = mask_strategy
195         self.mask_args = mask_args
196         self.sample_mask = sample_mask
197         self.dtype = dtype
198 
199         self.memory = memory
200         self.memory_level = memory_level
201         self.verbose = verbose
202 
203         self._shelving = False
204 
205     def _check_fitted(self):
206         if not hasattr(self, 'mask_img_'):
207             raise ValueError('It seems that %s has not been fitted. '
208                              'You must call fit() before calling transform().'
209                              % self.__class__.__name__)
210 
211     def fit(self, imgs=None, y=None):
212         """Compute the mask corresponding to the data
213 
214         Parameters
215         ----------
216         imgs: list of Niimg-like objects
217             See http://nilearn.github.io/manipulating_images/input_output.html
218             Data on which the mask must be calculated. If this is a list,
219             the affine is considered the same for all.
220         """
221         # y=None is for scikit-learn compatibility (unused here).
222 
223         # Load data (if filenames are given, load them)
224         if self.verbose > 0:
225             print("[%s.fit] Loading data from %s" % (
226                 self.__class__.__name__,
227                 _utils._repr_niimgs(imgs)[:200]))
228 
229         # Compute the mask if not given by the user
230         if self.mask_img is None:
231             mask_args = (self.mask_args if self.mask_args is not None
232                          else {})
233             if self.mask_strategy == 'background':
234                 compute_mask = masking.compute_background_mask
235             elif self.mask_strategy == 'epi':
236                 compute_mask = masking.compute_epi_mask
237             elif self.mask_strategy == 'template':
238                 compute_mask = masking.compute_gray_matter_mask
239             else:
240                 raise ValueError("Unknown value of mask_strategy '%s'. "
241                                  "Acceptable values are 'background', "
242                                  "'epi' and 'template'." % self.mask_strategy)
243             if self.verbose > 0:
244                 print("[%s.fit] Computing the mask" % self.__class__.__name__)
245             self.mask_img_ = self._cache(compute_mask, ignore=['verbose'])(
246                 imgs, verbose=max(0, self.verbose - 1), **mask_args)
247         else:
248             self.mask_img_ = _utils.check_niimg_3d(self.mask_img)
249 
250         # If resampling is requested, resample also the mask
251         # Resampling: allows the user to change the affine, the shape or both
252         if self.verbose > 0:
253             print("[%s.fit] Resampling mask" % self.__class__.__name__)
254         self.mask_img_ = self._cache(image.resample_img)(
255             self.mask_img_,
256             target_affine=self.target_affine,
257             target_shape=self.target_shape,
258             copy=False)
259         if self.target_affine is not None:
260             self.affine_ = self.target_affine
261         else:
262             self.affine_ = self.mask_img_.affine
263         # Load data in memory
264         self.mask_img_.get_data()
265         if self.verbose > 10:
266             print("[%s.fit] Finished fit" % self.__class__.__name__)
267         return self
268 
269     def transform_single_imgs(self, imgs, confounds=None, copy=True):
270         """Apply mask, spatial and temporal preprocessing
271 
272         Parameters
273         ----------
274         imgs: 3D/4D Niimg-like object
275             See http://nilearn.github.io/manipulating_images/input_output.html
276             Images to process. It must boil down to a 4D image with scans
277             number as last dimension.
278 
279         confounds: CSV file or array-like, optional
280             This parameter is passed to signal.clean. Please see the related
281             documentation for details.
282             shape: (number of scans, number of confounds)
283 
284         Returns
285         -------
286         region_signals: 2D numpy.ndarray
287             Signal for each voxel inside the mask.
288             shape: (number of scans, number of voxels)
289         """
290 
291         # Ignore the mask-computing params: they are not useful and will
292         # just invalid the cache for no good reason
293         # target_shape and target_affine are conveyed implicitly in mask_img
294         params = get_params(self.__class__, self,
295                             ignore=['mask_img', 'mask_args', 'mask_strategy'])
296 
297         data = self._cache(filter_and_mask,
298                            ignore=['verbose', 'memory', 'memory_level',
299                                    'copy'],
300                            shelve=self._shelving)(
301             imgs, self.mask_img_, params,
302             memory_level=self.memory_level,
303             memory=self.memory,
304             verbose=self.verbose,
305             confounds=confounds,
306             copy=copy,
307             dtype=self.dtype
308         )
309 
310         return data
311
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/nilearn/input_data/nifti_masker.py b/nilearn/input_data/nifti_masker.py
--- a/nilearn/input_data/nifti_masker.py
+++ b/nilearn/input_data/nifti_masker.py
@@ -255,7 +255,7 @@
             self.mask_img_,
             target_affine=self.target_affine,
             target_shape=self.target_shape,
-            copy=False)
+            copy=False, interpolation='nearest')
         if self.target_affine is not None:
             self.affine_ = self.target_affine
         else:

{"golden_diff": "diff --git a/nilearn/input_data/nifti_masker.py b/nilearn/input_data/nifti_masker.py\n--- a/nilearn/input_data/nifti_masker.py\n+++ b/nilearn/input_data/nifti_masker.py\n@@ -255,7 +255,7 @@\n             self.mask_img_,\n             target_affine=self.target_affine,\n             target_shape=self.target_shape,\n-            copy=False)\n+            copy=False, interpolation='nearest')\n         if self.target_affine is not None:\n             self.affine_ = self.target_affine\n         else:\n", "issue": "NiftiMasker with target_affine throws exception.\nI am using the NifitiMasker in a sklearn pipeline. Everythings works fine until i try to reshape the images:\r\n\r\n`nifti_masker = NiftiMasker(target_affine=np.eye(3)*3)`\r\n\r\nThe error i got was:\r\n\r\n`File \"/anaconda3/envs/toolbox/lib/python3.6/site-packages/nilearn/masking.py\", line 62, in _load_mask_img\r\n    % values)\r\nValueError: Given mask is not made of 2 values: [-0.0000000e+00  1.4012985e-45  2.8025969e-45 ...  5.1444152e-15\r\n  5.3116801e-15  1.0000000e+00]. Cannot interpret as true or false`\r\n\r\nI unsing nilearn version 0.4.2 .\n", "before_files": [{"content": "\"\"\"\nTransformer used to apply basic transformations on MRI data.\n\"\"\"\n# Author: Gael Varoquaux, Alexandre Abraham\n# License: simplified BSD\n\nfrom copy import copy as copy_object\n\nfrom sklearn.externals.joblib import Memory\n\nfrom .base_masker import BaseMasker, filter_and_extract\nfrom .. import _utils\nfrom .. import image\nfrom .. import masking\nfrom .._utils import CacheMixin\nfrom .._utils.class_inspect import get_params\nfrom .._utils.niimg_conversions import _check_same_fov\n\n\nclass _ExtractionFunctor(object):\n    func_name = 'nifti_masker_extractor'\n\n    def __init__(self, mask_img_):\n        self.mask_img_ = mask_img_\n\n    def __call__(self, imgs):\n        return(masking.apply_mask(imgs, self.mask_img_,\n                                  dtype=imgs.get_data_dtype()), imgs.affine)\n\n\ndef filter_and_mask(imgs, mask_img_, parameters,\n                    memory_level=0, memory=Memory(cachedir=None),\n                    verbose=0,\n                    confounds=None,\n                    copy=True,\n                    dtype=None):\n    imgs = _utils.check_niimg(imgs, atleast_4d=True, ensure_ndim=4)\n\n    # Check whether resampling is truly necessary. If so, crop mask\n    # as small as possible in order to speed up the process\n\n    if not _check_same_fov(imgs, mask_img_):\n        parameters = copy_object(parameters)\n        # now we can crop\n        mask_img_ = image.crop_img(mask_img_, copy=False)\n        parameters['target_shape'] = mask_img_.shape\n        parameters['target_affine'] = mask_img_.affine\n\n    data, affine = filter_and_extract(imgs, _ExtractionFunctor(mask_img_),\n                                      parameters,\n                                      memory_level=memory_level,\n                                      memory=memory,\n                                      verbose=verbose,\n                                      confounds=confounds, copy=copy,\n                                      dtype=dtype)\n\n    # For _later_: missing value removal or imputing of missing data\n    # (i.e. we want to get rid of NaNs, if smoothing must be done\n    # earlier)\n    # Optionally: 'doctor_nan', remove voxels with NaNs, other option\n    # for later: some form of imputation\n    return data\n\n\nclass NiftiMasker(BaseMasker, CacheMixin):\n    \"\"\"Applying a mask to extract time-series from Niimg-like objects.\n\n    NiftiMasker is useful when preprocessing (detrending, standardization,\n    resampling, etc.) of in-mask voxels is necessary. Use case: working with\n    time series of resting-state or task maps.\n\n    Parameters\n    ----------\n    mask_img : Niimg-like object, optional\n        See http://nilearn.github.io/manipulating_images/input_output.html\n        Mask for the data. If not given, a mask is computed in the fit step.\n        Optional parameters (mask_args and mask_strategy) can be set to\n        fine tune the mask extraction.\n\n    sessions : numpy array, optional\n        Add a session level to the preprocessing. Each session will be\n        detrended independently. Must be a 1D array of n_samples elements.\n\n    smoothing_fwhm : float, optional\n        If smoothing_fwhm is not None, it gives the full-width half maximum in\n        millimeters of the spatial smoothing to apply to the signal.\n\n    standardize : boolean, optional\n        If standardize is True, the time-series are centered and normed:\n        their mean is put to 0 and their variance to 1 in the time dimension.\n\n    detrend : boolean, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    low_pass: None or float, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    high_pass: None or float, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    t_r : float, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    target_affine : 3x3 or 4x4 matrix, optional\n        This parameter is passed to image.resample_img. Please see the\n        related documentation for details.\n\n    target_shape : 3-tuple of integers, optional\n        This parameter is passed to image.resample_img. Please see the\n        related documentation for details.\n\n    mask_strategy: {'background', 'epi' or 'template'}, optional\n        The strategy used to compute the mask: use 'background' if your\n        images present a clear homogeneous background, 'epi' if they\n        are raw EPI images, or you could use 'template' which will\n        extract the gray matter part of your data by resampling the MNI152\n        brain mask for your data's field of view.\n        Depending on this value, the mask will be computed from\n        masking.compute_background_mask, masking.compute_epi_mask or\n        masking.compute_gray_matter_mask. Default is 'background'.\n\n    mask_args : dict, optional\n        If mask is None, these are additional parameters passed to\n        masking.compute_background_mask or masking.compute_epi_mask\n        to fine-tune mask computation. Please see the related documentation\n        for details.\n\n    sample_mask : Any type compatible with numpy-array indexing\n        Masks the niimgs along time/fourth dimension. This complements\n        3D masking by the mask_img argument. This masking step is applied\n        before data preprocessing at the beginning of NiftiMasker.transform.\n        This is useful to perform data subselection as part of a scikit-learn\n        pipeline.\n\n    `dtype: {dtype, \"auto\"}\n        Data type toward which the data should be converted. If \"auto\", the\n        data will be converted to int32 if dtype is discrete and float32 if it\n        is continuous.\n\n    memory : instance of joblib.Memory or string\n        Used to cache the masking process.\n        By default, no caching is done. If a string is given, it is the\n        path to the caching directory.\n\n    memory_level : integer, optional\n        Rough estimator of the amount of memory used by caching. Higher value\n        means more memory for caching.\n\n    verbose : integer, optional\n        Indicate the level of verbosity. By default, nothing is printed\n\n    Attributes\n    ----------\n    `mask_img_` : nibabel.Nifti1Image\n        The mask of the data, or the computed one.\n\n    `affine_` : 4x4 numpy array\n        Affine of the transformed image.\n\n    See also\n    --------\n    nilearn.masking.compute_background_mask\n    nilearn.masking.compute_epi_mask\n    nilearn.image.resample_img\n    nilearn.masking.apply_mask\n    nilearn.signal.clean\n    \"\"\"\n\n    def __init__(self, mask_img=None, sessions=None, smoothing_fwhm=None,\n                 standardize=False, detrend=False,\n                 low_pass=None, high_pass=None, t_r=None,\n                 target_affine=None, target_shape=None,\n                 mask_strategy='background',\n                 mask_args=None, sample_mask=None, dtype=None,\n                 memory_level=1, memory=Memory(cachedir=None),\n                 verbose=0\n                 ):\n        # Mask is provided or computed\n        self.mask_img = mask_img\n\n        self.sessions = sessions\n        self.smoothing_fwhm = smoothing_fwhm\n        self.standardize = standardize\n        self.detrend = detrend\n        self.low_pass = low_pass\n        self.high_pass = high_pass\n        self.t_r = t_r\n        self.target_affine = target_affine\n        self.target_shape = target_shape\n        self.mask_strategy = mask_strategy\n        self.mask_args = mask_args\n        self.sample_mask = sample_mask\n        self.dtype = dtype\n\n        self.memory = memory\n        self.memory_level = memory_level\n        self.verbose = verbose\n\n        self._shelving = False\n\n    def _check_fitted(self):\n        if not hasattr(self, 'mask_img_'):\n            raise ValueError('It seems that %s has not been fitted. '\n                             'You must call fit() before calling transform().'\n                             % self.__class__.__name__)\n\n    def fit(self, imgs=None, y=None):\n        \"\"\"Compute the mask corresponding to the data\n\n        Parameters\n        ----------\n        imgs: list of Niimg-like objects\n            See http://nilearn.github.io/manipulating_images/input_output.html\n            Data on which the mask must be calculated. If this is a list,\n            the affine is considered the same for all.\n        \"\"\"\n        # y=None is for scikit-learn compatibility (unused here).\n\n        # Load data (if filenames are given, load them)\n        if self.verbose > 0:\n            print(\"[%s.fit] Loading data from %s\" % (\n                self.__class__.__name__,\n                _utils._repr_niimgs(imgs)[:200]))\n\n        # Compute the mask if not given by the user\n        if self.mask_img is None:\n            mask_args = (self.mask_args if self.mask_args is not None\n                         else {})\n            if self.mask_strategy == 'background':\n                compute_mask = masking.compute_background_mask\n            elif self.mask_strategy == 'epi':\n                compute_mask = masking.compute_epi_mask\n            elif self.mask_strategy == 'template':\n                compute_mask = masking.compute_gray_matter_mask\n            else:\n                raise ValueError(\"Unknown value of mask_strategy '%s'. \"\n                                 \"Acceptable values are 'background', \"\n                                 \"'epi' and 'template'.\" % self.mask_strategy)\n            if self.verbose > 0:\n                print(\"[%s.fit] Computing the mask\" % self.__class__.__name__)\n            self.mask_img_ = self._cache(compute_mask, ignore=['verbose'])(\n                imgs, verbose=max(0, self.verbose - 1), **mask_args)\n        else:\n            self.mask_img_ = _utils.check_niimg_3d(self.mask_img)\n\n        # If resampling is requested, resample also the mask\n        # Resampling: allows the user to change the affine, the shape or both\n        if self.verbose > 0:\n            print(\"[%s.fit] Resampling mask\" % self.__class__.__name__)\n        self.mask_img_ = self._cache(image.resample_img)(\n            self.mask_img_,\n            target_affine=self.target_affine,\n            target_shape=self.target_shape,\n            copy=False)\n        if self.target_affine is not None:\n            self.affine_ = self.target_affine\n        else:\n            self.affine_ = self.mask_img_.affine\n        # Load data in memory\n        self.mask_img_.get_data()\n        if self.verbose > 10:\n            print(\"[%s.fit] Finished fit\" % self.__class__.__name__)\n        return self\n\n    def transform_single_imgs(self, imgs, confounds=None, copy=True):\n        \"\"\"Apply mask, spatial and temporal preprocessing\n\n        Parameters\n        ----------\n        imgs: 3D/4D Niimg-like object\n            See http://nilearn.github.io/manipulating_images/input_output.html\n            Images to process. It must boil down to a 4D image with scans\n            number as last dimension.\n\n        confounds: CSV file or array-like, optional\n            This parameter is passed to signal.clean. Please see the related\n            documentation for details.\n            shape: (number of scans, number of confounds)\n\n        Returns\n        -------\n        region_signals: 2D numpy.ndarray\n            Signal for each voxel inside the mask.\n            shape: (number of scans, number of voxels)\n        \"\"\"\n\n        # Ignore the mask-computing params: they are not useful and will\n        # just invalid the cache for no good reason\n        # target_shape and target_affine are conveyed implicitly in mask_img\n        params = get_params(self.__class__, self,\n                            ignore=['mask_img', 'mask_args', 'mask_strategy'])\n\n        data = self._cache(filter_and_mask,\n                           ignore=['verbose', 'memory', 'memory_level',\n                                   'copy'],\n                           shelve=self._shelving)(\n            imgs, self.mask_img_, params,\n            memory_level=self.memory_level,\n            memory=self.memory,\n            verbose=self.verbose,\n            confounds=confounds,\n            copy=copy,\n            dtype=self.dtype\n        )\n\n        return data\n", "path": "nilearn/input_data/nifti_masker.py"}], "after_files": [{"content": "\"\"\"\nTransformer used to apply basic transformations on MRI data.\n\"\"\"\n# Author: Gael Varoquaux, Alexandre Abraham\n# License: simplified BSD\n\nfrom copy import copy as copy_object\n\nfrom sklearn.externals.joblib import Memory\n\nfrom .base_masker import BaseMasker, filter_and_extract\nfrom .. import _utils\nfrom .. import image\nfrom .. import masking\nfrom .._utils import CacheMixin\nfrom .._utils.class_inspect import get_params\nfrom .._utils.niimg_conversions import _check_same_fov\n\n\nclass _ExtractionFunctor(object):\n    func_name = 'nifti_masker_extractor'\n\n    def __init__(self, mask_img_):\n        self.mask_img_ = mask_img_\n\n    def __call__(self, imgs):\n        return(masking.apply_mask(imgs, self.mask_img_,\n                                  dtype=imgs.get_data_dtype()), imgs.affine)\n\n\ndef filter_and_mask(imgs, mask_img_, parameters,\n                    memory_level=0, memory=Memory(cachedir=None),\n                    verbose=0,\n                    confounds=None,\n                    copy=True,\n                    dtype=None):\n    imgs = _utils.check_niimg(imgs, atleast_4d=True, ensure_ndim=4)\n\n    # Check whether resampling is truly necessary. If so, crop mask\n    # as small as possible in order to speed up the process\n\n    if not _check_same_fov(imgs, mask_img_):\n        parameters = copy_object(parameters)\n        # now we can crop\n        mask_img_ = image.crop_img(mask_img_, copy=False)\n        parameters['target_shape'] = mask_img_.shape\n        parameters['target_affine'] = mask_img_.affine\n\n    data, affine = filter_and_extract(imgs, _ExtractionFunctor(mask_img_),\n                                      parameters,\n                                      memory_level=memory_level,\n                                      memory=memory,\n                                      verbose=verbose,\n                                      confounds=confounds, copy=copy,\n                                      dtype=dtype)\n\n    # For _later_: missing value removal or imputing of missing data\n    # (i.e. we want to get rid of NaNs, if smoothing must be done\n    # earlier)\n    # Optionally: 'doctor_nan', remove voxels with NaNs, other option\n    # for later: some form of imputation\n    return data\n\n\nclass NiftiMasker(BaseMasker, CacheMixin):\n    \"\"\"Applying a mask to extract time-series from Niimg-like objects.\n\n    NiftiMasker is useful when preprocessing (detrending, standardization,\n    resampling, etc.) of in-mask voxels is necessary. Use case: working with\n    time series of resting-state or task maps.\n\n    Parameters\n    ----------\n    mask_img : Niimg-like object, optional\n        See http://nilearn.github.io/manipulating_images/input_output.html\n        Mask for the data. If not given, a mask is computed in the fit step.\n        Optional parameters (mask_args and mask_strategy) can be set to\n        fine tune the mask extraction.\n\n    sessions : numpy array, optional\n        Add a session level to the preprocessing. Each session will be\n        detrended independently. Must be a 1D array of n_samples elements.\n\n    smoothing_fwhm : float, optional\n        If smoothing_fwhm is not None, it gives the full-width half maximum in\n        millimeters of the spatial smoothing to apply to the signal.\n\n    standardize : boolean, optional\n        If standardize is True, the time-series are centered and normed:\n        their mean is put to 0 and their variance to 1 in the time dimension.\n\n    detrend : boolean, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    low_pass: None or float, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    high_pass: None or float, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    t_r : float, optional\n        This parameter is passed to signal.clean. Please see the related\n        documentation for details\n\n    target_affine : 3x3 or 4x4 matrix, optional\n        This parameter is passed to image.resample_img. Please see the\n        related documentation for details.\n\n    target_shape : 3-tuple of integers, optional\n        This parameter is passed to image.resample_img. Please see the\n        related documentation for details.\n\n    mask_strategy: {'background', 'epi' or 'template'}, optional\n        The strategy used to compute the mask: use 'background' if your\n        images present a clear homogeneous background, 'epi' if they\n        are raw EPI images, or you could use 'template' which will\n        extract the gray matter part of your data by resampling the MNI152\n        brain mask for your data's field of view.\n        Depending on this value, the mask will be computed from\n        masking.compute_background_mask, masking.compute_epi_mask or\n        masking.compute_gray_matter_mask. Default is 'background'.\n\n    mask_args : dict, optional\n        If mask is None, these are additional parameters passed to\n        masking.compute_background_mask or masking.compute_epi_mask\n        to fine-tune mask computation. Please see the related documentation\n        for details.\n\n    sample_mask : Any type compatible with numpy-array indexing\n        Masks the niimgs along time/fourth dimension. This complements\n        3D masking by the mask_img argument. This masking step is applied\n        before data preprocessing at the beginning of NiftiMasker.transform.\n        This is useful to perform data subselection as part of a scikit-learn\n        pipeline.\n\n    `dtype: {dtype, \"auto\"}\n        Data type toward which the data should be converted. If \"auto\", the\n        data will be converted to int32 if dtype is discrete and float32 if it\n        is continuous.\n\n    memory : instance of joblib.Memory or string\n        Used to cache the masking process.\n        By default, no caching is done. If a string is given, it is the\n        path to the caching directory.\n\n    memory_level : integer, optional\n        Rough estimator of the amount of memory used by caching. Higher value\n        means more memory for caching.\n\n    verbose : integer, optional\n        Indicate the level of verbosity. By default, nothing is printed\n\n    Attributes\n    ----------\n    `mask_img_` : nibabel.Nifti1Image\n        The mask of the data, or the computed one.\n\n    `affine_` : 4x4 numpy array\n        Affine of the transformed image.\n\n    See also\n    --------\n    nilearn.masking.compute_background_mask\n    nilearn.masking.compute_epi_mask\n    nilearn.image.resample_img\n    nilearn.masking.apply_mask\n    nilearn.signal.clean\n    \"\"\"\n\n    def __init__(self, mask_img=None, sessions=None, smoothing_fwhm=None,\n                 standardize=False, detrend=False,\n                 low_pass=None, high_pass=None, t_r=None,\n                 target_affine=None, target_shape=None,\n                 mask_strategy='background',\n                 mask_args=None, sample_mask=None, dtype=None,\n                 memory_level=1, memory=Memory(cachedir=None),\n                 verbose=0\n                 ):\n        # Mask is provided or computed\n        self.mask_img = mask_img\n\n        self.sessions = sessions\n        self.smoothing_fwhm = smoothing_fwhm\n        self.standardize = standardize\n        self.detrend = detrend\n        self.low_pass = low_pass\n        self.high_pass = high_pass\n        self.t_r = t_r\n        self.target_affine = target_affine\n        self.target_shape = target_shape\n        self.mask_strategy = mask_strategy\n        self.mask_args = mask_args\n        self.sample_mask = sample_mask\n        self.dtype = dtype\n\n        self.memory = memory\n        self.memory_level = memory_level\n        self.verbose = verbose\n\n        self._shelving = False\n\n    def _check_fitted(self):\n        if not hasattr(self, 'mask_img_'):\n            raise ValueError('It seems that %s has not been fitted. '\n                             'You must call fit() before calling transform().'\n                             % self.__class__.__name__)\n\n    def fit(self, imgs=None, y=None):\n        \"\"\"Compute the mask corresponding to the data\n\n        Parameters\n        ----------\n        imgs: list of Niimg-like objects\n            See http://nilearn.github.io/manipulating_images/input_output.html\n            Data on which the mask must be calculated. If this is a list,\n            the affine is considered the same for all.\n        \"\"\"\n        # y=None is for scikit-learn compatibility (unused here).\n\n        # Load data (if filenames are given, load them)\n        if self.verbose > 0:\n            print(\"[%s.fit] Loading data from %s\" % (\n                self.__class__.__name__,\n                _utils._repr_niimgs(imgs)[:200]))\n\n        # Compute the mask if not given by the user\n        if self.mask_img is None:\n            mask_args = (self.mask_args if self.mask_args is not None\n                         else {})\n            if self.mask_strategy == 'background':\n                compute_mask = masking.compute_background_mask\n            elif self.mask_strategy == 'epi':\n                compute_mask = masking.compute_epi_mask\n            elif self.mask_strategy == 'template':\n                compute_mask = masking.compute_gray_matter_mask\n            else:\n                raise ValueError(\"Unknown value of mask_strategy '%s'. \"\n                                 \"Acceptable values are 'background', \"\n                                 \"'epi' and 'template'.\" % self.mask_strategy)\n            if self.verbose > 0:\n                print(\"[%s.fit] Computing the mask\" % self.__class__.__name__)\n            self.mask_img_ = self._cache(compute_mask, ignore=['verbose'])(\n                imgs, verbose=max(0, self.verbose - 1), **mask_args)\n        else:\n            self.mask_img_ = _utils.check_niimg_3d(self.mask_img)\n\n        # If resampling is requested, resample also the mask\n        # Resampling: allows the user to change the affine, the shape or both\n        if self.verbose > 0:\n            print(\"[%s.fit] Resampling mask\" % self.__class__.__name__)\n        self.mask_img_ = self._cache(image.resample_img)(\n            self.mask_img_,\n            target_affine=self.target_affine,\n            target_shape=self.target_shape,\n            copy=False, interpolation='nearest')\n        if self.target_affine is not None:\n            self.affine_ = self.target_affine\n        else:\n            self.affine_ = self.mask_img_.affine\n        # Load data in memory\n        self.mask_img_.get_data()\n        if self.verbose > 10:\n            print(\"[%s.fit] Finished fit\" % self.__class__.__name__)\n        return self\n\n    def transform_single_imgs(self, imgs, confounds=None, copy=True):\n        \"\"\"Apply mask, spatial and temporal preprocessing\n\n        Parameters\n        ----------\n        imgs: 3D/4D Niimg-like object\n            See http://nilearn.github.io/manipulating_images/input_output.html\n            Images to process. It must boil down to a 4D image with scans\n            number as last dimension.\n\n        confounds: CSV file or array-like, optional\n            This parameter is passed to signal.clean. Please see the related\n            documentation for details.\n            shape: (number of scans, number of confounds)\n\n        Returns\n        -------\n        region_signals: 2D numpy.ndarray\n            Signal for each voxel inside the mask.\n            shape: (number of scans, number of voxels)\n        \"\"\"\n\n        # Ignore the mask-computing params: they are not useful and will\n        # just invalid the cache for no good reason\n        # target_shape and target_affine are conveyed implicitly in mask_img\n        params = get_params(self.__class__, self,\n                            ignore=['mask_img', 'mask_args', 'mask_strategy'])\n\n        data = self._cache(filter_and_mask,\n                           ignore=['verbose', 'memory', 'memory_level',\n                                   'copy'],\n                           shelve=self._shelving)(\n            imgs, self.mask_img_, params,\n            memory_level=self.memory_level,\n            memory=self.memory,\n            verbose=self.verbose,\n            confounds=confounds,\n            copy=copy,\n            dtype=self.dtype\n        )\n\n        return data\n", "path": "nilearn/input_data/nifti_masker.py"}]}