|
| 1 | +# Copyright (c) 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 "functional" transforms for spatial operations |
| 13 | +https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import numpy as np |
| 19 | +import torch |
| 20 | +from torch.nn.functional import pad as pad_pt |
| 21 | + |
| 22 | +from monai.data.meta_obj import get_track_meta |
| 23 | +from monai.data.meta_tensor import MetaTensor |
| 24 | +from monai.transforms.inverse import TraceableTransform |
| 25 | +from monai.transforms.utils import convert_pad_mode, create_translate |
| 26 | +from monai.utils import TraceKeys, convert_to_dst_type, convert_to_tensor |
| 27 | + |
| 28 | +__all__ = ["pad_nd", "pad_func"] |
| 29 | + |
| 30 | + |
| 31 | +def _np_pad(img: torch.Tensor, pad_width: list[tuple[int, int]], mode: str, **kwargs) -> torch.Tensor: |
| 32 | + img_np = img.detach().cpu().numpy() if isinstance(img, torch.Tensor) else img |
| 33 | + mode = convert_pad_mode(dst=img_np, mode=mode).value |
| 34 | + if mode == "constant" and "value" in kwargs: |
| 35 | + kwargs["constant_values"] = kwargs.pop("value") |
| 36 | + out = torch.as_tensor(np.pad(img, pad_width, mode=mode, **kwargs)) # type: ignore |
| 37 | + if isinstance(img, MetaTensor): |
| 38 | + out = convert_to_dst_type(out, dst=img)[0] |
| 39 | + return out |
| 40 | + |
| 41 | + |
| 42 | +def _pt_pad(img: torch.Tensor, pad_width: list[tuple[int, int]], mode: str, **kwargs) -> torch.Tensor: |
| 43 | + pt_pad_width = [val for sublist in pad_width[1:] for val in sublist[::-1]][::-1] |
| 44 | + # torch.pad expects `[B, C, H, W, [D]]` shape |
| 45 | + return pad_pt(img.unsqueeze(0), pt_pad_width, mode=mode, **kwargs).squeeze(0) |
| 46 | + |
| 47 | + |
| 48 | +def pad_nd(img: torch.Tensor, to_pad: list[tuple[int, int]], mode: str, **kwargs): |
| 49 | + """ |
| 50 | + PyTorch/Numpy pad ``img`` with integers ``to_pad`` amounts. Depending on the ``mode`` and input dtype, |
| 51 | + a suitable backend will be used automatically. |
| 52 | +
|
| 53 | + Args: |
| 54 | + img: data to be transformed, assuming `img` is channel-first and padding doesn't apply to the channel dim. |
| 55 | + to_pad: the amount to be padded in each dimension [(low_H, high_H), (low_W, high_W), ...]. |
| 56 | + default to `self.to_pad`. |
| 57 | + mode: available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, |
| 58 | + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} |
| 59 | + (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. |
| 60 | + One of the listed string values or a user supplied function. Defaults to ``"constant"``. |
| 61 | + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html |
| 62 | + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html |
| 63 | + kwargs: other arguments for the `np.pad` or `torch.pad` function. |
| 64 | + note that `np.pad` treats channel dimension as the first dimension. |
| 65 | + """ |
| 66 | + if mode in {"linear_ramp", "maximum", "mean", "median", "minimum", "symmetric", "empty"}: |
| 67 | + return _np_pad(img, pad_width=to_pad, mode=mode, **kwargs) |
| 68 | + mode = convert_pad_mode(dst=img, mode=mode).value |
| 69 | + try: |
| 70 | + _pad = ( |
| 71 | + _pt_pad |
| 72 | + if mode in {"reflect", "replicate"} and img.dtype not in {torch.int16, torch.int64, torch.bool, torch.uint8} |
| 73 | + else _np_pad |
| 74 | + ) |
| 75 | + return _pad(img, pad_width=to_pad, mode=mode, **kwargs) |
| 76 | + except (ValueError, TypeError, RuntimeError) as err: |
| 77 | + if isinstance(err, NotImplementedError) or any( |
| 78 | + k in str(err) for k in ("supported", "unexpected keyword", "implemented") |
| 79 | + ): |
| 80 | + return _np_pad(img, pad_width=to_pad, mode=mode, **kwargs) |
| 81 | + raise ValueError(f"{img.shape} {to_pad} {mode} {kwargs} {img.dtype} {img.device}") from err |
| 82 | + |
| 83 | + |
| 84 | +def pad_func(img: torch.Tensor, to_pad: list[tuple[int, int]], mode: str, transform_info: dict, kwargs): |
| 85 | + """ |
| 86 | + Functional implementation of padding a MetaTensor. This function operates eagerly or lazily according |
| 87 | + to ``transform_info[TraceKeys.LAZY_EVALUATION]`` (default ``False``). |
| 88 | +
|
| 89 | + Args: |
| 90 | + img: data to be transformed, assuming `img` is channel-first and padding doesn't apply to the channel dim. |
| 91 | + to_pad: the amount to be padded in each dimension [(low_H, high_H), (low_W, high_W), ...]. |
| 92 | + default to `self.to_pad`. |
| 93 | + mode: available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, |
| 94 | + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} |
| 95 | + (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. |
| 96 | + One of the listed string values or a user supplied function. Defaults to ``"constant"``. |
| 97 | + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html |
| 98 | + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html |
| 99 | + transform_info: a dictionary with the relevant information pertaining to an applied transform. |
| 100 | + kwargs: other arguments for the `np.pad` or `torch.pad` function. |
| 101 | + note that `np.pad` treats channel dimension as the first dimension. |
| 102 | + """ |
| 103 | + extra_info = {"padded": to_pad} |
| 104 | + img_size = img.peek_pending_shape() if isinstance(img, MetaTensor) else img.shape[1:] |
| 105 | + spatial_rank = img.peek_pending_rank() if isinstance(img, MetaTensor) else 3 |
| 106 | + do_pad = np.asarray(to_pad).any() |
| 107 | + if do_pad: |
| 108 | + to_pad = list(to_pad) |
| 109 | + if len(to_pad) < len(img.shape): |
| 110 | + to_pad = list(to_pad) + [(0, 0)] * (len(img.shape) - len(to_pad)) |
| 111 | + to_shift = [-s[0] for s in to_pad[1:]] # skipping the channel pad |
| 112 | + xform = create_translate(spatial_rank, to_shift) |
| 113 | + shape = [d + s + e for d, (s, e) in zip(img_size, to_pad[1:])] |
| 114 | + else: |
| 115 | + shape = img_size |
| 116 | + xform = torch.eye(int(spatial_rank) + 1, device=torch.device("cpu"), dtype=torch.float64) |
| 117 | + meta_info = TraceableTransform.track_transform_meta( |
| 118 | + img, |
| 119 | + sp_size=shape, |
| 120 | + affine=xform, |
| 121 | + extra_info=extra_info, |
| 122 | + orig_size=img_size, |
| 123 | + transform_info=transform_info, |
| 124 | + lazy_evaluation=transform_info.get(TraceKeys.LAZY_EVALUATION, False), |
| 125 | + ) |
| 126 | + out = convert_to_tensor(img.as_tensor() if isinstance(img, MetaTensor) else img, track_meta=get_track_meta()) |
| 127 | + if transform_info.get(TraceKeys.LAZY_EVALUATION, False): |
| 128 | + return out.copy_meta_from(meta_info) if isinstance(out, MetaTensor) else meta_info |
| 129 | + out = pad_nd(out, to_pad, mode, **kwargs) if do_pad else out |
| 130 | + out = convert_to_tensor(out, track_meta=get_track_meta()) |
| 131 | + return out.copy_meta_from(meta_info) if isinstance(out, MetaTensor) else out |
0 commit comments