Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
43 changes: 26 additions & 17 deletions monai/data/nifti_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Union, Optional
from typing import Optional, Union

import numpy as np
import torch

from monai.data.nifti_writer import write_nifti

from .utils import create_file_basename


Expand All @@ -31,37 +33,31 @@ def __init__(
output_postfix: str = "seg",
output_ext: str = ".nii.gz",
resample: bool = True,
interp_order: int = 3,
mode: str = "constant",
cval: Union[int, float] = 0,
interp_order: str = "bilinear",
mode: str = "border",
dtype: Optional[np.dtype] = None,
):
"""
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 before saving the data array.
interp_order: the order of the spline interpolation, default is InterpolationCode.SPLINE3.
The order has to be in the range 0 - 5.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html
this option is used when `resample = True`.
mode (`reflect|constant|nearest|mirror|wrap`):
resample (bool): whether to resample before saving the data array.
interp_order (`nearest|bilinear`): the interpolation mode, default is "bilinear".
See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
This option is used when `resample = True`.
mode (`zeros|border|reflection`):
The mode parameter determines how the input array is extended beyond its boundaries.
this option is used when `resample = True`.
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
this option is used when `resample = True`.
Defaults to "border". This option is used when `resample = True`.
dtype (np.dtype, optional): convert the image data to save to this data type.
If None, keep the original type of data.

"""
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.dtype = dtype
self._data_index = 0

Expand Down Expand Up @@ -95,6 +91,9 @@ def save(self, data: Union[torch.Tensor, np.ndarray], meta_data=None):
data = data.detach().cpu().numpy()
filename = create_file_basename(self.output_postfix, filename, self.output_dir)
filename = f"{filename}{self.output_ext}"
# change data shape to be (channel, h, w, d)
while len(data.shape) < 4:
data = np.expand_dims(data, -1)
Comment thread
wyli marked this conversation as resolved.
Resolved
# change data to "channel last" format and write to nifti format file
data = np.moveaxis(data, 0, -1)
write_nifti(
Expand All @@ -106,12 +105,22 @@ def save(self, data: Union[torch.Tensor, np.ndarray], meta_data=None):
output_shape=spatial_shape,
interp_order=self.interp_order,
mode=self.mode,
cval=self.cval,
dtype=self.dtype or data.dtype,
)

def save_batch(self, batch_data: Union[torch.Tensor, np.ndarray], meta_data=None):
"""Save a batch of data into Nifti format files.
"""
Save a batch of data into Nifti format files.

Spatially it supports up to three dimensions, that is, H, HW, HWD for
1D, 2D, 3D respectively (with resampling supports for 2D and 3D only).

When saving multiple time steps or multiple channels `batch_data`,
time and/or modality axes should be appended after the batch dimensions.
For example, the shape of a batch of 2D eight-class
segmentation probabilities to be saved could be `(batch, 8, 64, 64)`;
in this case each item in the batch will be saved as (64, 64, 1, 8)
NIfTI file (the third dimension is reserved as a spatial dimension).

args:
batch_data (Tensor or ndarray): target batch data content that save into NIfTI format.
Expand Down
78 changes: 40 additions & 38 deletions monai/data/nifti_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@

import nibabel as nib
import numpy as np
import scipy.ndimage
import torch

from monai.data.utils import compute_shape_offset, to_affine_nd, InterpolationCode
from monai.data.utils import compute_shape_offset, to_affine_nd
from monai.networks.layers import AffineTransform


