Skip to content

Commit da7cd5b

Browse files
committed
ENH + TEST: enforce float image affines
Image affines could be any data type (depending on what was passed). This could be odd when doing things like ``img.get_affine()[0, 0] = 1.1; the value would be truncated if the original affine was an integer type. Obviously this is numpy's default behavior, but we're copying the affine anyway, so casting to float seems ordinary and a bit less surprising.
1 parent 227917e commit da7cd5b

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

nibabel/spatialimages.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,8 +301,9 @@ 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-
# Copy affine to isolate from environment
305-
affine = np.array(affine, copy=True)
304+
# Copy affine to isolate from environment. Specify float type to
305+
# avoid surprising integer rounding when setting values into affine
306+
affine = np.array(affine, dtype=np.float64, copy=True)
306307
if not affine.shape == (4,4):
307308
raise ValueError('Affine should be shape 4,4')
308309
self._affine = affine

nibabel/tests/test_spatialimages.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,15 @@ def test_isolation(self):
194194
ihdr.set_zooms((4,))
195195
assert_not_equal(img.get_header(), ihdr)
196196

197+
def test_float_affine(self):
198+
# Check affines get converted to float
199+
img_klass = self.image_class
200+
arr = np.arange(3, dtype=np.int16)
201+
img = img_klass(arr, np.eye(4, dtype=np.float32))
202+
assert_equal(img.get_affine().dtype, np.dtype(np.float64))
203+
img = img_klass(arr, np.eye(4, dtype=np.int16))
204+
assert_equal(img.get_affine().dtype, np.dtype(np.float64))
205+
197206
def test_images(self):
198207
# Assumes all possible images support int16
199208
# See https://github.com/nipy/nibabel/issues/58

0 commit comments

Comments
 (0)