Skip to content

Commit c3794be

Browse files
committed
RF: Simplify to/from affine
1 parent 10c6d68 commit c3794be

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

nibabel/freesurfer/mghformat.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from os.path import splitext
1414
import numpy as np
1515

16+
from ..affines import voxel_sizes
1617
from ..volumeutils import (array_to_file, array_from_file, Recoder)
1718
from ..spatialimages import HeaderDataError, SpatialImage
1819
from ..fileholders import FileHolder
@@ -152,15 +153,14 @@ def get_affine(self):
152153
from the zooms ( delta ), direction cosines ( Mdc ), RAS centers (
153154
c_ras ) and the dimensions.
154155
'''
156+
affine = np.eye(4)
155157
hdr = self._structarr
156158
d = np.diag(hdr['delta'])
157159
pcrs_c = hdr['dims'][:3] / 2.0
158-
Mdc = np.hstack((hdr['x_ras'], hdr['y_ras'], hdr['z_ras']))
159-
pxyz_0 = hdr['c_ras'] - Mdc.dot(d).dot(pcrs_c.reshape(3, 1))
160-
M = np.eye(4, 4)
161-
M[:3, :3] = np.dot(Mdc, d)
162-
M[:3, [3]] = pxyz_0
163-
return M
160+
MdcD = np.hstack((hdr['x_ras'], hdr['y_ras'], hdr['z_ras'])).dot(d)
161+
affine[:3, :3] = MdcD
162+
affine[:3, [3]] = hdr['c_ras'] - MdcD.dot(pcrs_c.reshape(3, 1))
163+
return affine
164164

165165
# For compatibility with nifti (multiple affines)
166166
get_best_affine = get_affine
@@ -527,16 +527,14 @@ def _write_data(self, mghfile, data, header):
527527
def _affine2header(self):
528528
""" Unconditionally set affine into the header """
529529
hdr = self._header
530-
shape = self._dataobj.shape
530+
shape = np.array(self._dataobj.shape[:3]).reshape(3, 1)
531531
# for more information, go through save_mgh.m in FreeSurfer dist
532532
MdcD = self._affine[:3, :3]
533-
delta = np.sqrt(np.sum(MdcD * MdcD, axis=0))
533+
delta = voxel_sizes(self._affine)
534534
Mdc = MdcD / np.tile(delta, (3, 1))
535-
Pcrs_c = np.array([0, 0, 0, 1], dtype=np.float)
536-
Pcrs_c[:3] = np.array(shape[:3]) / 2.0
537-
c_ras = self._affine.dot(Pcrs_c.reshape(4, 1))
535+
c_ras = self._affine.dot(np.vstack((shape, [1])))
538536

539-
hdr['delta'][:] = delta
537+
hdr['delta'] = delta
540538
hdr['x_ras'] = Mdc[:, [0]]
541539
hdr['y_ras'] = Mdc[:, [1]]
542540
hdr['z_ras'] = Mdc[:, [2]]

0 commit comments

Comments
 (0)