Skip to content

Commit 026d79f

Browse files
authored
Keep SaveImage channel options local to each call (#9243)
Fixes #9242. The contributor explanation below was written by leecoring in Korean and translated with OpenAI Codex. The technical details and diagnostic report were prepared with Codex. Code and tests were developed with Codex assistance after a friend suggested the bug candidate. ### Description When saving multiple images with the same saver, the channel-axis setting from the first image can remain in the saver. A setting that should apply only to that image is then reused for later images, even when those images have a different channel layout, causing incorrect saving in SaveImage. Previously, the saver kept and applied that modified setting. With the fix, it retains the original configuration and uses a separate copy of the settings for the current image during the actual save. ### Technical details — assisted by Codex The verified trigger is a channel-less input followed by a channel-first input. Metadata-driven inference of no channel currently leaves `self.data_kwargs["channel_dim"] = None` behind. Copy the data options for each call, apply inference to that copy, and pass it to the writer. This also preserves caller settings made through `set_options`, including a non-default channel dimension. Add NiBabel file round-trip regression tests for NumPy arrays, torch tensors, MetaTensor inputs, multiple channels, a metadata-free later call, a non-default channel axis, and mixed `SaveImaged` keys in both orders and over repeated calls. NiBabel is already an optional dependency; the new tests explicitly skip when it is unavailable. ### Validation — Codex-run local diagnostics - The same 9 new regression cases fail against the original source and pass with the fix. - The focused command below reports 52 passed and 18 skipped. The skipped tests require ITK, which is not installed. ```sh python -m unittest tests.transforms.test_save_image tests.transforms.test_save_imaged tests.data.test_nifti_rw tests.data.test_itk_writer -v ``` - Whole-checkout `./runtests.sh --black`, `--isort`, `--ruff`, `--copyright` and `--pyrefly` each exit successfully. Pyrefly reports 0 errors, 781 suppressed diagnostics and 72 warnings under the repository configuration. - `git diff --check` and all applicable pre-commit hooks on the three changed files pass. - Local environment: macOS 15.5 arm64, Python 3.14.7, PyTorch 2.15.0, NumPy 2.5.4 and NiBabel 5.4.2. - Full integration/distributed tests, other OS/Python configurations and the documentation build were not run locally. Public API signatures and documentation files are unchanged. ### Types of changes - [x] Non-breaking change (bug fix). - [x] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated and `make html` tested. --------- Signed-off-by: leecoring <109904107+leecoring@users.noreply.github.com>
1 parent 8c31f2e commit 026d79f

3 files changed

Lines changed: 109 additions & 4 deletions

File tree

‎monai/transforms/io/array.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -531,21 +531,22 @@ def __call__(
531531
kw = self.fname_formatter(meta_data, self)
532532
filename = self.folder_layout.filename(**kw)
533533

534+
data_kwargs = self.data_kwargs.copy()
534535
if meta_data:
535536
meta_spatial_shape = ensure_tuple(meta_data.get("spatial_shape", ()))
536537
if len(meta_spatial_shape) >= len(img.shape):
537-
self.data_kwargs["channel_dim"] = None
538-
elif is_no_channel(self.data_kwargs.get("channel_dim")):
538+
data_kwargs["channel_dim"] = None
539+
elif is_no_channel(data_kwargs.get("channel_dim")):
539540
warnings.warn(
540541
f"data shape {img.shape} (with spatial shape {meta_spatial_shape}) "
541-
f"but SaveImage `channel_dim` is set to {self.data_kwargs.get('channel_dim')} no channel."
542+
f"but SaveImage `channel_dim` is set to {data_kwargs.get('channel_dim')} no channel."
542543
)
543544

544545
err = []
545546
for writer_cls in self.writers:
546547
try:
547548
writer_obj = writer_cls(**self.init_kwargs)
548-
writer_obj.set_data_array(data_array=img, **self.data_kwargs)
549+
writer_obj.set_data_array(data_array=img, **data_kwargs)
549550
writer_obj.set_metadata(meta_dict=meta_data, **self.meta_kwargs)
550551
writer_obj.write(filename, **self.write_kwargs)
551552
self.writer_obj = writer_obj

‎tests/transforms/test_save_image.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import tempfile
1616
import unittest
1717

18+
import numpy as np
1819
import torch
1920
from parameterized import parameterized
2021

@@ -23,6 +24,7 @@
2324
from monai.utils import optional_import
2425

2526
_, has_itk = optional_import("itk", allow_namespace_pkg=True)
27+
nib, has_nibabel = optional_import("nibabel")
2628

2729
TEST_CASE_1 = [torch.randint(0, 255, (1, 2, 3, 4)), {"filename_or_obj": "testfile0.nii.gz"}, ".nii.gz", False]
2830

@@ -76,5 +78,57 @@ def test_saved_content_with_filename(self, test_data, output_ext, resample):
7678
self.assertTrue(os.path.exists(filename + output_ext))
7779

7880

81+
@unittest.skipUnless(has_nibabel, "nibabel not installed")
82+
class TestSaveImageChannelDim(unittest.TestCase):
83+
"""Check that reusing SaveImage preserves saved values and configured channel options."""
84+
85+
@parameterized.expand(
86+
[
87+
("numpy_single", "numpy", 1, 0, True),
88+
("numpy_no_metadata", "numpy", 1, 0, False),
89+
("tensor", "tensor", 1, 0, True),
90+
("metatensor", "metatensor", 1, 0, True),
91+
("multiple_channels", "numpy", 2, 0, True),
92+
("channel_last", "numpy", 2, -1, True),
93+
]
94+
)
95+
def test_reuse_after_channel_less(self, _, input_type, channels, channel_dim, with_metadata):
96+
"""Save channel-less and channel-bearing inputs without leaking inferred options.
97+
98+
Both saved arrays must retain all input values. The second saved array omits
99+
a singleton channel axis or places multiple channels last, while the saver's
100+
configured data options remain unchanged.
101+
102+
Args:
103+
_: Case name used to identify the parameterized test.
104+
input_type: Input representation: numpy, tensor, or metatensor.
105+
channels: Number of channels in the second input.
106+
channel_dim: Channel axis configured for the second input.
107+
with_metadata: Whether to pass explicit metadata on the second save.
108+
"""
109+
spatial_shape = (2, 3, 4)
110+
first = np.arange(24, dtype=np.float32).reshape(spatial_shape)
111+
second = np.arange(channels * 24, dtype=np.float32).reshape((channels, *spatial_shape)) + 100
112+
expected = second[0] if channels == 1 else np.moveaxis(second, 0, -1)
113+
second = np.moveaxis(second, 0, channel_dim)
114+
metadata = {"spatial_shape": spatial_shape}
115+
if input_type == "tensor":
116+
first, second = torch.as_tensor(first), torch.as_tensor(second)
117+
elif input_type == "metatensor":
118+
first, second = MetaTensor(first, meta=metadata), MetaTensor(second, meta=metadata)
119+
120+
with tempfile.TemporaryDirectory() as tempdir:
121+
saver = SaveImage(writer="NibabelWriter", resample=False, print_log=False)
122+
saver.set_options(data_kwargs={"channel_dim": channel_dim})
123+
original_options = saver.data_kwargs.copy()
124+
saver(first, meta_data=metadata, filename=os.path.join(tempdir, "first"))
125+
np.testing.assert_array_equal(
126+
nib.load(os.path.join(tempdir, "first.nii.gz")).get_fdata(), np.arange(24).reshape(spatial_shape)
127+
)
128+
saver(second, meta_data=metadata if with_metadata else None, filename=os.path.join(tempdir, "second"))
129+
np.testing.assert_array_equal(nib.load(os.path.join(tempdir, "second.nii.gz")).get_fdata(), expected)
130+
self.assertEqual(saver.data_kwargs, original_options)
131+
132+
79133
if __name__ == "__main__":
80134
unittest.main()

‎tests/transforms/test_save_imaged.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import unittest
1717
from pathlib import Path
1818

19+
import numpy as np
1920
import torch
2021
from parameterized import parameterized
2122

@@ -26,6 +27,7 @@
2627
from monai.utils import optional_import
2728

2829
_, has_itk = optional_import("itk", allow_namespace_pkg=True)
30+
nib, has_nibabel = optional_import("nibabel")
2931

3032
TEST_CASE_1 = [
3133
{"img": MetaTensor(torch.randint(0, 255, (1, 2, 3, 4)), meta={"filename_or_obj": "testfile0.nii.gz"})},
@@ -126,5 +128,53 @@ def test_includes_metadata(self, test_data, output_ext, resample):
126128
self.assertTrue(os.path.exists(test_data["img"].meta["saved_to"]))
127129

128130

131+
@unittest.skipUnless(has_nibabel, "nibabel not installed")
132+
class TestSaveImagedChannelDim(unittest.TestCase):
133+
"""Check that SaveImaged keeps channel inference local to each saved image or label."""
134+
135+
@parameterized.expand(
136+
[
137+
("image_first", ("image", "label"), False),
138+
("label_first", ("label", "image"), False),
139+
("metatensor", ("image", "label"), True),
140+
]
141+
)
142+
def test_mixed_channel_dimensions(self, _, keys, use_metatensor):
143+
"""Preserve image and label values across key orders and repeated saves.
144+
145+
Each of two calls must save the channel-less image unchanged and the
146+
single-channel label with its singleton channel axis removed. Both saved
147+
arrays must have shape (2, 3, 4) and retain all their respective input values.
148+
149+
Args:
150+
_: Case name used to identify the parameterized test.
151+
keys: Order in which the image and label are saved.
152+
use_metatensor: Whether to use MetaTensor inputs with embedded metadata
153+
instead of NumPy arrays with separate metadata dictionaries.
154+
"""
155+
image = np.arange(24, dtype=np.float32).reshape(2, 3, 4)
156+
label = (image + 100)[None]
157+
with tempfile.TemporaryDirectory() as tempdir:
158+
saver = SaveImaged(
159+
keys=keys,
160+
output_dir=tempdir,
161+
writer="NibabelWriter",
162+
resample=False,
163+
separate_folder=False,
164+
print_log=False,
165+
)
166+
data = {}
167+
for key, array in (("image", image), ("label", label)):
168+
metadata = {"filename_or_obj": key, "spatial_shape": (2, 3, 4)}
169+
data[key] = MetaTensor(array, meta=metadata) if use_metatensor else array
170+
if not use_metatensor:
171+
data[f"{key}_meta_dict"] = metadata
172+
for _ in range(2):
173+
saver(data)
174+
for key, expected in (("image", image), ("label", label[0])):
175+
saved = nib.load(os.path.join(tempdir, f"{key}_trans.nii.gz")).get_fdata()
176+
np.testing.assert_array_equal(saved, expected)
177+
178+
129179
if __name__ == "__main__":
130180
unittest.main()

0 commit comments

Comments
 (0)