Skip to content

Commit 41732f4

Browse files
author
Ben Cipollini
committed
Improve efficiency: load img0 once, del reference, and don't check affine on first image.
1 parent 3331a51 commit 41732f4

File tree

2 files changed

+18
-15
lines changed

2 files changed

+18
-15
lines changed

nibabel/funcs.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -107,26 +107,27 @@ def concat_images(images, check_affines=True, axis=None):
107107
New image resulting from concatenating `images` across last
108108
dimension
109109
'''
110+
110111
n_imgs = len(images)
111-
img0 = images[0]
112-
if not hasattr(img0, 'get_data'):
113-
img0 = load(img0)
114-
affine = img0.affine
115-
header = img0.header
116-
i0shape = img0.shape
117-
del img0
118-
119-
if axis is None: # collect images in output array for efficiency
120-
out_shape = (n_imgs, ) + i0shape[:3]
121-
out_data = np.empty(out_shape)
122-
else: # collect images in list for use with np.concatenate
123-
out_data = [None] * n_imgs
112+
if n_imgs == 0:
113+
raise ValueError('Cannot concatenate an empty list of images.')
124114

125115
for i, img in enumerate(images):
126116
if not hasattr(img, 'get_data'):
127117
img = load(img)
128118

129-
if check_affines and not np.all(img.affine == affine):
119+
if i == 0: # first image, initialize data from loaded image
120+
affine = img.affine
121+
header = img.header
122+
klass = img.__class__
123+
124+
if axis is None: # collect images in output array for efficiency
125+
out_shape = (n_imgs, ) + img.shape[:3]
126+
out_data = np.empty(out_shape)
127+
else: # collect images in list for use with np.concatenate
128+
out_data = [None] * n_imgs
129+
130+
elif check_affines and not np.all(img.affine == affine):
130131
raise ValueError('Affines do not match')
131132

132133
# Special case for 4D image with size[3] == 1; reshape to work!
@@ -148,7 +149,6 @@ def concat_images(images, check_affines=True, axis=None):
148149
for di, data in enumerate(out_data)]
149150
out_data = np.concatenate(out_data, axis=axis)
150151

151-
klass = img0.__class__
152152
return klass(out_data, affine, header)
153153

154154

nibabel/tests/test_funcs.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ def _as_fname(img):
3030

3131

3232
def test_concat():
33+
# Smoke test: concat empty list.
34+
assert_raises(ValueError, concat_images, [])
3335

3436
# Build combinations of 3D, 4D w/size[3] == 1, and 4D w/size[3] == 3
3537
all_shapes_3D = ((1, 2, 5), (7, 3, 1), (13, 11, 11), (0, 1, 1))
@@ -128,6 +130,7 @@ def test_concat():
128130
assert_true(expect_error, ve.message)
129131

130132

133+
131134
def test_closest_canonical():
132135
arr = np.arange(24).reshape((2,3,4,1))
133136
# no funky stuff, returns same thing

0 commit comments

Comments
 (0)