Skip to content

Commit b57be8e

Browse files
committed
Add image_like function for generic SpatialImage
1 parent 0f7f2a9 commit b57be8e

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

nibabel/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
from .freesurfer import MGHImage
5959
from .funcs import (squeeze_image, concat_images, four_to_three,
6060
as_closest_canonical)
61+
from .spatialimages import image_like
6162
from .orientations import (io_orientation, orientation_affine,
6263
flip_axis, OrientationError,
6364
apply_orientation, aff2axcodes)

nibabel/spatialimages.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,3 +662,11 @@ def __getitem__(self):
662662
raise TypeError("Cannot slice image objects; consider slicing image "
663663
"array data with `img.dataobj[slice]` or "
664664
"`img.get_data()[slice]`")
665+
666+
667+
def image_like(img, data):
668+
''' Create new SpatialImage with metadata of `img`, and data
669+
contained in `data`.
670+
'''
671+
return img.__class__(data, img.affine, img.header.copy(),
672+
extra=img.extra.copy())

nibabel/tests/test_spatialimages.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
from ..externals.six import BytesIO
1818
from ..spatialimages import (SpatialHeader, SpatialImage, HeaderDataError,
19-
Header, ImageDataError)
19+
Header, image_like)
2020

2121
from unittest import TestCase
2222
from nose.tools import (assert_true, assert_false, assert_equal,
@@ -398,3 +398,13 @@ class MyHeader(Header):
398398

399399
MyHeader()
400400
assert_equal(len(w), 1)
401+
402+
403+
def test_image_like():
404+
zeros = SpatialImage(np.zeros((2, 3, 4)), np.eye(4))
405+
ones = image_like(zeros, np.ones((2, 3, 4)))
406+
407+
assert np.all(ones.dataobj != zeros.dataobj)
408+
assert np.all(ones.affine == zeros.affine)
409+
assert ones.header == zeros.header
410+
assert ones.extra == zeros.extra

0 commit comments

Comments
 (0)