Skip to content

Commit 2626884

Browse files
author
Ben Cipollini
committed
Try again, this time with lists and more tests...
1 parent c6c6a1d commit 2626884

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

nibabel/funcs.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,19 +117,18 @@ def concat_images(images, check_affines=True, axis=None):
117117
affine = img0.affine
118118
header = img0.header
119119
out_shape = (n_imgs, ) + i0shape
120-
out_data = np.empty(out_shape)
120+
out_data = []
121121
for i, img in enumerate(images):
122122
if is_filename:
123123
img = load(img)
124124
if check_affines:
125125
if not np.all(img.affine == affine):
126126
raise ValueError('Affines do not match')
127-
out_data[i] = img.get_data().copy()
127+
out_data.append(img.get_data())
128128
if axis is not None:
129129
out_data = np.concatenate(out_data, axis=axis)
130-
elif np.all([d.shape[-1] == 1 for d in out_data]):
131-
out_data = np.concatenate(out_data, axis=d.ndim-1)
132130
else:
131+
out_data = np.asarray(out_data)
133132
out_data = np.rollaxis(out_data, 0, len(i0shape)+1)
134133
klass = img0.__class__
135134
return klass(out_data, affine, header)

nibabel/tests/test_funcs.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,16 +66,35 @@ def test_concat():
6666
img0_mem = Nifti1Image(data0, affine)
6767
img1_mem = Nifti1Image(data0 - 10, affine)
6868

69-
concat_img1 = concat_images([img0_mem, img1_mem])
69+
# 4d, same shape, append on axis 3
70+
concat_img1 = concat_images([img0_mem, img1_mem], axis=3)
7071
expected_shape1 = shape_4D.copy()
7172
expected_shape1[-1] *= 2
7273
assert_array_equal(concat_img1.shape, expected_shape1)
7374

75+
# 4d, same shape, append on axis 0
7476
concat_img2 = concat_images([img0_mem, img1_mem], axis=0)
7577
expected_shape2 = shape_4D.copy()
7678
expected_shape2[0] *= 2
7779
assert_array_equal(concat_img2.shape, expected_shape2)
7880

81+
# 4d, same shape, append on axis -1
82+
concat_img3 = concat_images([img0_mem, img1_mem], axis=-1)
83+
expected_shape3 = shape_4D.copy()
84+
expected_shape3[-1] *= 2
85+
assert_array_equal(concat_img3.shape, expected_shape3)
86+
87+
# 4d, different shape, append on axis that's different
88+
print('%s %s' % (str(concat_img3.shape), str(img1_mem.shape)))
89+
concat_img4 = concat_images([concat_img3, img1_mem], axis=-1)
90+
expected_shape4 = shape_4D.copy()
91+
expected_shape4[-1] *= 3
92+
assert_array_equal(concat_img4.shape, expected_shape4)
93+
94+
# 4d, different shape, append on axis that's not different...
95+
# Doesn't work!
96+
assert_raises(ValueError, concat_images, [concat_img3, img1_mem], axis=1)
97+
7998

8099
def test_closest_canonical():
81100
arr = np.arange(24).reshape((2,3,4,1))

0 commit comments

Comments
 (0)