Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support specified filenames in Saveimage #7318

Merged
merged 6 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions monai/transforms/io/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,15 +458,27 @@ def set_options(self, init_kwargs=None, data_kwargs=None, meta_kwargs=None, writ
self.write_kwargs.update(write_kwargs)
return self

def __call__(self, img: torch.Tensor | np.ndarray, meta_data: dict | None = None):
def __call__(
self, img: torch.Tensor | np.ndarray, meta_data: dict | None = None, filename: str | PathLike | None = None
):
"""
Args:
img: target data content that save into file. The image should be channel-first, shape: `[C,H,W,[D]]`.
meta_data: key-value pairs of metadata corresponding to the data.
filename: str or file-like object which to save img.
If specified, will ignore `self.output_name_formatter` and `self.folder_layout`.
"""
meta_data = img.meta if isinstance(img, MetaTensor) else meta_data
kw = self.fname_formatter(meta_data, self)
filename = self.folder_layout.filename(**kw)
if filename is not None:
filename = str(filename) + (
f".{self.output_ext}"
if self.output_ext and not self.output_ext.startswith(".")
else f"{self.output_ext}"
)
KumoLiu marked this conversation as resolved.
Show resolved Hide resolved
else:
kw = self.fname_formatter(meta_data, self)
filename = self.folder_layout.filename(**kw)

if meta_data:
meta_spatial_shape = ensure_tuple(meta_data.get("spatial_shape", ()))
if len(meta_spatial_shape) >= len(img.shape):
Expand Down
16 changes: 16 additions & 0 deletions tests/test_save_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
False,
]

TEST_CASE_5 = [torch.randint(0, 255, (3, 2, 4, 5), dtype=torch.uint8), ".dcm", False]


@unittest.skipUnless(has_itk, "itk not installed")
class TestSaveImage(unittest.TestCase):
Expand All @@ -58,6 +60,20 @@ def test_saved_content(self, test_data, meta_data, output_ext, resample):
filepath = "testfile0" if meta_data is not None else "0"
self.assertTrue(os.path.exists(os.path.join(tempdir, filepath + "_trans" + output_ext)))

@parameterized.expand([TEST_CASE_5])
def test_saved_content_with_filename(self, test_data, output_ext, resample):
with tempfile.TemporaryDirectory() as tempdir:
trans = SaveImage(
output_dir=tempdir,
output_ext=output_ext,
resample=resample,
separate_folder=False, # test saving into the same folder
)
filename = str(os.path.join(tempdir, "test"))
trans(test_data, filename=filename)

self.assertTrue(os.path.exists(filename + output_ext))


if __name__ == "__main__":
unittest.main()
Loading