Skip to content

Commit 6b5994e

Browse files
committed
Add image_like function for generic SpatialImage
1 parent 41e126a commit 6b5994e

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

nibabel/__init__.py

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

nibabel/spatialimages.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,6 @@ def orthoview(self):
606606
return OrthoSlicer3D(self.dataobj, self.affine,
607607
title=self.get_filename())
608608

609-
610609
def as_reoriented(self, ornt):
611610
"""Apply an orientation change and return a new image
612611
@@ -636,3 +635,11 @@ def as_reoriented(self, ornt):
636635
new_aff = self.affine.dot(inv_ornt_aff(ornt, self.shape))
637636

638637
return self.__class__(t_arr, new_aff, self.header)
638+
639+
640+
def image_like(img, data):
641+
''' Create new SpatialImage with metadata of `img`, and data
642+
contained in `data`.
643+
'''
644+
return img.__class__(data, img.affine, img.header.copy(),
645+
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 io import BytesIO
1818
from ..spatialimages import (SpatialHeader, SpatialImage, HeaderDataError,
19-
Header, ImageDataError)
19+
Header, ImageDataError, image_like)
2020
from ..imageclasses import spatial_axes_first
2121

2222
from unittest import TestCase
@@ -659,3 +659,13 @@ class MyHeader(Header):
659659

660660
MyHeader()
661661
assert_equal(len(w), 1)
662+
663+
664+
def test_image_like():
665+
zeros = SpatialImage(np.zeros((2, 3, 4)), np.eye(4))
666+
ones = image_like(zeros, np.ones((2, 3, 4)))
667+
668+
assert np.all(ones.dataobj != zeros.dataobj)
669+
assert np.all(ones.affine == zeros.affine)
670+
assert ones.header == zeros.header
671+
assert ones.extra == zeros.extra

0 commit comments

Comments
 (0)