|
| 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 | +from __future__ import annotations |
| 13 | + |
| 14 | +from typing import Sequence |
| 15 | + |
| 16 | +import torch |
| 17 | +import torch.nn.functional as F |
| 18 | +from torch import Tensor |
| 19 | + |
| 20 | +from monai.config import NdarrayOrTensor |
| 21 | +from monai.utils import convert_data_type, convert_to_dst_type, ensure_tuple_rep |
| 22 | + |
| 23 | + |
| 24 | +def erode(mask: NdarrayOrTensor, filter_size: int | Sequence[int] = 3, pad_value: float = 1.0) -> NdarrayOrTensor: |
| 25 | + """ |
| 26 | + Erode 2D/3D binary mask. |
| 27 | +
|
| 28 | + Args: |
| 29 | + mask: input 2D/3D binary mask, [N,C,M,N] or [N,C,M,N,P] torch tensor or ndarray. |
| 30 | + filter_size: erosion filter size, has to be odd numbers, default to be 3. |
| 31 | + pad_value: the filled value for padding. We need to pad the input before filtering |
| 32 | + to keep the output with the same size as input. Usually use default value |
| 33 | + and not changed. |
| 34 | +
|
| 35 | + Return: |
| 36 | + eroded mask, same shape and data type as input. |
| 37 | +
|
| 38 | + Example: |
| 39 | +
|
| 40 | + .. code-block:: python |
| 41 | +
|
| 42 | + # define a naive mask |
| 43 | + mask = torch.zeros(3,2,3,3,3) |
| 44 | + mask[:,:,1,1,1] = 1.0 |
| 45 | + filter_size = 3 |
| 46 | + erode_result = erode(mask, filter_size) # expect torch.zeros(3,2,3,3,3) |
| 47 | + dilate_result = dilate(mask, filter_size) # expect torch.ones(3,2,3,3,3) |
| 48 | + """ |
| 49 | + mask_t, *_ = convert_data_type(mask, torch.Tensor) |
| 50 | + res_mask_t = erode_t(mask_t, filter_size=filter_size, pad_value=pad_value) |
| 51 | + res_mask: NdarrayOrTensor |
| 52 | + res_mask, *_ = convert_to_dst_type(src=res_mask_t, dst=mask) |
| 53 | + return res_mask |
| 54 | + |
| 55 | + |
| 56 | +def dilate(mask: NdarrayOrTensor, filter_size: int | Sequence[int] = 3, pad_value: float = 0.0) -> NdarrayOrTensor: |
| 57 | + """ |
| 58 | + Dilate 2D/3D binary mask. |
| 59 | +
|
| 60 | + Args: |
| 61 | + mask: input 2D/3D binary mask, [N,C,M,N] or [N,C,M,N,P] torch tensor or ndarray. |
| 62 | + filter_size: dilation filter size, has to be odd numbers, default to be 3. |
| 63 | + pad_value: the filled value for padding. We need to pad the input before filtering |
| 64 | + to keep the output with the same size as input. Usually use default value |
| 65 | + and not changed. |
| 66 | +
|
| 67 | + Return: |
| 68 | + dilated mask, same shape and data type as input. |
| 69 | +
|
| 70 | + Example: |
| 71 | +
|
| 72 | + .. code-block:: python |
| 73 | +
|
| 74 | + # define a naive mask |
| 75 | + mask = torch.zeros(3,2,3,3,3) |
| 76 | + mask[:,:,1,1,1] = 1.0 |
| 77 | + filter_size = 3 |
| 78 | + erode_result = erode(mask,filter_size) # expect torch.zeros(3,2,3,3,3) |
| 79 | + dilate_result = dilate(mask,filter_size) # expect torch.ones(3,2,3,3,3) |
| 80 | + """ |
| 81 | + mask_t, *_ = convert_data_type(mask, torch.Tensor) |
| 82 | + res_mask_t = dilate_t(mask_t, filter_size=filter_size, pad_value=pad_value) |
| 83 | + res_mask: NdarrayOrTensor |
| 84 | + res_mask, *_ = convert_to_dst_type(src=res_mask_t, dst=mask) |
| 85 | + return res_mask |
| 86 | + |
| 87 | + |
| 88 | +def get_morphological_filter_result_t(mask_t: Tensor, filter_size: int | Sequence[int], pad_value: float) -> Tensor: |
| 89 | + """ |
| 90 | + Apply a morphological filter to a 2D/3D binary mask tensor. |
| 91 | +
|
| 92 | + Args: |
| 93 | + mask_t: input 2D/3D binary mask, [N,C,M,N] or [N,C,M,N,P] torch tensor. |
| 94 | + filter_size: morphological filter size, has to be odd numbers. |
| 95 | + pad_value: the filled value for padding. We need to pad the input before filtering |
| 96 | + to keep the output with the same size as input. |
| 97 | +
|
| 98 | + Return: |
| 99 | + Tensor: Morphological filter result mask, same shape as input. |
| 100 | + """ |
| 101 | + spatial_dims = len(mask_t.shape) - 2 |
| 102 | + if spatial_dims not in [2, 3]: |
| 103 | + raise ValueError( |
| 104 | + f"spatial_dims must be either 2 or 3, " |
| 105 | + f"got spatial_dims={spatial_dims} for mask tensor with shape of {mask_t.shape}." |
| 106 | + ) |
| 107 | + |
| 108 | + # Define the structuring element |
| 109 | + filter_size = ensure_tuple_rep(filter_size, spatial_dims) |
| 110 | + if any(size % 2 == 0 for size in filter_size): |
| 111 | + raise ValueError(f"All dimensions in filter_size must be odd numbers, got {filter_size}.") |
| 112 | + |
| 113 | + structuring_element = torch.ones((mask_t.shape[1], mask_t.shape[1]) + filter_size).to(mask_t.device) |
| 114 | + |
| 115 | + # Pad the input tensor to handle border pixels |
| 116 | + # Calculate padding size |
| 117 | + pad_size = [size // 2 for size in filter_size for _ in range(2)] |
| 118 | + |
| 119 | + input_padded = F.pad(mask_t.float(), pad_size, mode="constant", value=pad_value) |
| 120 | + |
| 121 | + # Apply filter operation |
| 122 | + conv_fn = F.conv2d if spatial_dims == 2 else F.conv3d |
| 123 | + output = conv_fn(input_padded, structuring_element, padding=0) / torch.sum(structuring_element[0, ...]) |
| 124 | + |
| 125 | + return output |
| 126 | + |
| 127 | + |
| 128 | +def erode_t(mask_t: Tensor, filter_size: int | Sequence[int] = 3, pad_value: float = 1.0) -> Tensor: |
| 129 | + """ |
| 130 | + Erode 2D/3D binary mask with data type as torch tensor. |
| 131 | +
|
| 132 | + Args: |
| 133 | + mask_t: input 2D/3D binary mask, [N,C,M,N] or [N,C,M,N,P] torch tensor. |
| 134 | + filter_size: erosion filter size, has to be odd numbers, default to be 3. |
| 135 | + pad_value: the filled value for padding. We need to pad the input before filtering |
| 136 | + to keep the output with the same size as input. Usually use default value |
| 137 | + and not changed. |
| 138 | +
|
| 139 | + Return: |
| 140 | + Tensor: eroded mask, same shape as input. |
| 141 | + """ |
| 142 | + |
| 143 | + output = get_morphological_filter_result_t(mask_t, filter_size, pad_value) |
| 144 | + |
| 145 | + # Set output values based on the minimum value within the structuring element |
| 146 | + output = torch.where(torch.abs(output - 1.0) < 1e-7, 1.0, 0.0) |
| 147 | + |
| 148 | + return output |
| 149 | + |
| 150 | + |
| 151 | +def dilate_t(mask_t: Tensor, filter_size: int | Sequence[int] = 3, pad_value: float = 0.0) -> Tensor: |
| 152 | + """ |
| 153 | + Dilate 2D/3D binary mask with data type as torch tensor. |
| 154 | +
|
| 155 | + Args: |
| 156 | + mask_t: input 2D/3D binary mask, [N,C,M,N] or [N,C,M,N,P] torch tensor. |
| 157 | + filter_size: dilation filter size, has to be odd numbers, default to be 3. |
| 158 | + pad_value: the filled value for padding. We need to pad the input before filtering |
| 159 | + to keep the output with the same size as input. Usually use default value |
| 160 | + and not changed. |
| 161 | +
|
| 162 | + Return: |
| 163 | + Tensor: dilated mask, same shape as input. |
| 164 | + """ |
| 165 | + output = get_morphological_filter_result_t(mask_t, filter_size, pad_value) |
| 166 | + |
| 167 | + # Set output values based on the minimum value within the structuring element |
| 168 | + output = torch.where(output > 0, 1.0, 0.0) |
| 169 | + |
| 170 | + return output |
0 commit comments