Skip to content
8 changes: 8 additions & 0 deletions monai/config/deviceconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,11 @@ def print_config(file=sys.stdout):

def set_visible_devices(*dev_inds):
os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, dev_inds))


def get_torch_version_tuple():
"""
Returns:
tuple of ints represents the pytorch major/minor version.
"""
return tuple([int(x) for x in torch.__version__.split(".")[:2]])
2 changes: 1 addition & 1 deletion monai/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class PersistentDataset(Dataset):

For a composite transform like

.. code-block:: python
.. code-block:: python

[ LoadNiftid(keys=['image', 'label']),
Orientationd(keys=['image', 'label'], axcodes='RAS'),
Expand Down
9 changes: 6 additions & 3 deletions monai/data/nifti_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,20 @@ def __init__(
self.dtype = dtype
self._data_index = 0

def save(self, data: Union[torch.Tensor, np.ndarray], meta_data=None):
def save(self, data: Union[torch.Tensor, np.ndarray], meta_data: dict = None):
"""
Save data into a Nifti file.
The metadata could optionally have the following keys:
The meta_data could optionally have the following keys:

- ``'filename_or_obj'`` -- for output file name creation, corresponding to filename or object.
- ``'original_affine'`` -- for data orientation handling, defaulting to an identity matrix.
- ``'affine'`` -- for data output affine, defaulting to an identity matrix.
- ``'spatial_shape'`` -- for data output shape.

If meta_data is None, use the default index from 0 to save data instead.
When meta_data is specified, the saver will try to resample batch data from the space
defined by "affine" to the space defined by "original_affine".

If meta_data is None, use the default index (starting from 0) as the filename.

args:
data (Tensor or ndarray): target data content that to be saved as a NIfTI format file.
Expand Down
42 changes: 14 additions & 28 deletions monai/data/png_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

from typing import Union

import torch
import numpy as np
import torch

from monai.data.png_writer import write_png

from .utils import create_file_basename


Expand All @@ -31,49 +33,39 @@ def __init__(
output_postfix: str = "seg",
output_ext: str = ".png",
resample: bool = True,
interp_order: int = 3,
mode: str = "constant",
cval: float = 0.0,
interp_order: str = "nearest",
scale: bool = False,
):
"""
Args:
output_dir (str): output image directory.
output_postfix (str): a string appended to all output file names.
output_ext (str): output file extension name.
resample: whether to resample and resize if providing spatial_shape in the metadata.
Defaults to True.
interp_order (int): the order of the spline interpolation, default is InterpolationCode.SPLINE3.
This option is used when spatial_shape is specified and different from the data shape.
The order has to be in the range 0 - 5. Defaults to 3.
mode (`constant|edge|symmetric|reflect|wrap`):
The mode parameter determines how the input array is extended beyond its boundaries.
This option is used when spatial_shape is specified and different from the data shape.
Defaults to "constant".
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
This option is used when spatial_shape is specified and different from the data shape.
scale: whether to scale data with 255 and convert to uint8 for data in range [0, 1].
resample (bool): whether to resample and resize if providing spatial_shape in the metadata.
interp_order (`nearest|bilinear|bicubic|area`):
the interpolation mode. Default="nearest".
See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate
scale (bool): whether to scale data with 255 and convert to uint8 for data in range [0, 1].

"""
self.output_dir = output_dir
self.output_postfix = output_postfix
self.output_ext = output_ext
self.resample = resample
self.interp_order = interp_order
self.mode = mode
self.cval = cval
self.scale = scale

self._data_index = 0

def save(self, data: Union[torch.Tensor, np.ndarray], meta_data=None):
def save(self, data: Union[torch.Tensor, np.ndarray], meta_data: dict = None):
"""
Save data into a png file.
The metadata could optionally have the following keys:
The meta_data could optionally have the following keys:

- ``'filename_or_obj'`` -- for output file name creation, corresponding to filename or object.
- ``'spatial_shape'`` -- for data output shape.

If meta_data is None, use the default index from 0 to save data instead.
If meta_data is None, use the default index (starting from 0) as the filename.

args:
data (Tensor or ndarray): target data content that to be saved as a png format file.
Expand Down Expand Up @@ -103,13 +95,7 @@ def save(self, data: Union[torch.Tensor, np.ndarray], meta_data=None):
raise ValueError("PNG image should only have 1, 3 or 4 channels.")

write_png(
data,
file_name=filename,
output_shape=spatial_shape,
interp_order=self.interp_order,
mode=self.mode,
cval=self.cval,
scale=self.scale,
data, file_name=filename, output_shape=spatial_shape, interp_order=self.interp_order, scale=self.scale,
)

def save_batch(self, batch_data: Union[torch.Tensor, np.ndarray], meta_data=None):
Expand Down
50 changes: 22 additions & 28 deletions monai/data/png_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,28 @@
# limitations under the License.

import numpy as np
from skimage import io, transform
from skimage import io

from monai.transforms import Resize
from monai.utils.misc import ensure_tuple_rep


def write_png(
data,
file_name,
output_shape=None,
interp_order: int = 3,
mode="constant",
cval: float = 0.0,
scale: bool = False,
plugin=None,
**plugin_args,
data, file_name, output_shape=None, interp_order: str = "bicubic", scale: bool = False, plugin=None, **plugin_args,
):
"""
Write numpy data into png files to disk.
Write numpy data into png files to disk.
Spatially it supports HW for 2D.(H,W) or (H,W,3) or (H,W,4)
It's based on skimage library: https://scikit-image.org/docs/dev/api/skimage

Args:
data (numpy.ndarray): input data to write to file.
file_name (string): expected file name that saved on disk.
output_shape (None or tuple of ints): output image shape.
interp_order (int): the order of the spline interpolation, default is InterpolationCode.SPLINE3.
The order has to be in the range 0 - 5. Defaults to 3.
this option is used when `output_shape != None`.
mode (`constant|edge|symmetric|reflect|wrap`):
The mode parameter determines how the input array is extended beyond its boundaries.
This option is used when `output_shape != None`. Defaults to "constant".
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
this option is used when `output_shape != None`.
scale: whether to scale data with 255 and convert to uint8 for data in range [0, 1].
interp_order (`nearest|linear|bilinear|bicubic|trilinear|area`):
the interpolation mode. Default="bicubic".
See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate
scale (bool): whether to postprocess data by clipping to [0, 1] and scaling [0, 255] (uint8).
plugin (string): name of plugin to use in `imsave`. By default, the different plugins
are tried(starting with imageio) until a suitable candidate is found.
plugin_args (keywords): arguments passed to the given plugin.
Expand All @@ -50,17 +40,21 @@ def write_png(
assert isinstance(data, np.ndarray), "input data must be numpy array."

if output_shape is not None:
assert (
isinstance(output_shape, (list, tuple)) and len(output_shape) == 2
), "output_shape must be a list of 2 values (H, W)."

output_shape = ensure_tuple_rep(output_shape, 2)
xform = Resize(spatial_size=output_shape, interp_order=interp_order)
_min, _max = np.min(data), np.max(data)
if len(data.shape) == 3:
output_shape = tuple(output_shape) + (data.shape[2],)

data = transform.resize(data, output_shape, order=interp_order, mode=mode, cval=cval, preserve_range=True)
data = np.moveaxis(data, -1, 0) # to channel first
data = xform(data)
data = np.moveaxis(data, 0, -1)
else: # (H, W)
data = np.expand_dims(data, 0) # make a channel
data = xform(data)[0] # first channel
if interp_order != "nearest":
data = np.clip(data, _min, _max)

if scale:
assert np.min(data) >= 0 and np.max(data) <= 1, "png writer only can scale data in range [0, 1]."
data = np.clip(data, 0.0, 1.0) # png writer only can scale data in range [0, 1].
data = 255 * data
data = data.astype(np.uint8)
io.imsave(file_name, data, plugin=plugin, **plugin_args)
Expand Down
32 changes: 12 additions & 20 deletions monai/handlers/segmentation_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Optional, Union, Callable
import logging
from typing import Callable, Optional, Union

import numpy as np
from ignite.engine import Events, Engine
import logging
from ignite.engine import Engine, Events

from monai.data import NiftiSaver, PNGSaver


Expand All @@ -28,9 +29,8 @@ def __init__(
output_postfix: str = "seg",
output_ext: str = ".nii.gz",
resample: bool = True,
interp_order="bilinear",
interp_order: str = "nearest",
mode: str = "border",
cval: float = 0.0,
scale: bool = False,
dtype: Optional[np.dtype] = None,
batch_transform: Callable = lambda x: x,
Expand All @@ -43,19 +43,16 @@ def __init__(
output_postfix (str): a string appended to all output file names.
output_ext (str): output file extension name.
resample (bool): whether to resample before saving the data array.
interp_order (int or str):
The interpolation mode. This option is used when `resample = True`.
When saving NIfTI files, the options are "nearest", "bilinear". Defaults to "bilinear".
See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
When saving PNG files, this sets the order of the spline interpolation.
The order has to be in the range 0 - 5.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html
interp_order (str):
The interpolation mode. Defaults to "nearest". This option is used when `resample = True`.
Comment thread
wyli marked this conversation as resolved.
Resolved
When saving NIfTI files, the available options are "nearest", "bilinear"
See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample.
When saving PNG files, the available options are "nearest", "bilinear", "bicubic", "area".
See also: https://pytorch.org/docs/stable/nn.functional.html#interpolate.
mode (str): The mode parameter determines how the input array is extended beyond its boundaries.
This option is used when `resample = True`.
When saving NIfTI files, the options are "zeros", "border", "reflection". Default is "border".
When saving PNG files, the options are "reflect", "constant", "nearest", "mirror", "wrap".
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
this option is used when `resample = True`. It's used for PNG format only.
When saving PNG files, the options is ignored.
scale (bool): whether to scale data with 255 and convert to uint8 for data in range [0, 1].
It's used for PNG format only.
dtype (np.dtype, optional): convert the image data to save to this data type.
Expand All @@ -81,17 +78,12 @@ def __init__(
dtype=dtype,
)
elif output_ext == ".png":
# handling the function's default
interp_order = 1 if interp_order == "bilinear" else interp_order
mode = "edge" if mode == "border" else mode
self.saver = PNGSaver(
output_dir=output_dir,
output_postfix=output_postfix,
output_ext=output_ext,
resample=resample,
interp_order=interp_order,
mode=mode,
cval=cval,
scale=scale,
)
self.batch_transform = batch_transform
Expand Down
Loading