|
| 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 | +import warnings |
| 13 | +from typing import Dict, Hashable, Mapping |
| 14 | + |
| 15 | +import numpy as np |
| 16 | +import torch |
| 17 | + |
| 18 | +from monai.config import KeysCollection |
| 19 | +from monai.networks.utils import pytorch_after |
| 20 | +from monai.transforms import MapTransform |
| 21 | + |
| 22 | + |
| 23 | +class EnsureSameShaped(MapTransform): |
| 24 | + """ |
| 25 | + Checks if segmentation label images (in keys) have the same spatial shape as the main image (in source_key), |
| 26 | + and raise an error if the shapes are significantly different. |
| 27 | + If the shapes are only slightly different (within an allowed_shape_difference in each dim), then resize the label using |
| 28 | + nearest interpolation. This transform is designed to correct datasets with slight label shape mismatches. |
| 29 | + Generally image and segmentation label must have the same spatial shape, however some public datasets are having slight |
| 30 | + shape mismatches, which will cause potential crashes when calculating loss or metric functions. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + keys: KeysCollection = "label", |
| 36 | + allow_missing_keys: bool = False, |
| 37 | + source_key: str = "image", |
| 38 | + allowed_shape_difference: int = 5, |
| 39 | + ) -> None: |
| 40 | + """ |
| 41 | + Args: |
| 42 | + keys: keys of the corresponding items to be compared to the source_key item shape. |
| 43 | + allow_missing_keys: do not raise exception if key is missing. |
| 44 | + source_key: key of the item with the reference shape. |
| 45 | + allowed_shape_difference: raises error if shapes are different more than this value in any dimension, |
| 46 | + otherwise corrects for the shape mismatch using nearest interpolation. |
| 47 | +
|
| 48 | + """ |
| 49 | + super().__init__(keys=keys, allow_missing_keys=allow_missing_keys) |
| 50 | + self.source_key = source_key |
| 51 | + self.allowed_shape_difference = allowed_shape_difference |
| 52 | + |
| 53 | + def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> Dict[Hashable, torch.Tensor]: |
| 54 | + d = dict(data) |
| 55 | + image_shape = d[self.source_key].shape[1:] |
| 56 | + for key in self.key_iterator(d): |
| 57 | + label_shape = d[key].shape[1:] |
| 58 | + if label_shape != image_shape: |
| 59 | + if np.allclose(list(label_shape), list(image_shape), atol=self.allowed_shape_difference): |
| 60 | + warnings.warn( |
| 61 | + f"The {key} with shape {label_shape} was resized to match the source shape {image_shape}," |
| 62 | + f"the meta-data was not updated." |
| 63 | + ) |
| 64 | + d[key] = torch.nn.functional.interpolate( |
| 65 | + input=d[key].unsqueeze(0), |
| 66 | + size=image_shape, |
| 67 | + mode="nearest-exact" if pytorch_after(1, 11) else "nearest", |
| 68 | + ).squeeze(0) |
| 69 | + else: |
| 70 | + raise ValueError(f"The {key} shape {label_shape} is different from the source shape {image_shape}.") |
| 71 | + return d |
0 commit comments