|
33 | 33 | InputMultiPath, OutputMultiPath,
|
34 | 34 | BaseInterfaceInputSpec, isdefined,
|
35 | 35 | DynamicTraitedSpec, Undefined)
|
36 |
| -from ..utils.filemanip import fname_presuffix, split_filename |
| 36 | +from ..utils.filemanip import fname_presuffix, split_filename, filename_to_list |
37 | 37 | from ..utils import NUMPY_MMAP
|
38 | 38 |
|
39 | 39 | from . import confounds
|
@@ -1380,6 +1380,51 @@ def merge_rois(in_files, in_idxs, in_ref,
|
1380 | 1380 | return out_file
|
1381 | 1381 |
|
1382 | 1382 |
|
| 1383 | +class CalculateMedianInputSpec(BaseInterfaceInputSpec): |
| 1384 | + in_file = InputMultiPath(File(exists=True, mandatory=True, |
| 1385 | + desc="One or more realigned Nifti 4D timeseries")) |
| 1386 | + median_file = traits.Str('median.nii.gz', usedefault=True, |
| 1387 | + desc="Filename to store median image") |
| 1388 | + |
| 1389 | +class CalculateMedianOutputSpec(TraitedSpec): |
| 1390 | + median_file = File(exists=True) |
| 1391 | + |
| 1392 | +class CalculateMedian(BaseInterface): |
| 1393 | + """ |
| 1394 | + Computes an average of the median across one or more 4D Nifti timeseries |
| 1395 | +
|
| 1396 | + Example |
| 1397 | + ------- |
| 1398 | +
|
| 1399 | + >>> from nipype.algorithms.misc import CalculateMedian |
| 1400 | + >>> mean = CalculateMedian() |
| 1401 | + >>> mean.inputs.in_file = 'functional.nii' |
| 1402 | + >>> mean.run() # doctest: +SKIP |
| 1403 | +
|
| 1404 | + """ |
| 1405 | + input_spec = CalculateMedianInputSpec |
| 1406 | + output_spec = CalculateMedianOutputSpec |
| 1407 | + |
| 1408 | + def _run_interface(self, runtime): |
| 1409 | + total = None |
| 1410 | + for idx, fname in enumerate(filename_to_list(self.inputs.in_file)): |
| 1411 | + img = nb.load(fname, mmap=NUMPY_MMAP) |
| 1412 | + data = np.median(img.get_data(), axis=3) |
| 1413 | + if total is None: |
| 1414 | + total = data |
| 1415 | + else: |
| 1416 | + total += data |
| 1417 | + median_img = nb.Nifti1Image(total/(idx + 1), img.affine, img.header) |
| 1418 | + filename = os.path.join(os.getcwd(), self.inputs.median_file) |
| 1419 | + median_img.to_filename(filename) |
| 1420 | + return runtime |
| 1421 | + |
| 1422 | + def _list_outputs(self): |
| 1423 | + outputs = self._outputs().get() |
| 1424 | + outputs['median_file'] = os.path.abspath(self.inputs.median_file) |
| 1425 | + return outputs |
| 1426 | + |
| 1427 | + |
1383 | 1428 | # Deprecated interfaces ------------------------------------------------------
|
1384 | 1429 |
|
1385 | 1430 | class Distance(nam.Distance):
|
|
0 commit comments