diff --git a/monai/data/folder_layout.py b/monai/data/folder_layout.py index 7aa6effeb0..190a07334d 100644 --- a/monai/data/folder_layout.py +++ b/monai/data/folder_layout.py @@ -21,7 +21,11 @@ def default_name_formatter(metadict, saver): """Returns a kwargs dict for :py:meth:`FolderLayout.filename`, according to the input metadata and SaveImage transform.""" - subject = metadict[monai.utils.ImageMetaKey.FILENAME_OR_OBJ] if metadict else getattr(saver, "_data_index", 0) + subject = ( + metadict.get(monai.utils.ImageMetaKey.FILENAME_OR_OBJ, getattr(saver, "_data_index", 0)) + if metadict + else getattr(saver, "_data_index", 0) + ) patch_index = metadict.get(monai.utils.ImageMetaKey.PATCH_INDEX, None) if metadict else None return {"subject": f"{subject}", "idx": patch_index} diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py index e26a15e1dc..02ee7a8c50 100644 --- a/monai/transforms/spatial/array.py +++ b/monai/transforms/spatial/array.py @@ -346,7 +346,7 @@ def update_meta(self, img: torch.Tensor, dst_affine=None, img_dst=None): if dst_affine is not None: super().update_meta(img, dst_affine) if isinstance(img_dst, MetaTensor) and isinstance(img, MetaTensor): - original_fname = img.meta[Key.FILENAME_OR_OBJ] + original_fname = img.meta.get(Key.FILENAME_OR_OBJ, "resample_to_match_source") img.meta = deepcopy(img_dst.meta) img.meta[Key.FILENAME_OR_OBJ] = original_fname # keep the original name, the others are overwritten diff --git a/tests/test_resample_to_match.py b/tests/test_resample_to_match.py index 0661981031..0074ec2065 100644 --- a/tests/test_resample_to_match.py +++ b/tests/test_resample_to_match.py @@ -21,11 +21,13 @@ import nibabel as nib import numpy as np +import torch from parameterized import parameterized +from monai.data import MetaTensor from monai.data.image_reader import ITKReader, NibabelReader from monai.data.image_writer import ITKWriter -from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ResampleToMatch, SaveImaged +from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ResampleToMatch, SaveImage, SaveImaged from monai.utils import optional_import from tests.utils import assert_allclose, download_url_or_skip_test, testing_data_config @@ -90,6 +92,13 @@ def test_inverse(self): self.assertLess(((im_mod2.affine - data["im2"].affine) ** 2).sum() ** 0.5, 1e-2) self.assertEqual(im_mod2.applied_operations, []) + def test_no_name(self): + img_1 = MetaTensor(torch.zeros(1, 2, 2, 2)) + img_2 = MetaTensor(torch.zeros(1, 3, 3, 3)) + im_mod = ResampleToMatch()(img_1, img_2) + self.assertEqual(im_mod.meta["filename_or_obj"], "resample_to_match_source") + SaveImage(output_dir=self.tmpdir, output_postfix="", separate_folder=False, resample=False)(im_mod) + if __name__ == "__main__": unittest.main()