def write_nifti(
Expand All @@ -23,9 +24,8 @@ def write_nifti(
target_affine=None,
resample: bool = True,
output_shape=None,
interp_order=InterpolationCode.SPLINE3,
mode="constant",
cval=0,
interp_order: str = "bilinear",
mode: str = "border",
dtype=None,
):
"""
Expand Down Expand Up @@ -54,7 +54,8 @@ def write_nifti(
When saving multiple time steps or multiple channels `data`, time and/or
modality axes should be appended after the first three dimensions. For
example, shape of 2D eight-class segmentation probabilities to be saved
could be `(64, 64, 1, 8)`,
could be `(64, 64, 1, 8)`. Also, data in shape (64, 64, 8), (64, 64, 8, 1)
will be considered as a single-channel 3D image.

Args:
data (numpy.ndarray): input data to write to file.
Expand All @@ -66,16 +67,13 @@ def write_nifti(
resample: whether to run resampling when the target affine
could not be achieved by swapping/flipping data axes.
output_shape (None or tuple of ints): output image shape.
this option is used when resample = True.
interp_order: the order of the spline interpolation, default is InterpolationCode.SPLINE3.
The order has to be in the range 0 - 5.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html
this option is used when `resample = True`.
mode (`reflect|constant|nearest|mirror|wrap`):
This option is used when resample = True.
interp_order (`nearest|bilinear`): the interpolation mode, default is "bilinear".
See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
This option is used when `resample = True`.
mode (`zeros|border|reflection`):
Comment thread
wyli marked this conversation as resolved.
Resolved
The mode parameter determines how the input array is extended beyond its boundaries.
this option is used when `resample = True`.
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
this option is used when `resample = True`.
Defaults to "border". This option is used when `resample = True`.
dtype (np.dtype, optional): convert the image to save to this data type.
"""
assert isinstance(data, np.ndarray), "input data must be numpy array."
Expand All @@ -88,7 +86,7 @@ def write_nifti(
target_affine = affine
target_affine = to_affine_nd(sr, target_affine)

if np.allclose(affine, target_affine):
if np.allclose(affine, target_affine, atol=1e-3):
# no affine changes, save (data, affine)
results_img = nib.Nifti1Image(data.astype(dtype), to_affine_nd(3, target_affine))
nib.save(results_img, file_name)
Expand All @@ -101,38 +99,42 @@ def write_nifti(
data_shape = data.shape
data = nib.orientations.apply_orientation(data, ornt_transform)
_affine = affine @ nib.orientations.inv_ornt_aff(ornt_transform, data_shape)
if np.allclose(_affine, target_affine) or not resample:
if np.allclose(_affine, target_affine, atol=1e-3) or not resample:
results_img = nib.Nifti1Image(data.astype(dtype), to_affine_nd(3, target_affine))
nib.save(results_img, file_name)
return

# need resampling
affine_xform = AffineTransform(
normalized=False, mode=interp_order, padding_mode=mode, align_corners=True, reverse_indexing=True
)
transform = np.linalg.inv(_affine) @ target_affine
if output_shape is None:
output_shape, _ = compute_shape_offset(data.shape, _affine, target_affine)
dtype = dtype or data.dtype
if data.ndim > 3: # multi channel, resampling each channel
while len(output_shape) < 3:
output_shape = list(output_shape) + [1]
spatial_shape, channel_shape = data.shape[:3], data.shape[3:]
data_ = data.astype(dtype).reshape(list(spatial_shape) + [-1])
data_chns = []
for chn in range(data_.shape[-1]):
data_chns.append(
scipy.ndimage.affine_transform(
data_[..., chn],
matrix=transform,
output_shape=output_shape[:3],
order=interp_order,
mode=mode,
cval=cval,
)
)
data_chns_ = np.stack(data_chns, axis=-1)
data_ = data_chns_.reshape(list(data_chns_.shape[:3]) + list(channel_shape))
else:
data_ = data.astype(dtype)
data_ = scipy.ndimage.affine_transform(
data_, matrix=transform, output_shape=output_shape[: data_.ndim], order=interp_order, mode=mode, cval=cval
data_ = data.reshape(list(spatial_shape) + [-1])
data_ = np.moveaxis(data_, -1, 0) # channel first for pytorch
data_ = affine_xform(
torch.from_numpy((data_.astype(np.float64))[None]),
torch.from_numpy(transform.astype(np.float64)),
spatial_size=output_shape[:3],
)
data_ = data_.squeeze(0).detach().cpu().numpy()
data_ = np.moveaxis(data_, 0, -1) # channel last for nifti
data_ = data_.reshape(list(data_.shape[:3]) + list(channel_shape))
else: # single channel image, need to expand to have batch and channel
while len(output_shape) < len(data.shape):
output_shape = list(output_shape) + [1]
data_ = affine_xform(
torch.from_numpy((data.astype(np.float64))[None, None]),
torch.from_numpy(transform.astype(np.float64)),
spatial_size=output_shape[: len(data.shape)],
)
results_img = nib.Nifti1Image(data_, to_affine_nd(3, target_affine))
data_ = data_.squeeze(0).squeeze(0).detach().cpu().numpy()
dtype = dtype or data.dtype
results_img = nib.Nifti1Image(data_.astype(dtype), to_affine_nd(3, target_affine))
nib.save(results_img, file_name)
return
8 changes: 5 additions & 3 deletions monai/data/png_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,14 @@ def __init__(
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.
interp_order: the order of the spline interpolation, default is InterpolationCode.SPLINE3.
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.
mode (`reflect|constant|nearest|mirror|wrap`):
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].
Expand Down
8 changes: 4 additions & 4 deletions monai/data/png_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ def write_png(
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: the order of the spline interpolation, default is InterpolationCode.SPLINE3.
The order has to be in the range 0 - 5.
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 (`reflect|constant|nearest|mirror|wrap`):
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`.
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].
Expand Down
4 changes: 2 additions & 2 deletions monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,12 +387,12 @@ def to_affine_nd(r, affine):
"""
affine_ = np.array(affine, dtype=np.float64)
if affine_.ndim != 2:
raise ValueError("input affine must have two dimensions")
raise ValueError(f"input affine matrix must have two dimensions, got {affine_.ndim}.")
new_affine = np.array(r, dtype=np.float64, copy=True)
if new_affine.ndim == 0:
sr = new_affine.astype(int)
if not np.isfinite(sr) or sr < 0:
raise ValueError("r must be positive.")
raise ValueError(f"r must be positive, got {sr}.")
new_affine = np.eye(sr + 1, dtype=np.float64)
d = max(min(len(new_affine) - 1, len(affine_) - 1), 1)
new_affine[:d, :d] = affine_[:d, :d]
Expand Down
46 changes: 35 additions & 11 deletions monai/handlers/segmentation_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ def __init__(
output_postfix: str = "seg",
output_ext: str = ".nii.gz",
resample: bool = True,
interp_order: int = 0,
mode: str = "constant",
interp_order="bilinear",
mode: str = "border",
cval: Union[int, float] = 0,
scale: bool = False,
dtype: Optional[np.dtype] = None,
Expand All @@ -42,17 +42,21 @@ def __init__(
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 before saving the data array.
interp_order: the order of the spline interpolation, default is 0.
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.
Comment thread
Nic-Ma marked this conversation as resolved.
Resolved
The order has to be in the range 0 - 5.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html
mode (str): The mode parameter determines how the input array is extended beyond its boundaries.
This option is used when `resample = True`.
mode (`reflect|constant|nearest|mirror|wrap`):
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`.
scale: whether to scale data with 255 and convert to uint8 for data in range [0, 1].
this option is used when `resample = True`. It's used for PNG format only.
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.
If None, keep the original type of data. It's used for Nifti format only.
Expand All @@ -67,9 +71,29 @@ def __init__(
"""
self.saver: Union[NiftiSaver, PNGSaver]
if output_ext in (".nii.gz", ".nii"):
self.saver = NiftiSaver(output_dir, output_postfix, output_ext, resample, interp_order, mode, cval, dtype)
self.saver = NiftiSaver(
output_dir=output_dir,
output_postfix=output_postfix,
output_ext=output_ext,
resample=resample,
interp_order=interp_order,
mode=mode,
dtype=dtype,
)
elif output_ext == ".png":
self.saver = PNGSaver(output_dir, output_postfix, output_ext, resample, interp_order, mode, cval, scale)
# 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
self.output_transform = output_transform

Expand Down
3 changes: 1 addition & 2 deletions monai/networks/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import warnings
import torch
import torch.nn.functional as f


def one_hot(labels, num_classes: int, dtype: torch.dtype = torch.float):
Expand Down Expand Up @@ -96,7 +95,7 @@ def normalize_transform(shape, device=None, dtype=None, align_corners: bool = Fa
norm[norm <= 0.0] = 2.0
norm = 2.0 / norm
norm = torch.diag(torch.cat((norm, torch.ones((1,), dtype=torch.float64, device=device))))
norm[:-1, -1] = 1.0 / torch.tensor(shape, dtype=torch.float32, device=device) - 1.0
norm[:-1, -1] = 1.0 / torch.tensor(shape, dtype=torch.float64, device=device) - 1.0
norm = norm.unsqueeze(0).to(dtype=dtype)
norm.requires_grad = False
return norm
Expand Down
Loading