Skip to content

Commit d5357cb

Browse files
committed
BF+TST - ensure and test for affine, hdr isolation
Spatial images accept affines and headers as input, but they should copy or otherwise isolate them from external changes to the affine, header objects they have been passed.
1 parent 1046c11 commit d5357cb

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

nibabel/spatialimages.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,8 @@ def __init__(self, data, affine, header=None,
301301
# Check that affine is array-like 4,4. Maybe this is too strict at
302302
# this abstract level, but so far I think all image formats we know
303303
# do need 4,4.
304-
affine = np.asarray(affine)
304+
# Copy affine to isolate from environment
305+
affine = np.array(affine, copy=True)
305306
if not affine.shape == (4,4):
306307
raise ValueError('Affine should be shape 4,4')
307308
self._affine = affine

nibabel/tests/test_spatialimages.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,23 @@ class TestSpatialImage(TestCase):
177177
# class for testing images
178178
image_class = SpatialImage
179179

180+
def test_isolation(self):
181+
# Test image isolated from external changes to header and affine
182+
img_klass = self.image_class
183+
arr = np.arange(3, dtype=np.int16)
184+
aff = np.eye(4)
185+
img = img_klass(arr, aff)
186+
assert_array_equal(img.get_affine(), aff)
187+
aff[0,0] = 99
188+
assert_false(np.all(img.get_affine() == aff))
189+
# header, created by image creation
190+
ihdr = img.get_header()
191+
# Pass it back in
192+
img = img_klass(arr, aff, ihdr)
193+
# Check modifying header outside does not modify image
194+
ihdr.set_zooms((4,))
195+
assert_not_equal(img.get_header(), ihdr)
196+
180197
def test_images(self):
181198
# Assumes all possible images support int16
182199
# See https://github.com/nipy/nibabel/issues/58

0 commit comments

Comments
 (0)