diff --git a/fsl/data/image.py b/fsl/data/image.py index 0dbd331af452c1e2c23beeaca7a4ea2b77c29672..3dfe8a818286126c98939d83a3979f2f363cb375 100644 --- a/fsl/data/image.py +++ b/fsl/data/image.py @@ -46,6 +46,8 @@ import numpy as np import nibabel as nib import nibabel.fileslice as fileslice +from pathlib import Path + import fsl.utils.meta as meta import fsl.transform.affine as affine import fsl.utils.notifier as notifier @@ -1004,8 +1006,9 @@ class Image(Nifti): """Create an ``Image`` object with the given image data or file name. :arg image: A string containing the name of an image file to load, - or a :mod:`numpy` array, or a :mod:`nibabel` image - object, or an ``Image`` object. + or a Path object pointing to an image file, or a + :mod:`numpy` array, or a :mod:`nibabel` image object, + or an ``Image`` object. :arg name: A name for the image. @@ -1088,6 +1091,11 @@ class Image(Nifti): nibImage = nib.load(image, **kwargs) dataSource = image saved = True + # The image parameter may be a Path object pointing to an image file + elif isinstance(image, Path): + nibImage = nib.load(image, **kwargs) + dataSource = str(image) + saved = True # Or a numpy array - we wrap it in a nibabel image, # with an identity transformation (each voxel maps @@ -1140,6 +1148,8 @@ class Image(Nifti): # from disk, use the file name. if isinstance(image, six.string_types): name = removeExt(op.basename(image)) + elif isinstance(image, Path): + name = image.name # Or the image was created from a numpy array elif isinstance(image, np.ndarray): diff --git a/tests/test_image.py b/tests/test_image.py index b7de2def252e4f8bf4edcf672ebb773eafc38ee5..e2e7f213f0d7c791737c62ceb9eaa57a75f42344 100644 --- a/tests/test_image.py +++ b/tests/test_image.py @@ -12,6 +12,8 @@ import json import os.path as op import itertools as it +from pathlib import Path + import pytest import numpy as np @@ -148,6 +150,7 @@ def test_load(): # Not raising an error means the test passes for fname in shouldPass: fslimage.Image(op.join(testdir, fname)) + fslimage.Image(Path(testdir) / fname) # These should raise an error for fname, exc in shouldRaise: