Skip to content

Commit 1f1d56d

Browse files
committed
Add image_like function for generic SpatialImage
1 parent 2817d1b commit 1f1d56d

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
@@ -485,7 +485,6 @@ def orthoview(self):
485485
return OrthoSlicer3D(self.dataobj, self.affine,
486486
title=self.get_filename())
487487

488-
489488
def as_reoriented(self, ornt):
490489
"""Apply an orientation change and return a new image
491490
@@ -515,3 +514,11 @@ def as_reoriented(self, ornt):
515514
new_aff = self.affine.dot(inv_ornt_aff(ornt, self.shape))
516515

517516
return self.__class__(t_arr, new_aff, self.header)
517+
518+
519+
def image_like(img, data):
520+
''' Create new SpatialImage with metadata of `img`, and data
521+
contained in `data`.
522+
'''
523+
return img.__class__(data, img.affine, img.header.copy(),
524+
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, image_like)
2020

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

520520
MyHeader()
521521
assert_equal(len(w), 1)
522+
523+
524+
def test_image_like():
525+
zeros = SpatialImage(np.zeros((2, 3, 4)), np.eye(4))
526+
ones = image_like(zeros, np.ones((2, 3, 4)))
527+
528+
assert np.all(ones.dataobj != zeros.dataobj)
529+
assert np.all(ones.affine == zeros.affine)
530+
assert ones.header == zeros.header
531+
assert ones.extra == zeros.extra

0 commit comments

Comments
 (0)