|
| 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 typing import Callable, Sequence |
| 13 | + |
| 14 | +from lib.transforms.transforms import ConvertFromMultiChannelBasedOnBratsClassesd, GetCentroidsd, LoadDirectoryImagesd |
| 15 | +from monai.inferers import Inferer, SlidingWindowInferer |
| 16 | +from monai.transforms import ( |
| 17 | + Activationsd, |
| 18 | + AsDiscreted, |
| 19 | + EnsureChannelFirstd, |
| 20 | + EnsureTyped, |
| 21 | + KeepLargestConnectedComponentd, |
| 22 | + LoadImaged, |
| 23 | + NormalizeIntensityd, |
| 24 | + Orientationd, |
| 25 | + Spacingd, |
| 26 | +) |
| 27 | + |
| 28 | +from monailabel.interfaces.tasks.infer_v2 import InferType |
| 29 | +from monailabel.tasks.infer.basic_infer import BasicInferTask |
| 30 | +from monailabel.transform.post import Restored |
| 31 | + |
| 32 | + |
| 33 | +class Segmentation(BasicInferTask): |
| 34 | + """ |
| 35 | + Inference Engine for BraTS brain tumour segmentation using a SegResNet. |
| 36 | +
|
| 37 | + The model outputs 3 channels (TC, WT, ET) with sigmoid activations — it is |
| 38 | + a multilabel task, NOT a softmax classification. Each channel is thresholded |
| 39 | + independently at 0.5 to produce binary maps. |
| 40 | +
|
| 41 | + Two image loading modes are supported (set via ``data["multi_file"]``): |
| 42 | + - False (default): the input image is a single 4-channel NIfTI volume. |
| 43 | + - True: ``data["image"]`` is a directory containing 4 single- |
| 44 | + modality NIfTI files; LoadDirectoryImagesd stacks them. |
| 45 | + """ |
| 46 | + |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + path, |
| 50 | + network=None, |
| 51 | + target_spacing=(1.0, 1.0, 1.0), |
| 52 | + type=InferType.SEGMENTATION, |
| 53 | + labels=None, |
| 54 | + dimension=3, |
| 55 | + description="Pre-trained BraTS SegResNet — TC/WT/ET multilabel segmentation", |
| 56 | + **kwargs, |
| 57 | + ): |
| 58 | + super().__init__( |
| 59 | + path=path, |
| 60 | + network=network, |
| 61 | + type=type, |
| 62 | + labels=labels, |
| 63 | + dimension=dimension, |
| 64 | + description=description, |
| 65 | + load_strict=False, |
| 66 | + **kwargs, |
| 67 | + ) |
| 68 | + self.target_spacing = target_spacing |
| 69 | + |
| 70 | + def pre_transforms(self, data=None) -> Sequence[Callable]: |
| 71 | + """ |
| 72 | + Pre-processing pipeline matching the official MONAI BraTS tutorial. |
| 73 | +
|
| 74 | + NOTE: ScaleIntensityRangePercentilesd and CenterSpatialCropd from the |
| 75 | + original file have been removed — they are not part of the BraTS pipeline |
| 76 | + and would distort MRI intensity normalisation. NormalizeIntensityd with |
| 77 | + nonzero=True, channel_wise=True is the correct approach for multi-modal MRI. |
| 78 | + """ |
| 79 | + channels = data.get("input_channels", 4) |
| 80 | + t = [ |
| 81 | + ( |
| 82 | + LoadImaged(keys="image", reader="ITKReader", ensure_channel_first=True) |
| 83 | + if data.get("multi_file", False) is False |
| 84 | + else LoadDirectoryImagesd( |
| 85 | + keys="image", |
| 86 | + target_spacing=self.target_spacing, |
| 87 | + channels=channels, |
| 88 | + ) |
| 89 | + ), |
| 90 | + EnsureTyped(keys="image", device=data.get("device") if data else None), |
| 91 | + # EnsureChannelFirstd is safe to keep as a guard; if the channel dim is |
| 92 | + # already present (ITKReader + ensure_channel_first) it is a no-op. |
| 93 | + EnsureChannelFirstd(keys="image", channel_dim=0), |
| 94 | + Orientationd(keys="image", axcodes="RAS"), |
| 95 | + Spacingd( |
| 96 | + keys="image", |
| 97 | + pixdim=self.target_spacing, |
| 98 | + allow_missing_keys=True, |
| 99 | + ), |
| 100 | + # Channel-wise intensity normalisation on non-zero voxels only. |
| 101 | + # This matches both the tutorial and the training pipeline exactly. |
| 102 | + NormalizeIntensityd(keys="image", nonzero=True, channel_wise=True), |
| 103 | + ] |
| 104 | + return t |
| 105 | + |
| 106 | + def inferer(self, data=None) -> Inferer: |
| 107 | + return SlidingWindowInferer( |
| 108 | + roi_size=self.roi_size, |
| 109 | + sw_batch_size=2, |
| 110 | + overlap=0.4, |
| 111 | + padding_mode="replicate", |
| 112 | + mode="gaussian", |
| 113 | + ) |
| 114 | + |
| 115 | + def inverse_transforms(self, data=None): |
| 116 | + return [] |
| 117 | + |
| 118 | + def post_transforms(self, data=None) -> Sequence[Callable]: |
| 119 | + """ |
| 120 | + Post-processing for multilabel sigmoid output. |
| 121 | +
|
| 122 | + IMPORTANT differences from a softmax segmentation: |
| 123 | + - Activationsd uses sigmoid=True (not softmax=True). |
| 124 | + - AsDiscreted thresholds each channel at 0.5 independently |
| 125 | + (not argmax, because channels are not mutually exclusive). |
| 126 | + - KeepLargestConnectedComponentd is applied per-channel if available. |
| 127 | + """ |
| 128 | + t = [ |
| 129 | + EnsureTyped(keys="pred", device=data.get("device") if data else None), |
| 130 | + # Sigmoid: each of the 3 channels (TC, WT, ET) is activated independently. |
| 131 | + Activationsd(keys="pred", sigmoid=True), |
| 132 | + # Threshold each channel at 0.5 to produce binary masks. |
| 133 | + AsDiscreted(keys="pred", threshold=0.5), |
| 134 | + ] |
| 135 | + |
| 136 | + if data and data.get("largest_cc", False): |
| 137 | + # Apply per-channel so TC, WT and ET are each cleaned independently. |
| 138 | + t.append( |
| 139 | + KeepLargestConnectedComponentd( |
| 140 | + keys="pred", |
| 141 | + independent=True, # treat each channel separately |
| 142 | + ) |
| 143 | + ) |
| 144 | + |
| 145 | + t.extend( |
| 146 | + [ |
| 147 | + # Merge 3 binary channels → single-channel integer label map |
| 148 | + # Must happen before Restored so spatial metadata is applied |
| 149 | + # to the final (1, H, W, D) output, not the intermediate (3, H, W, D). |
| 150 | + ConvertFromMultiChannelBasedOnBratsClassesd(keys="pred"), |
| 151 | + Restored( |
| 152 | + keys="pred", |
| 153 | + ref_image="image", |
| 154 | + config_labels=self.labels if data.get("restore_label_idx", False) else None, |
| 155 | + ), |
| 156 | + GetCentroidsd(keys="pred", centroids_key="centroids"), |
| 157 | + ] |
| 158 | + ) |
| 159 | + return t |
0 commit comments