Skip to content

ENH: Add image_like function for SpatialImages #300

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions nibabel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def setup_test():
from .freesurfer import MGHImage
from .funcs import (squeeze_image, concat_images, four_to_three,
as_closest_canonical)
from .spatialimages import image_like
from .orientations import (io_orientation, orientation_affine,
flip_axis, OrientationError,
apply_orientation, aff2axcodes)
Expand Down
11 changes: 9 additions & 2 deletions nibabel/spatialimages.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ def get_affine(self):
return self.affine

@classmethod
def from_image(klass, img):
def from_image(klass, img, data=None):
''' Class method to create new instance of own class from `img`

Parameters
Expand All @@ -551,7 +551,7 @@ def from_image(klass, img):
cimg : ``spatialimage`` instance
Image, of our own class
'''
return klass(img.dataobj,
return klass(img.dataobj if data is None else data,
img.affine,
klass.header_class.from_header(img.header),
extra=img.extra.copy())
Expand Down Expand Up @@ -634,3 +634,10 @@ def as_reoriented(self, ornt):
new_aff = self.affine.dot(inv_ornt_aff(ornt, self.shape))

return self.__class__(t_arr, new_aff, self.header)


def image_like(img, data):
''' Create new SpatialImage with metadata of `img`, and data
contained in `data`.
'''
return img.from_image(img, data)
12 changes: 11 additions & 1 deletion nibabel/tests/test_spatialimages.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from io import BytesIO
from ..spatialimages import (SpatialHeader, SpatialImage, HeaderDataError,
Header, ImageDataError)
Header, ImageDataError, image_like)
from ..imageclasses import spatial_axes_first

from unittest import TestCase
Expand Down Expand Up @@ -659,3 +659,13 @@ class MyHeader(Header):

MyHeader()
assert_equal(len(w), 1)


def test_image_like():
zeros = SpatialImage(np.zeros((2, 3, 4)), np.eye(4))
ones = image_like(zeros, np.ones((2, 3, 4)))

assert np.all(ones.dataobj != zeros.dataobj)
assert np.all(ones.affine == zeros.affine)
assert ones.header == zeros.header
assert ones.extra == zeros.extra