Skip to content

Commit 1686030

Browse files
authored
Merge pull request #706 from mgxd/enh/merge-tolerance
ENH: Add `affine_tolerance` flag to `MergeSeries`
2 parents 6373632 + de1593c commit 1686030

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

niworkflows/interfaces/nibabel.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ class _MergeSeriesInputSpec(BaseInterfaceInputSpec):
160160
allow_4D = traits.Bool(
161161
True, usedefault=True, desc="whether 4D images are allowed to be concatenated"
162162
)
163+
affine_tolerance = traits.Float(desc="Absolute tolerance allowed between image affines")
163164

164165

165166
class _MergeSeriesOutputSpec(TraitedSpec):
@@ -174,8 +175,17 @@ class MergeSeries(SimpleInterface):
174175

175176
def _run_interface(self, runtime):
176177
nii_list = []
178+
aff0 = None
177179
for f in self.inputs.in_files:
178180
filenii = nb.squeeze_image(nb.load(f))
181+
if self.inputs.affine_tolerance:
182+
if aff0 is None:
183+
aff0 = filenii.affine
184+
elif not np.allclose(aff0, filenii.affine, atol=self.inputs.affine_tolerance):
185+
raise ValueError(
186+
"Difference in affines greater than allowed tolerance "
187+
f"{self.inputs.affine_tolerance}"
188+
)
179189
ndim = filenii.dataobj.ndim
180190
if ndim == 3:
181191
nii_list.append(filenii)
@@ -188,7 +198,10 @@ def _run_interface(self, runtime):
188198
"Input image has an incorrect number of dimensions" f" ({ndim})."
189199
)
190200

191-
img_4d = nb.concat_images(nii_list)
201+
img_4d = nb.concat_images(
202+
nii_list,
203+
check_affines=not bool(self.inputs.affine_tolerance)
204+
)
192205
out_file = fname_presuffix(
193206
self.inputs.in_files[0], suffix="_merged", newpath=runtime.cwd
194207
)

niworkflows/interfaces/tests/test_nibabel.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,21 @@ def test_MergeSeries(tmp_path):
155155

156156
with pytest.raises(ValueError):
157157
MergeSeries(in_files=[str(in_file)] + [str(in_4D)], allow_4D=False).run()
158+
159+
160+
def test_MergeSeries_affines(tmp_path):
161+
os.chdir(str(tmp_path))
162+
163+
files = ['img0.nii.gz', 'img1.nii.gz']
164+
data = np.ones((10, 10, 10), dtype=int)
165+
aff = np.eye(4)
166+
nb.Nifti1Image(data, aff, None).to_filename(files[0])
167+
# slightly alter affine
168+
aff[0][0] = 1.00005
169+
nb.Nifti1Image(data, aff, None).to_filename(files[1])
170+
171+
# affine mismatch will cause this to fail
172+
with pytest.raises(ValueError):
173+
MergeSeries(in_files=files).run()
174+
# but works if we set a tolerance
175+
MergeSeries(in_files=files, affine_tolerance=1e-04).run()

0 commit comments

Comments
 (0)