|
| 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 | +import copy |
| 15 | +from collections.abc import Sequence |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +import torch |
| 19 | + |
| 20 | +from monai.data.meta_tensor import MetaTensor |
| 21 | +from monai.utils import optional_import |
| 22 | + |
| 23 | +tqdm, _ = optional_import("tqdm", name="tqdm") |
| 24 | + |
| 25 | +__all__ = ["point_based_window_inferer"] |
| 26 | + |
| 27 | + |
| 28 | +def point_based_window_inferer( |
| 29 | + inputs: torch.Tensor | MetaTensor, |
| 30 | + roi_size: Sequence[int], |
| 31 | + predictor: torch.nn.Module, |
| 32 | + point_coords: torch.Tensor, |
| 33 | + point_labels: torch.Tensor, |
| 34 | + class_vector: torch.Tensor | None = None, |
| 35 | + prompt_class: torch.Tensor | None = None, |
| 36 | + prev_mask: torch.Tensor | MetaTensor | None = None, |
| 37 | + point_start: int = 0, |
| 38 | + center_only: bool = True, |
| 39 | + margin: int = 5, |
| 40 | + **kwargs: Any, |
| 41 | +) -> torch.Tensor: |
| 42 | + """ |
| 43 | + Point-based window inferer that takes an input image, a set of points, and a model, and returns a segmented image. |
| 44 | + The inferer algorithm crops the input image into patches that centered at the point sets, which is followed by |
| 45 | + patch inference and average output stitching, and finally returns the segmented mask. |
| 46 | +
|
| 47 | + Args: |
| 48 | + inputs: [1CHWD], input image to be processed. |
| 49 | + roi_size: the spatial window size for inferences. |
| 50 | + When its components have None or non-positives, the corresponding inputs dimension will be used. |
| 51 | + if the components of the `roi_size` are non-positive values, the transform will use the |
| 52 | + corresponding components of img size. For example, `roi_size=(32, -1)` will be adapted |
| 53 | + to `(32, 64)` if the second spatial dimension size of img is `64`. |
| 54 | + sw_batch_size: the batch size to run window slices. |
| 55 | + predictor: the model. For vista3D, the output is [B, 1, H, W, D] which needs to be transposed to [1, B, H, W, D]. |
| 56 | + Add transpose=True in kwargs for vista3d. |
| 57 | + point_coords: [B, N, 3]. Point coordinates for B foreground objects, each has N points. |
| 58 | + point_labels: [B, N]. Point labels. 0/1 means negative/positive points for regular supported or zero-shot classes. |
| 59 | + 2/3 means negative/positive points for special supported classes (e.g. tumor, vessel). |
| 60 | + class_vector: [B]. Used for class-head automatic segmentation. Can be None value. |
| 61 | + prompt_class: [B]. The same as class_vector representing the point class and inform point head about |
| 62 | + supported class or zeroshot, not used for automatic segmentation. If None, point head is default |
| 63 | + to supported class segmentation. |
| 64 | + prev_mask: [1, B, H, W, D]. The value is before sigmoid. An optional tensor of previously segmented masks. |
| 65 | + point_start: only use points starting from this number. All points before this number is used to generate |
| 66 | + prev_mask. This is used to avoid re-calculating the points in previous iterations if given prev_mask. |
| 67 | + center_only: for each point, only crop the patch centered at this point. If false, crop 3 patches for each point. |
| 68 | + margin: if center_only is false, this value is the distance between point to the patch boundary. |
| 69 | + Returns: |
| 70 | + stitched_output: [1, B, H, W, D]. The value is before sigmoid. |
| 71 | + Notice: The function only supports SINGLE OBJECT INFERENCE with B=1. |
| 72 | + """ |
| 73 | + if not point_coords.shape[0] == 1: |
| 74 | + raise ValueError("Only supports single object point click.") |
| 75 | + if not len(inputs.shape) == 5: |
| 76 | + raise ValueError("Input image should be 5D.") |
| 77 | + image, pad = _pad_previous_mask(copy.deepcopy(inputs), roi_size) |
| 78 | + point_coords = point_coords + torch.tensor([pad[-2], pad[-4], pad[-6]]).to(point_coords.device) |
| 79 | + prev_mask = _pad_previous_mask(copy.deepcopy(prev_mask), roi_size)[0] if prev_mask is not None else None |
| 80 | + stitched_output = None |
| 81 | + for p in point_coords[0][point_start:]: |
| 82 | + lx_, rx_ = _get_window_idx(p[0], roi_size[0], image.shape[-3], center_only=center_only, margin=margin) |
| 83 | + ly_, ry_ = _get_window_idx(p[1], roi_size[1], image.shape[-2], center_only=center_only, margin=margin) |
| 84 | + lz_, rz_ = _get_window_idx(p[2], roi_size[2], image.shape[-1], center_only=center_only, margin=margin) |
| 85 | + for i in range(len(lx_)): |
| 86 | + for j in range(len(ly_)): |
| 87 | + for k in range(len(lz_)): |
| 88 | + lx, rx, ly, ry, lz, rz = (lx_[i], rx_[i], ly_[j], ry_[j], lz_[k], rz_[k]) |
| 89 | + unravel_slice = [ |
| 90 | + slice(None), |
| 91 | + slice(None), |
| 92 | + slice(int(lx), int(rx)), |
| 93 | + slice(int(ly), int(ry)), |
| 94 | + slice(int(lz), int(rz)), |
| 95 | + ] |
| 96 | + batch_image = image[unravel_slice] |
| 97 | + output = predictor( |
| 98 | + batch_image, |
| 99 | + point_coords=point_coords, |
| 100 | + point_labels=point_labels, |
| 101 | + class_vector=class_vector, |
| 102 | + prompt_class=prompt_class, |
| 103 | + patch_coords=unravel_slice, |
| 104 | + prev_mask=prev_mask, |
| 105 | + **kwargs, |
| 106 | + ) |
| 107 | + if stitched_output is None: |
| 108 | + stitched_output = torch.zeros( |
| 109 | + [1, output.shape[1], image.shape[-3], image.shape[-2], image.shape[-1]], device="cpu" |
| 110 | + ) |
| 111 | + stitched_mask = torch.zeros( |
| 112 | + [1, output.shape[1], image.shape[-3], image.shape[-2], image.shape[-1]], device="cpu" |
| 113 | + ) |
| 114 | + stitched_output[unravel_slice] += output.to("cpu") |
| 115 | + stitched_mask[unravel_slice] = 1 |
| 116 | + # if stitched_mask is 0, then NaN value |
| 117 | + stitched_output = stitched_output / stitched_mask |
| 118 | + # revert padding |
| 119 | + stitched_output = stitched_output[ |
| 120 | + :, :, pad[4] : image.shape[-3] - pad[5], pad[2] : image.shape[-2] - pad[3], pad[0] : image.shape[-1] - pad[1] |
| 121 | + ] |
| 122 | + stitched_mask = stitched_mask[ |
| 123 | + :, :, pad[4] : image.shape[-3] - pad[5], pad[2] : image.shape[-2] - pad[3], pad[0] : image.shape[-1] - pad[1] |
| 124 | + ] |
| 125 | + if prev_mask is not None: |
| 126 | + prev_mask = prev_mask[ |
| 127 | + :, |
| 128 | + :, |
| 129 | + pad[4] : image.shape[-3] - pad[5], |
| 130 | + pad[2] : image.shape[-2] - pad[3], |
| 131 | + pad[0] : image.shape[-1] - pad[1], |
| 132 | + ] |
| 133 | + prev_mask = prev_mask.to("cpu") # type: ignore |
| 134 | + # for un-calculated place, use previous mask |
| 135 | + stitched_output[stitched_mask < 1] = prev_mask[stitched_mask < 1] |
| 136 | + if isinstance(inputs, torch.Tensor): |
| 137 | + inputs = MetaTensor(inputs) |
| 138 | + if not hasattr(stitched_output, "meta"): |
| 139 | + stitched_output = MetaTensor(stitched_output, affine=inputs.meta["affine"], meta=inputs.meta) |
| 140 | + return stitched_output |
| 141 | + |
| 142 | + |
| 143 | +def _get_window_idx_c(p: int, roi: int, s: int) -> tuple[int, int]: |
| 144 | + """Helper function to get the window index.""" |
| 145 | + if p - roi // 2 < 0: |
| 146 | + left, right = 0, roi |
| 147 | + elif p + roi // 2 > s: |
| 148 | + left, right = s - roi, s |
| 149 | + else: |
| 150 | + left, right = int(p) - roi // 2, int(p) + roi // 2 |
| 151 | + return left, right |
| 152 | + |
| 153 | + |
| 154 | +def _get_window_idx(p: int, roi: int, s: int, center_only: bool = True, margin: int = 5) -> tuple[list[int], list[int]]: |
| 155 | + """Get the window index.""" |
| 156 | + left, right = _get_window_idx_c(p, roi, s) |
| 157 | + if center_only: |
| 158 | + return [left], [right] |
| 159 | + left_most = max(0, p - roi + margin) |
| 160 | + right_most = min(s, p + roi - margin) |
| 161 | + left_list = [left_most, right_most - roi, left] |
| 162 | + right_list = [left_most + roi, right_most, right] |
| 163 | + return left_list, right_list |
| 164 | + |
| 165 | + |
| 166 | +def _pad_previous_mask( |
| 167 | + inputs: torch.Tensor | MetaTensor, roi_size: Sequence[int], padvalue: int = 0 |
| 168 | +) -> tuple[torch.Tensor | MetaTensor, list[int]]: |
| 169 | + """Helper function to pad inputs.""" |
| 170 | + pad_size = [] |
| 171 | + for k in range(len(inputs.shape) - 1, 1, -1): |
| 172 | + diff = max(roi_size[k - 2] - inputs.shape[k], 0) |
| 173 | + half = diff // 2 |
| 174 | + pad_size.extend([half, diff - half]) |
| 175 | + if any(pad_size): |
| 176 | + inputs = torch.nn.functional.pad(inputs, pad=pad_size, mode="constant", value=padvalue) # type: ignore |
| 177 | + return inputs, pad_size |
0 commit comments