Skip to content

Commit 1046c11

Browse files
committed
BF - allow for None affine in SPM images
None affine results in no write to the mat file object, and reading from an empty mat file object raised an error. Test and fix.
1 parent 3b9f8c4 commit 1046c11

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

nibabel/spm99analyze.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import warnings
1111
import numpy as np
1212

13+
from .py3k import BytesIO
14+
1315
from .spatialimages import HeaderDataError, HeaderTypeError
1416

1517
from .batteryrunners import Report
@@ -246,14 +248,18 @@ class Spm99AnalyzeImage(analyze.AnalyzeImage):
246248
@classmethod
247249
def from_file_map(klass, file_map):
248250
ret = super(Spm99AnalyzeImage, klass).from_file_map(file_map)
249-
import scipy.io as sio
250251
try:
251252
matf = file_map['mat'].get_prepare_fileobj()
252253
except IOError:
253254
return ret
254-
mats = sio.loadmat(matf)
255+
# Allow for possibility of empty file -> no update to affine
256+
contents = matf.read()
255257
if file_map['mat'].filename is not None: # was filename
256258
matf.close()
259+
if len(contents) == 0:
260+
return ret
261+
import scipy.io as sio
262+
mats = sio.loadmat(BytesIO(contents))
257263
if 'mat' in mats: # this overrides a 'M', and includes any flip
258264
mat = mats['mat']
259265
if mat.ndim > 2:

nibabel/tests/test_spm99analyze.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,20 @@ def test_mat_read(self):
157157
assert_array_equal(r_img.get_affine(),
158158
np.dot(np.diag([3,4,5,1]), np.dot(flipper, to_111)))
159159

160+
def test_none_affine(self):
161+
# Allow for possibility of no affine resulting in nothing written into
162+
# mat file. If the mat file is a filename, we just get no file, but if
163+
# it's a fileobj, we get an empty fileobj
164+
img_klass = self.image_class
165+
# With a None affine - no matfile written
166+
img = img_klass(np.zeros((2,3,4)), None)
167+
aff = img.get_header().get_best_affine()
168+
# Save / reload using bytes IO objects
169+
for key, value in img.file_map.items():
170+
value.fileobj = BytesIO()
171+
img.to_file_map()
172+
img_back = img.from_file_map(img.file_map)
173+
assert_array_equal(img_back.get_affine(), aff)
160174

161175

162176
def test_origin_affine():

0 commit comments

Comments
 (0)