We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Missing `return` in `__call__` of transforms: `SaveImage`, `NiftiSaver` and `PNGSaver`
**To Reproduce**
Steps to reproduce the behavior:

```
from monai.transforms import SaveImage, Compose
saver = Compose([SaveImage(output_dir="./output", output_ext=".png", output_postfix="seg")])
img = torch.randn([3, 32, 32])
output = saver(img)
print(output)
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `monai/transforms/io/array.py`
Content:
```
1 # Copyright 2020 - 2021 MONAI Consortium
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
5 #     http://www.apache.org/licenses/LICENSE-2.0
6 # Unless required by applicable law or agreed to in writing, software
7 # distributed under the License is distributed on an "AS IS" BASIS,
8 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 # See the License for the specific language governing permissions and
10 # limitations under the License.
11 """
12 A collection of "vanilla" transforms for IO functions
13 https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design
14 """
15 
16 import sys
17 from typing import Dict, List, Optional, Sequence, Union
18 
19 import numpy as np
20 import torch
21 
22 from monai.config import DtypeLike
23 from monai.data.image_reader import ImageReader, ITKReader, NibabelReader, NumpyReader, PILReader
24 from monai.data.nifti_saver import NiftiSaver
25 from monai.data.png_saver import PNGSaver
26 from monai.transforms.transform import Transform
27 from monai.utils import GridSampleMode, GridSamplePadMode
28 from monai.utils import ImageMetaKey as Key
29 from monai.utils import InterpolateMode, ensure_tuple, optional_import
30 
31 nib, _ = optional_import("nibabel")
32 Image, _ = optional_import("PIL.Image")
33 
34 __all__ = ["LoadImage", "SaveImage"]
35 
36 
37 def switch_endianness(data, new="<"):
38     """
39     Convert the input `data` endianness to `new`.
40 
41     Args:
42         data: input to be converted.
43         new: the target endianness, currently support "<" or ">".
44     """
45     if isinstance(data, np.ndarray):
46         # default to system endian
47         sys_native = ((sys.byteorder == "little") and "<") or ">"
48         current_ = sys_native if data.dtype.byteorder not in ("<", ">") else data.dtype.byteorder
49         if new not in ("<", ">"):
50             raise NotImplementedError(f"Not implemented option new={new}.")
51         if current_ != new:
52             data = data.byteswap().newbyteorder(new)
53     elif isinstance(data, tuple):
54         data = tuple(switch_endianness(x, new) for x in data)
55     elif isinstance(data, list):
56         data = [switch_endianness(x, new) for x in data]
57     elif isinstance(data, dict):
58         data = {k: switch_endianness(v, new) for k, v in data.items()}
59     elif isinstance(data, (bool, str, float, int, type(None))):
60         pass
61     else:
62         raise AssertionError(f"Unknown type: {type(data).__name__}")
63     return data
64 
65 
66 class LoadImage(Transform):
67     """
68     Load image file or files from provided path based on reader.
69     Automatically choose readers based on the supported suffixes and in below order:
70     - User specified reader at runtime when call this loader.
71     - Registered readers from the latest to the first in list.
72     - Default readers: (nii, nii.gz -> NibabelReader), (png, jpg, bmp -> PILReader),
73     (npz, npy -> NumpyReader), (others -> ITKReader).
74 
75     """
76 
77     def __init__(
78         self,
79         reader: Optional[Union[ImageReader, str]] = None,
80         image_only: bool = False,
81         dtype: DtypeLike = np.float32,
82         *args,
83         **kwargs,
84     ) -> None:
85         """
86         Args:
87             reader: register reader to load image file and meta data, if None, still can register readers
88                 at runtime or use the default readers. If a string of reader name provided, will construct
89                 a reader object with the `*args` and `**kwargs` parameters, supported reader name: "NibabelReader",
90                 "PILReader", "ITKReader", "NumpyReader".
91             image_only: if True return only the image volume, otherwise return image data array and header dict.
92             dtype: if not None convert the loaded image to this data type.
93             args: additional parameters for reader if providing a reader name.
94             kwargs: additional parameters for reader if providing a reader name.
95 
96         Note:
97             The transform returns image data array if `image_only` is True,
98             or a tuple of two elements containing the data array, and the meta data in a dict format otherwise.
99 
100         """
101         # set predefined readers as default
102         self.readers: List[ImageReader] = [ITKReader(), NumpyReader(), PILReader(), NibabelReader()]
103         if reader is not None:
104             if isinstance(reader, str):
105                 supported_readers = {
106                     "nibabelreader": NibabelReader,
107                     "pilreader": PILReader,
108                     "itkreader": ITKReader,
109                     "numpyreader": NumpyReader,
110                 }
111                 reader = reader.lower()
112                 if reader not in supported_readers:
113                     raise ValueError(f"unsupported reader type: {reader}, available options: {supported_readers}.")
114                 self.register(supported_readers[reader](*args, **kwargs))
115             else:
116                 self.register(reader)
117 
118         self.image_only = image_only
119         self.dtype = dtype
120 
121     def register(self, reader: ImageReader) -> List[ImageReader]:
122         """
123         Register image reader to load image file and meta data, latest registered reader has higher priority.
124         Return all the registered image readers.
125 
126         Args:
127             reader: registered reader to load image file and meta data based on suffix,
128                 if all registered readers can't match suffix at runtime, use the default readers.
129 
130         """
131         if not isinstance(reader, ImageReader):
132             raise ValueError(f"reader must be ImageReader object, but got {type(reader)}.")
133         self.readers.append(reader)
134         return self.readers
135 
136     def __call__(
137         self,
138         filename: Union[Sequence[str], str],
139         reader: Optional[ImageReader] = None,
140     ):
141         """
142         Args:
143             filename: path file or file-like object or a list of files.
144                 will save the filename to meta_data with key `filename_or_obj`.
145                 if provided a list of files, use the filename of first file.
146             reader: runtime reader to load image file and meta data.
147 
148         """
149         if reader is None or not reader.verify_suffix(filename):
150             for r in reversed(self.readers):
151                 if r.verify_suffix(filename):
152                     reader = r
153                     break
154 
155         if reader is None:
156             raise RuntimeError(
157                 f"can not find suitable reader for this file: {filename}. \
158                 Please install dependency libraries: (nii, nii.gz) -> Nibabel, (png, jpg, bmp) -> PIL, \
159                 (npz, npy) -> Numpy, others -> ITK. Refer to the installation instruction: \
160                 https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies."
161             )
162 
163         img = reader.read(filename)
164         img_array, meta_data = reader.get_data(img)
165         img_array = img_array.astype(self.dtype)
166 
167         if self.image_only:
168             return img_array
169         meta_data[Key.FILENAME_OR_OBJ] = ensure_tuple(filename)[0]
170         # make sure all elements in metadata are little endian
171         meta_data = switch_endianness(meta_data, "<")
172 
173         return img_array, meta_data
174 
175 
176 class SaveImage(Transform):
177     """
178     Save transformed data into files, support NIfTI and PNG formats.
179     It can work for both numpy array and PyTorch Tensor in both preprocessing transform
180     chain and postprocessing transform chain.
181     The name of saved file will be `{input_image_name}_{output_postfix}{output_ext}`,
182     where the input image name is extracted from the provided meta data dictionary.
183     If no meta data provided, use index from 0 as the filename prefix.
184     It can also save a list of PyTorch Tensor or numpy array without `batch dim`.
185 
186     Note: image should be channel-first shape: [C,H,W,[D]].
187 
188     Args:
189         output_dir: output image directory.
190         output_postfix: a string appended to all output file names, default to `trans`.
191         output_ext: output file extension name, available extensions: `.nii.gz`, `.nii`, `.png`.
192         resample: whether to resample before saving the data array.
193             if saving PNG format image, based on the `spatial_shape` from metadata.
194             if saving NIfTI format image, based on the `original_affine` from metadata.
195         mode: This option is used when ``resample = True``. Defaults to ``"nearest"``.
196 
197             - NIfTI files {``"bilinear"``, ``"nearest"``}
198                 Interpolation mode to calculate output values.
199                 See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
200             - PNG files {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}
201                 The interpolation mode.
202                 See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate
203 
204         padding_mode: This option is used when ``resample = True``. Defaults to ``"border"``.
205 
206             - NIfTI files {``"zeros"``, ``"border"``, ``"reflection"``}
207                 Padding mode for outside grid values.
208                 See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
209             - PNG files
210                 This option is ignored.
211 
212         scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling
213             [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling.
214             it's used for PNG format only.
215         dtype: data type during resampling computation. Defaults to ``np.float64`` for best precision.
216             if None, use the data type of input data. To be compatible with other modules,
217             the output data type is always ``np.float32``.
218             it's used for NIfTI format only.
219         output_dtype: data type for saving data. Defaults to ``np.float32``.
220             it's used for NIfTI format only.
221         squeeze_end_dims: if True, any trailing singleton dimensions will be removed (after the channel
222             has been moved to the end). So if input is (C,H,W,D), this will be altered to (H,W,D,C), and
223             then if C==1, it will be saved as (H,W,D). If D also ==1, it will be saved as (H,W). If false,
224             image will always be saved as (H,W,D,C).
225             it's used for NIfTI format only.
226         data_root_dir: if not empty, it specifies the beginning parts of the input file's
227             absolute path. it's used to compute `input_file_rel_path`, the relative path to the file from
228             `data_root_dir` to preserve folder structure when saving in case there are files in different
229             folders with the same file names. for example:
230             input_file_name: /foo/bar/test1/image.nii,
231             output_postfix: seg
232             output_ext: nii.gz
233             output_dir: /output,
234             data_root_dir: /foo/bar,
235             output will be: /output/test1/image/image_seg.nii.gz
236         print_log: whether to print log about the saved file path, etc. default to `True`.
237 
238     """
239 
240     def __init__(
241         self,
242         output_dir: str = "./",
243         output_postfix: str = "trans",
244         output_ext: str = ".nii.gz",
245         resample: bool = True,
246         mode: Union[GridSampleMode, InterpolateMode, str] = "nearest",
247         padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER,
248         scale: Optional[int] = None,
249         dtype: DtypeLike = np.float64,
250         output_dtype: DtypeLike = np.float32,
251         squeeze_end_dims: bool = True,
252         data_root_dir: str = "",
253         print_log: bool = True,
254     ) -> None:
255         self.saver: Union[NiftiSaver, PNGSaver]
256         if output_ext in (".nii.gz", ".nii"):
257             self.saver = NiftiSaver(
258                 output_dir=output_dir,
259                 output_postfix=output_postfix,
260                 output_ext=output_ext,
261                 resample=resample,
262                 mode=GridSampleMode(mode),
263                 padding_mode=padding_mode,
264                 dtype=dtype,
265                 output_dtype=output_dtype,
266                 squeeze_end_dims=squeeze_end_dims,
267                 data_root_dir=data_root_dir,
268                 print_log=print_log,
269             )
270         elif output_ext == ".png":
271             self.saver = PNGSaver(
272                 output_dir=output_dir,
273                 output_postfix=output_postfix,
274                 output_ext=output_ext,
275                 resample=resample,
276                 mode=InterpolateMode(mode),
277                 scale=scale,
278                 data_root_dir=data_root_dir,
279                 print_log=print_log,
280             )
281         else:
282             raise ValueError(f"unsupported output extension: {output_ext}.")
283 
284     def __call__(self, img: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None):
285         """
286         Args:
287             img: target data content that save into file.
288             meta_data: key-value pairs of meta_data corresponding to the data.
289 
290         """
291         self.saver.save(img, meta_data)
292
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/monai/transforms/io/array.py b/monai/transforms/io/array.py
--- a/monai/transforms/io/array.py
+++ b/monai/transforms/io/array.py
@@ -289,3 +289,5 @@
 
         """
         self.saver.save(img, meta_data)
+
+        return img

{"golden_diff": "diff --git a/monai/transforms/io/array.py b/monai/transforms/io/array.py\n--- a/monai/transforms/io/array.py\n+++ b/monai/transforms/io/array.py\n@@ -289,3 +289,5 @@\n \n         \"\"\"\n         self.saver.save(img, meta_data)\n+\n+        return img\n", "issue": "Missing `return` in `__call__` of transforms: `SaveImage`, `NiftiSaver` and `PNGSaver`\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n\r\n```\r\nfrom monai.transforms import SaveImage, Compose\r\nsaver = Compose([SaveImage(output_dir=\"./output\", output_ext=\".png\", output_postfix=\"seg\")])\r\nimg = torch.randn([3, 32, 32])\r\noutput = saver(img)\r\nprint(output)\r\n```\n", "before_files": [{"content": "# Copyright 2020 - 2021 MONAI Consortium\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nA collection of \"vanilla\" transforms for IO functions\nhttps://github.com/Project-MONAI/MONAI/wiki/MONAI_Design\n\"\"\"\n\nimport sys\nfrom typing import Dict, List, Optional, Sequence, Union\n\nimport numpy as np\nimport torch\n\nfrom monai.config import DtypeLike\nfrom monai.data.image_reader import ImageReader, ITKReader, NibabelReader, NumpyReader, PILReader\nfrom monai.data.nifti_saver import NiftiSaver\nfrom monai.data.png_saver import PNGSaver\nfrom monai.transforms.transform import Transform\nfrom monai.utils import GridSampleMode, GridSamplePadMode\nfrom monai.utils import ImageMetaKey as Key\nfrom monai.utils import InterpolateMode, ensure_tuple, optional_import\n\nnib, _ = optional_import(\"nibabel\")\nImage, _ = optional_import(\"PIL.Image\")\n\n__all__ = [\"LoadImage\", \"SaveImage\"]\n\n\ndef switch_endianness(data, new=\"<\"):\n    \"\"\"\n    Convert the input `data` endianness to `new`.\n\n    Args:\n        data: input to be converted.\n        new: the target endianness, currently support \"<\" or \">\".\n    \"\"\"\n    if isinstance(data, np.ndarray):\n        # default to system endian\n        sys_native = ((sys.byteorder == \"little\") and \"<\") or \">\"\n        current_ = sys_native if data.dtype.byteorder not in (\"<\", \">\") else data.dtype.byteorder\n        if new not in (\"<\", \">\"):\n            raise NotImplementedError(f\"Not implemented option new={new}.\")\n        if current_ != new:\n            data = data.byteswap().newbyteorder(new)\n    elif isinstance(data, tuple):\n        data = tuple(switch_endianness(x, new) for x in data)\n    elif isinstance(data, list):\n        data = [switch_endianness(x, new) for x in data]\n    elif isinstance(data, dict):\n        data = {k: switch_endianness(v, new) for k, v in data.items()}\n    elif isinstance(data, (bool, str, float, int, type(None))):\n        pass\n    else:\n        raise AssertionError(f\"Unknown type: {type(data).__name__}\")\n    return data\n\n\nclass LoadImage(Transform):\n    \"\"\"\n    Load image file or files from provided path based on reader.\n    Automatically choose readers based on the supported suffixes and in below order:\n    - User specified reader at runtime when call this loader.\n    - Registered readers from the latest to the first in list.\n    - Default readers: (nii, nii.gz -> NibabelReader), (png, jpg, bmp -> PILReader),\n    (npz, npy -> NumpyReader), (others -> ITKReader).\n\n    \"\"\"\n\n    def __init__(\n        self,\n        reader: Optional[Union[ImageReader, str]] = None,\n        image_only: bool = False,\n        dtype: DtypeLike = np.float32,\n        *args,\n        **kwargs,\n    ) -> None:\n        \"\"\"\n        Args:\n            reader: register reader to load image file and meta data, if None, still can register readers\n                at runtime or use the default readers. If a string of reader name provided, will construct\n                a reader object with the `*args` and `**kwargs` parameters, supported reader name: \"NibabelReader\",\n                \"PILReader\", \"ITKReader\", \"NumpyReader\".\n            image_only: if True return only the image volume, otherwise return image data array and header dict.\n            dtype: if not None convert the loaded image to this data type.\n            args: additional parameters for reader if providing a reader name.\n            kwargs: additional parameters for reader if providing a reader name.\n\n        Note:\n            The transform returns image data array if `image_only` is True,\n            or a tuple of two elements containing the data array, and the meta data in a dict format otherwise.\n\n        \"\"\"\n        # set predefined readers as default\n        self.readers: List[ImageReader] = [ITKReader(), NumpyReader(), PILReader(), NibabelReader()]\n        if reader is not None:\n            if isinstance(reader, str):\n                supported_readers = {\n                    \"nibabelreader\": NibabelReader,\n                    \"pilreader\": PILReader,\n                    \"itkreader\": ITKReader,\n                    \"numpyreader\": NumpyReader,\n                }\n                reader = reader.lower()\n                if reader not in supported_readers:\n                    raise ValueError(f\"unsupported reader type: {reader}, available options: {supported_readers}.\")\n                self.register(supported_readers[reader](*args, **kwargs))\n            else:\n                self.register(reader)\n\n        self.image_only = image_only\n        self.dtype = dtype\n\n    def register(self, reader: ImageReader) -> List[ImageReader]:\n        \"\"\"\n        Register image reader to load image file and meta data, latest registered reader has higher priority.\n        Return all the registered image readers.\n\n        Args:\n            reader: registered reader to load image file and meta data based on suffix,\n                if all registered readers can't match suffix at runtime, use the default readers.\n\n        \"\"\"\n        if not isinstance(reader, ImageReader):\n            raise ValueError(f\"reader must be ImageReader object, but got {type(reader)}.\")\n        self.readers.append(reader)\n        return self.readers\n\n    def __call__(\n        self,\n        filename: Union[Sequence[str], str],\n        reader: Optional[ImageReader] = None,\n    ):\n        \"\"\"\n        Args:\n            filename: path file or file-like object or a list of files.\n                will save the filename to meta_data with key `filename_or_obj`.\n                if provided a list of files, use the filename of first file.\n            reader: runtime reader to load image file and meta data.\n\n        \"\"\"\n        if reader is None or not reader.verify_suffix(filename):\n            for r in reversed(self.readers):\n                if r.verify_suffix(filename):\n                    reader = r\n                    break\n\n        if reader is None:\n            raise RuntimeError(\n                f\"can not find suitable reader for this file: {filename}. \\\n                Please install dependency libraries: (nii, nii.gz) -> Nibabel, (png, jpg, bmp) -> PIL, \\\n                (npz, npy) -> Numpy, others -> ITK. Refer to the installation instruction: \\\n                https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies.\"\n            )\n\n        img = reader.read(filename)\n        img_array, meta_data = reader.get_data(img)\n        img_array = img_array.astype(self.dtype)\n\n        if self.image_only:\n            return img_array\n        meta_data[Key.FILENAME_OR_OBJ] = ensure_tuple(filename)[0]\n        # make sure all elements in metadata are little endian\n        meta_data = switch_endianness(meta_data, \"<\")\n\n        return img_array, meta_data\n\n\nclass SaveImage(Transform):\n    \"\"\"\n    Save transformed data into files, support NIfTI and PNG formats.\n    It can work for both numpy array and PyTorch Tensor in both preprocessing transform\n    chain and postprocessing transform chain.\n    The name of saved file will be `{input_image_name}_{output_postfix}{output_ext}`,\n    where the input image name is extracted from the provided meta data dictionary.\n    If no meta data provided, use index from 0 as the filename prefix.\n    It can also save a list of PyTorch Tensor or numpy array without `batch dim`.\n\n    Note: image should be channel-first shape: [C,H,W,[D]].\n\n    Args:\n        output_dir: output image directory.\n        output_postfix: a string appended to all output file names, default to `trans`.\n        output_ext: output file extension name, available extensions: `.nii.gz`, `.nii`, `.png`.\n        resample: whether to resample before saving the data array.\n            if saving PNG format image, based on the `spatial_shape` from metadata.\n            if saving NIfTI format image, based on the `original_affine` from metadata.\n        mode: This option is used when ``resample = True``. Defaults to ``\"nearest\"``.\n\n            - NIfTI files {``\"bilinear\"``, ``\"nearest\"``}\n                Interpolation mode to calculate output values.\n                See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample\n            - PNG files {``\"nearest\"``, ``\"linear\"``, ``\"bilinear\"``, ``\"bicubic\"``, ``\"trilinear\"``, ``\"area\"``}\n                The interpolation mode.\n                See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate\n\n        padding_mode: This option is used when ``resample = True``. Defaults to ``\"border\"``.\n\n            - NIfTI files {``\"zeros\"``, ``\"border\"``, ``\"reflection\"``}\n                Padding mode for outside grid values.\n                See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample\n            - PNG files\n                This option is ignored.\n\n        scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling\n            [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling.\n            it's used for PNG format only.\n        dtype: data type during resampling computation. Defaults to ``np.float64`` for best precision.\n            if None, use the data type of input data. To be compatible with other modules,\n            the output data type is always ``np.float32``.\n            it's used for NIfTI format only.\n        output_dtype: data type for saving data. Defaults to ``np.float32``.\n            it's used for NIfTI format only.\n        squeeze_end_dims: if True, any trailing singleton dimensions will be removed (after the channel\n            has been moved to the end). So if input is (C,H,W,D), this will be altered to (H,W,D,C), and\n            then if C==1, it will be saved as (H,W,D). If D also ==1, it will be saved as (H,W). If false,\n            image will always be saved as (H,W,D,C).\n            it's used for NIfTI format only.\n        data_root_dir: if not empty, it specifies the beginning parts of the input file's\n            absolute path. it's used to compute `input_file_rel_path`, the relative path to the file from\n            `data_root_dir` to preserve folder structure when saving in case there are files in different\n            folders with the same file names. for example:\n            input_file_name: /foo/bar/test1/image.nii,\n            output_postfix: seg\n            output_ext: nii.gz\n            output_dir: /output,\n            data_root_dir: /foo/bar,\n            output will be: /output/test1/image/image_seg.nii.gz\n        print_log: whether to print log about the saved file path, etc. default to `True`.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        output_dir: str = \"./\",\n        output_postfix: str = \"trans\",\n        output_ext: str = \".nii.gz\",\n        resample: bool = True,\n        mode: Union[GridSampleMode, InterpolateMode, str] = \"nearest\",\n        padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER,\n        scale: Optional[int] = None,\n        dtype: DtypeLike = np.float64,\n        output_dtype: DtypeLike = np.float32,\n        squeeze_end_dims: bool = True,\n        data_root_dir: str = \"\",\n        print_log: bool = True,\n    ) -> None:\n        self.saver: Union[NiftiSaver, PNGSaver]\n        if output_ext in (\".nii.gz\", \".nii\"):\n            self.saver = NiftiSaver(\n                output_dir=output_dir,\n                output_postfix=output_postfix,\n                output_ext=output_ext,\n                resample=resample,\n                mode=GridSampleMode(mode),\n                padding_mode=padding_mode,\n                dtype=dtype,\n                output_dtype=output_dtype,\n                squeeze_end_dims=squeeze_end_dims,\n                data_root_dir=data_root_dir,\n                print_log=print_log,\n            )\n        elif output_ext == \".png\":\n            self.saver = PNGSaver(\n                output_dir=output_dir,\n                output_postfix=output_postfix,\n                output_ext=output_ext,\n                resample=resample,\n                mode=InterpolateMode(mode),\n                scale=scale,\n                data_root_dir=data_root_dir,\n                print_log=print_log,\n            )\n        else:\n            raise ValueError(f\"unsupported output extension: {output_ext}.\")\n\n    def __call__(self, img: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None):\n        \"\"\"\n        Args:\n            img: target data content that save into file.\n            meta_data: key-value pairs of meta_data corresponding to the data.\n\n        \"\"\"\n        self.saver.save(img, meta_data)\n", "path": "monai/transforms/io/array.py"}], "after_files": [{"content": "# Copyright 2020 - 2021 MONAI Consortium\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nA collection of \"vanilla\" transforms for IO functions\nhttps://github.com/Project-MONAI/MONAI/wiki/MONAI_Design\n\"\"\"\n\nimport sys\nfrom typing import Dict, List, Optional, Sequence, Union\n\nimport numpy as np\nimport torch\n\nfrom monai.config import DtypeLike\nfrom monai.data.image_reader import ImageReader, ITKReader, NibabelReader, NumpyReader, PILReader\nfrom monai.data.nifti_saver import NiftiSaver\nfrom monai.data.png_saver import PNGSaver\nfrom monai.transforms.transform import Transform\nfrom monai.utils import GridSampleMode, GridSamplePadMode\nfrom monai.utils import ImageMetaKey as Key\nfrom monai.utils import InterpolateMode, ensure_tuple, optional_import\n\nnib, _ = optional_import(\"nibabel\")\nImage, _ = optional_import(\"PIL.Image\")\n\n__all__ = [\"LoadImage\", \"SaveImage\"]\n\n\ndef switch_endianness(data, new=\"<\"):\n    \"\"\"\n    Convert the input `data` endianness to `new`.\n\n    Args:\n        data: input to be converted.\n        new: the target endianness, currently support \"<\" or \">\".\n    \"\"\"\n    if isinstance(data, np.ndarray):\n        # default to system endian\n        sys_native = ((sys.byteorder == \"little\") and \"<\") or \">\"\n        current_ = sys_native if data.dtype.byteorder not in (\"<\", \">\") else data.dtype.byteorder\n        if new not in (\"<\", \">\"):\n            raise NotImplementedError(f\"Not implemented option new={new}.\")\n        if current_ != new:\n            data = data.byteswap().newbyteorder(new)\n    elif isinstance(data, tuple):\n        data = tuple(switch_endianness(x, new) for x in data)\n    elif isinstance(data, list):\n        data = [switch_endianness(x, new) for x in data]\n    elif isinstance(data, dict):\n        data = {k: switch_endianness(v, new) for k, v in data.items()}\n    elif isinstance(data, (bool, str, float, int, type(None))):\n        pass\n    else:\n        raise AssertionError(f\"Unknown type: {type(data).__name__}\")\n    return data\n\n\nclass LoadImage(Transform):\n    \"\"\"\n    Load image file or files from provided path based on reader.\n    Automatically choose readers based on the supported suffixes and in below order:\n    - User specified reader at runtime when call this loader.\n    - Registered readers from the latest to the first in list.\n    - Default readers: (nii, nii.gz -> NibabelReader), (png, jpg, bmp -> PILReader),\n    (npz, npy -> NumpyReader), (others -> ITKReader).\n\n    \"\"\"\n\n    def __init__(\n        self,\n        reader: Optional[Union[ImageReader, str]] = None,\n        image_only: bool = False,\n        dtype: DtypeLike = np.float32,\n        *args,\n        **kwargs,\n    ) -> None:\n        \"\"\"\n        Args:\n            reader: register reader to load image file and meta data, if None, still can register readers\n                at runtime or use the default readers. If a string of reader name provided, will construct\n                a reader object with the `*args` and `**kwargs` parameters, supported reader name: \"NibabelReader\",\n                \"PILReader\", \"ITKReader\", \"NumpyReader\".\n            image_only: if True return only the image volume, otherwise return image data array and header dict.\n            dtype: if not None convert the loaded image to this data type.\n            args: additional parameters for reader if providing a reader name.\n            kwargs: additional parameters for reader if providing a reader name.\n\n        Note:\n            The transform returns image data array if `image_only` is True,\n            or a tuple of two elements containing the data array, and the meta data in a dict format otherwise.\n\n        \"\"\"\n        # set predefined readers as default\n        self.readers: List[ImageReader] = [ITKReader(), NumpyReader(), PILReader(), NibabelReader()]\n        if reader is not None:\n            if isinstance(reader, str):\n                supported_readers = {\n                    \"nibabelreader\": NibabelReader,\n                    \"pilreader\": PILReader,\n                    \"itkreader\": ITKReader,\n                    \"numpyreader\": NumpyReader,\n                }\n                reader = reader.lower()\n                if reader not in supported_readers:\n                    raise ValueError(f\"unsupported reader type: {reader}, available options: {supported_readers}.\")\n                self.register(supported_readers[reader](*args, **kwargs))\n            else:\n                self.register(reader)\n\n        self.image_only = image_only\n        self.dtype = dtype\n\n    def register(self, reader: ImageReader) -> List[ImageReader]:\n        \"\"\"\n        Register image reader to load image file and meta data, latest registered reader has higher priority.\n        Return all the registered image readers.\n\n        Args:\n            reader: registered reader to load image file and meta data based on suffix,\n                if all registered readers can't match suffix at runtime, use the default readers.\n\n        \"\"\"\n        if not isinstance(reader, ImageReader):\n            raise ValueError(f\"reader must be ImageReader object, but got {type(reader)}.\")\n        self.readers.append(reader)\n        return self.readers\n\n    def __call__(\n        self,\n        filename: Union[Sequence[str], str],\n        reader: Optional[ImageReader] = None,\n    ):\n        \"\"\"\n        Args:\n            filename: path file or file-like object or a list of files.\n                will save the filename to meta_data with key `filename_or_obj`.\n                if provided a list of files, use the filename of first file.\n            reader: runtime reader to load image file and meta data.\n\n        \"\"\"\n        if reader is None or not reader.verify_suffix(filename):\n            for r in reversed(self.readers):\n                if r.verify_suffix(filename):\n                    reader = r\n                    break\n\n        if reader is None:\n            raise RuntimeError(\n                f\"can not find suitable reader for this file: {filename}. \\\n                Please install dependency libraries: (nii, nii.gz) -> Nibabel, (png, jpg, bmp) -> PIL, \\\n                (npz, npy) -> Numpy, others -> ITK. Refer to the installation instruction: \\\n                https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies.\"\n            )\n\n        img = reader.read(filename)\n        img_array, meta_data = reader.get_data(img)\n        img_array = img_array.astype(self.dtype)\n\n        if self.image_only:\n            return img_array\n        meta_data[Key.FILENAME_OR_OBJ] = ensure_tuple(filename)[0]\n        # make sure all elements in metadata are little endian\n        meta_data = switch_endianness(meta_data, \"<\")\n\n        return img_array, meta_data\n\n\nclass SaveImage(Transform):\n    \"\"\"\n    Save transformed data into files, support NIfTI and PNG formats.\n    It can work for both numpy array and PyTorch Tensor in both preprocessing transform\n    chain and postprocessing transform chain.\n    The name of saved file will be `{input_image_name}_{output_postfix}{output_ext}`,\n    where the input image name is extracted from the provided meta data dictionary.\n    If no meta data provided, use index from 0 as the filename prefix.\n    It can also save a list of PyTorch Tensor or numpy array without `batch dim`.\n\n    Note: image should be channel-first shape: [C,H,W,[D]].\n\n    Args:\n        output_dir: output image directory.\n        output_postfix: a string appended to all output file names, default to `trans`.\n        output_ext: output file extension name, available extensions: `.nii.gz`, `.nii`, `.png`.\n        resample: whether to resample before saving the data array.\n            if saving PNG format image, based on the `spatial_shape` from metadata.\n            if saving NIfTI format image, based on the `original_affine` from metadata.\n        mode: This option is used when ``resample = True``. Defaults to ``\"nearest\"``.\n\n            - NIfTI files {``\"bilinear\"``, ``\"nearest\"``}\n                Interpolation mode to calculate output values.\n                See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample\n            - PNG files {``\"nearest\"``, ``\"linear\"``, ``\"bilinear\"``, ``\"bicubic\"``, ``\"trilinear\"``, ``\"area\"``}\n                The interpolation mode.\n                See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate\n\n        padding_mode: This option is used when ``resample = True``. Defaults to ``\"border\"``.\n\n            - NIfTI files {``\"zeros\"``, ``\"border\"``, ``\"reflection\"``}\n                Padding mode for outside grid values.\n                See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample\n            - PNG files\n                This option is ignored.\n\n        scale: {``255``, ``65535``} postprocess data by clipping to [0, 1] and scaling\n            [0, 255] (uint8) or [0, 65535] (uint16). Default is None to disable scaling.\n            it's used for PNG format only.\n        dtype: data type during resampling computation. Defaults to ``np.float64`` for best precision.\n            if None, use the data type of input data. To be compatible with other modules,\n            the output data type is always ``np.float32``.\n            it's used for NIfTI format only.\n        output_dtype: data type for saving data. Defaults to ``np.float32``.\n            it's used for NIfTI format only.\n        squeeze_end_dims: if True, any trailing singleton dimensions will be removed (after the channel\n            has been moved to the end). So if input is (C,H,W,D), this will be altered to (H,W,D,C), and\n            then if C==1, it will be saved as (H,W,D). If D also ==1, it will be saved as (H,W). If false,\n            image will always be saved as (H,W,D,C).\n            it's used for NIfTI format only.\n        data_root_dir: if not empty, it specifies the beginning parts of the input file's\n            absolute path. it's used to compute `input_file_rel_path`, the relative path to the file from\n            `data_root_dir` to preserve folder structure when saving in case there are files in different\n            folders with the same file names. for example:\n            input_file_name: /foo/bar/test1/image.nii,\n            output_postfix: seg\n            output_ext: nii.gz\n            output_dir: /output,\n            data_root_dir: /foo/bar,\n            output will be: /output/test1/image/image_seg.nii.gz\n        print_log: whether to print log about the saved file path, etc. default to `True`.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        output_dir: str = \"./\",\n        output_postfix: str = \"trans\",\n        output_ext: str = \".nii.gz\",\n        resample: bool = True,\n        mode: Union[GridSampleMode, InterpolateMode, str] = \"nearest\",\n        padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER,\n        scale: Optional[int] = None,\n        dtype: DtypeLike = np.float64,\n        output_dtype: DtypeLike = np.float32,\n        squeeze_end_dims: bool = True,\n        data_root_dir: str = \"\",\n        print_log: bool = True,\n    ) -> None:\n        self.saver: Union[NiftiSaver, PNGSaver]\n        if output_ext in (\".nii.gz\", \".nii\"):\n            self.saver = NiftiSaver(\n                output_dir=output_dir,\n                output_postfix=output_postfix,\n                output_ext=output_ext,\n                resample=resample,\n                mode=GridSampleMode(mode),\n                padding_mode=padding_mode,\n                dtype=dtype,\n                output_dtype=output_dtype,\n                squeeze_end_dims=squeeze_end_dims,\n                data_root_dir=data_root_dir,\n                print_log=print_log,\n            )\n        elif output_ext == \".png\":\n            self.saver = PNGSaver(\n                output_dir=output_dir,\n                output_postfix=output_postfix,\n                output_ext=output_ext,\n                resample=resample,\n                mode=InterpolateMode(mode),\n                scale=scale,\n                data_root_dir=data_root_dir,\n                print_log=print_log,\n            )\n        else:\n            raise ValueError(f\"unsupported output extension: {output_ext}.\")\n\n    def __call__(self, img: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None):\n        \"\"\"\n        Args:\n            img: target data content that save into file.\n            meta_data: key-value pairs of meta_data corresponding to the data.\n\n        \"\"\"\n        self.saver.save(img, meta_data)\n\n        return img\n", "path": "monai/transforms/io/array.py"}]}