Skip to content

Commit ad9ec16

Browse files
committed
BF - set pixdims from affine when initializing image with affine; thanks to Satra for pointing out the need
1 parent 7e37aa2 commit ad9ec16

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

nibabel/nifti1.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1376,8 +1376,13 @@ def update_header(self):
13761376
hdr = self._header
13771377
hdr['magic'] = 'ni1'
13781378
if not self._affine is None:
1379+
# Set affine into sform
13791380
hdr.set_sform(self._affine, code='aligned')
1381+
# Make qform 'unknown', set voxel sizes from affine
13801382
hdr['qform_code'] = 0
1383+
RZS = self._affine[:3, :3]
1384+
zooms = np.sqrt(np.sum(RZS * RZS, axis=0))
1385+
hdr['pixdim'][1:4] = zooms
13811386

13821387

13831388
class Nifti1Image(Nifti1Pair):

nibabel/tests/test_nifti1.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,24 +628,29 @@ def test_affines_init():
628628
hdr = img.get_header()
629629
assert_equal(hdr['qform_code'], 0)
630630
assert_equal(hdr['sform_code'], 2)
631+
assert_array_equal(hdr.get_zooms(), [2, 3, 4])
631632
# This is also true for affines with header passed
632633
qaff = np.diag([3, 4, 5, 1])
633634
saff = np.diag([6, 7, 8, 1])
634635
hdr.set_qform(qaff, code='scanner')
635636
hdr.set_sform(saff, code='talairach')
637+
assert_array_equal(hdr.get_zooms(), [3, 4, 5])
636638
img = Nifti1Image(arr, aff, hdr)
637639
new_hdr = img.get_header()
638640
# Again affine is sort of anonymous space
639641
assert_equal(new_hdr['qform_code'], 0)
640642
assert_equal(new_hdr['sform_code'], 2)
641643
assert_array_equal(new_hdr.get_sform(), aff)
644+
assert_array_equal(new_hdr.get_zooms(), [2, 3, 4])
642645
# But if no affine passed, codes and matrices stay the same
643646
img = Nifti1Image(arr, None, hdr)
644647
new_hdr = img.get_header()
645648
assert_equal(new_hdr['qform_code'], 1) # scanner
646649
assert_array_equal(new_hdr.get_qform(), qaff)
647650
assert_equal(new_hdr['sform_code'], 3) # Still talairach
648651
assert_array_equal(new_hdr.get_sform(), saff)
652+
# Pixdims as in the original header
653+
assert_array_equal(new_hdr.get_zooms(), [3, 4, 5])
649654

650655

651656

0 commit comments

Comments
 (0)