o  i@sdZddlmZddlZddlmZmZmZddlZ ddl Z ddl m m ZddlmZddlmZddlmZddlmZdd lmZmZmZdd lmZdd lmZdd lm Z dd l!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)ddl*m+Z+m,Z,m-Z-m.Z.m/Z/ddl0m1Z1gdZ2GdddeZ3GdddeZ4GdddeZ5GdddeZ6GdddeZ7GdddeZ8GdddeZ9Gd d!d!Z:Gd"d#d#e:eZ;Gd$d%d%e:eZGd*d+d+eZ?Gd,d-d-eZ@dS).zD A collection of "vanilla" transforms for the model output tensors. ) annotationsN)CallableIterableSequence)NdarrayOrTensor)get_track_meta) MetaTensor)one_hot)GaussianFilter apply_filterseparable_filtering)InvertibleTransform) Transform)ToTensor)convert_applied_interp_modedistance_transform_edt fill_holes$get_largest_connected_component_maskget_unique_labelsremove_small_objects) unravel_index)TransformBackendsconvert_data_typeconvert_to_tensor ensure_tuplelook_up_option)convert_to_dst_type) Activations AsDiscrete FillHolesKeepLargestConnectedComponentRemoveSmallObjects LabelFilterLabelToContour MeanEnsembleProbNMSSobelGradients VoteEnsembleInvertDistanceTransformEDTc@s6eZdZdZejgZddd d Z   ddddZdS)ra Activation operations, typically `Sigmoid` or `Softmax`. Args: sigmoid: whether to execute sigmoid function on model output before transform. Defaults to ``False``. softmax: whether to execute softmax function on model output before transform. Defaults to ``False``. other: callable function to execute other activation layers, for example: `other = lambda x: torch.tanh(x)`. Defaults to ``None``. kwargs: additional parameters to `torch.softmax` (used when ``softmax=True``). Defaults to ``dim=0``, unrecognized parameters will be ignored. Raises: TypeError: When ``other`` is not an ``Optional[Callable]``. FNsigmoidboolsoftmaxotherCallable | NonereturnNonecKsB||_||_||_|durt|stdt|jd||_dS)N&other must be None or callable but is .)r*r,kwargscallable TypeErrortype__name__r-)selfr*r,r-r3r9]/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/post/array.py__init__Rs  zActivations.__init__imgr bool | Nonec Cs|r|rtd|durt|stdt|jdt|td}t|tj tj d^}}|s2|j r7t |}|s<|j rHtj ||j ddd }|durO|jn|}|durY||}t||^}}|S) a Args: sigmoid: whether to execute sigmoid function on model output before transform. Defaults to ``self.sigmoid``. softmax: whether to execute softmax function on model output before transform. Defaults to ``self.softmax``. other: callable function to execute other activation layers, for example: `other = torch.tanh`. Defaults to ``self.other``. Raises: ValueError: When ``sigmoid=True`` and ``softmax=True``. Incompatible values. TypeError: When ``other`` is not an ``Optional[Callable]``. ValueError: When ``self.other=None`` and ``other=None``. Incompatible values. z3Incompatible values: sigmoid=True and softmax=True.Nr1r2 track_metadtypedimrrB) ValueErrorr4r5r6r7rrrtorchTensorfloatr*r,r3getr-r) r8r<r*r,r-img_t_Zact_funcoutr9r9r:__call__Zs   zActivations.__call__)FFN)r*r+r,r+r-r.r/r0)NNN) r<rr*r=r,r=r-r.r/r r7 __module__ __qualname____doc__rTORCHbackendr;rLr9r9r9r:r=s  rc@s@eZdZdZejgZ    ddddZ    ddddZdS)raX Convert the input tensor/array into discrete values, possible operations are: - `argmax`. - threshold input value to binary values. - convert input value to One-Hot format (set ``to_one_hot=N``, `N` is the number of classes). - round the value to the closest integer. Args: argmax: whether to execute argmax function on input data before transform. Defaults to ``False``. to_onehot: if not None, convert input data into the one-hot format with specified number of classes. Defaults to ``None``. threshold: if not None, threshold the float values to int number 0 or 1 with specified threshold. Defaults to ``None``. rounding: if not None, round the data according to the specified option, available options: ["torchrounding"]. kwargs: additional parameters to `torch.argmax`, `monai.networks.one_hot`. currently ``dim``, ``keepdim``, ``dtype`` are supported, unrecognized parameters will be ignored. These default to ``0``, ``True``, ``torch.float`` respectively. Example: >>> transform = AsDiscrete(argmax=True) >>> print(transform(np.array([[[0.0, 1.0]], [[2.0, 3.0]]]))) # [[[1.0, 1.0]]] >>> transform = AsDiscrete(threshold=0.6) >>> print(transform(np.array([[[0.0, 0.5], [0.8, 3.0]]]))) # [[[0.0, 0.0], [1.0, 1.0]]] >>> transform = AsDiscrete(argmax=True, to_onehot=2, threshold=0.5) >>> print(transform(np.array([[[0.0, 1.0]], [[2.0, 3.0]]]))) # [[[0.0, 0.0]], [[1.0, 1.0]]] FNargmaxr+ to_onehot int | None threshold float | Nonerounding str | Noner/r0cKs4||_t|tr td||_||_||_||_dS)NQ`to_onehot=True/False` is deprecated, please use `to_onehot=num_classes` instead.)rS isinstancer+rDrTrVrXr3)r8rSrTrVrXr3r9r9r:r;s  zAsDiscrete.__init__r<rr=cCs<t|tr tdt|td}t|tj^}}|dur|jn|}|r5tj||j dd|j ddd}|dur<|j n|}|durdt|t sQtd t |d t|||j dd|j d tjd }|durk|jn|}|duru||k}|dur||jn|}|durt|d gt|}t|||j d tjd^}}|S)a Args: img: the input tensor data to convert, if no channel dimension when converting to `One-Hot`, will automatically add it. argmax: whether to execute argmax function on input data before transform. Defaults to ``self.argmax``. to_onehot: if not None, convert input data into the one-hot format with specified number of classes. Defaults to ``self.to_onehot``. threshold: if not None, threshold the float values to int number 0 or 1 with specified threshold value. Defaults to ``self.threshold``. rounding: if not None, round the data according to the specified option, available options: ["torchrounding"]. rZr>NrBrkeepdimTrBr\z:the number of classes for One-Hot must be an integer, got r2rA) num_classesrBrAZ torchroundingr@)r[r+rDrrrrErFrSr3rHrTintr6r rGrVrXrroundr)r8r<rSrTrVrXrIrJr9r9r:rLs. $   zAsDiscrete.__call__)FNNN) rSr+rTrUrVrWrXrYr/r0)NNNN) r<rrSr=rTrUrVrWrXrYr/rrMr9r9r9r:rs% rcsDeZdZdZejejgZ     ddfdd ZdddZ Z S)r a Keeps only the largest connected component in the image. This transform can be used as a post-processing step to clean up over-segment areas in model output. The input is assumed to be a channel-first PyTorch Tensor: 1) For not OneHot format data, the values correspond to expected labels, 0 will be treated as background and the over-segment pixels will be set to 0. 2) For OneHot format data, the values should be 0, 1 on each labels, the over-segment pixels will be set to 0 in its channel. For example: Use with applied_labels=[1], is_onehot=False, connectivity=1:: [1, 0, 0] [0, 0, 0] [0, 1, 1] => [0, 1 ,1] [0, 1, 1] [0, 1, 1] Use with applied_labels=[1, 2], is_onehot=False, independent=False, connectivity=1:: [0, 0, 1, 0 ,0] [0, 0, 1, 0 ,0] [0, 2, 1, 1 ,1] [0, 2, 1, 1 ,1] [1, 2, 1, 0 ,0] => [1, 2, 1, 0 ,0] [1, 2, 0, 1 ,0] [1, 2, 0, 0 ,0] [2, 2, 0, 0 ,2] [2, 2, 0, 0 ,0] Use with applied_labels=[1, 2], is_onehot=False, independent=True, connectivity=1:: [0, 0, 1, 0 ,0] [0, 0, 1, 0 ,0] [0, 2, 1, 1 ,1] [0, 2, 1, 1 ,1] [1, 2, 1, 0 ,0] => [0, 2, 1, 0 ,0] [1, 2, 0, 1 ,0] [0, 2, 0, 0 ,0] [2, 2, 0, 0 ,2] [2, 2, 0, 0 ,0] Use with applied_labels=[1, 2], is_onehot=False, independent=False, connectivity=2:: [0, 0, 1, 0 ,0] [0, 0, 1, 0 ,0] [0, 2, 1, 1 ,1] [0, 2, 1, 1 ,1] [1, 2, 1, 0 ,0] => [1, 2, 1, 0 ,0] [1, 2, 0, 1 ,0] [1, 2, 0, 1 ,0] [2, 2, 0, 0 ,2] [2, 2, 0, 0 ,2] NTapplied_labelsSequence[int] | int | None is_onehotr= independentr+ connectivityrUnum_componentsr_r/r0cs<t|dur t|nd|_||_||_||_||_dS)a1 Args: applied_labels: Labels for applying the connected component analysis on. If given, voxels whose value is in this list will be analyzed. If `None`, all non-zero values will be analyzed. is_onehot: if `True`, treat the input data as OneHot format data, otherwise, not OneHot format data. default to None, which treats multi-channel data as OneHot and single channel data as not OneHot. independent: whether to treat ``applied_labels`` as a union of foreground labels. If ``True``, the connected component analysis will be performed on each foreground label independently and return the intersection of the largest components. If ``False``, the analysis will be performed on the union of foreground labels. default is `True`. connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If ``None``, a full connectivity of ``input.ndim`` is used. for more details: https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.label. num_components: The number of largest components to preserve. N)superr;rrbrdrerfrg)r8rbrdrerfrg __class__r9r:r;s  z&KeepLargestConnectedComponent.__init__r<rc Csz|jdur |jddkn|j}|jdur|j}n tt||dd}t|td}t|dd}|jrg|D]+}|r=||dkn|d|k}t||j |j }|rVd||||k<q3d|d||k<q3t ||ddS|st ||dd ^}} |d |k d d}t||j |j }d|d||k<t ||ddS||d fdk d}t||j |j }|D] }d||||k<qt ||ddS) z Args: img: shape must be (C, spatial_dim1[, spatial_dim2, ...]). Returns: An array with shape (C, spatial_dim1[, spatial_dim2, ...]). Nrra)discardr>FdstT)rm wrap_sequence).N.) rdshaperbtuplerrrrerrfrgrany) r8r<rdrbimg_i foregroundmasklabelsrJr9r9r:rL?s2  z&KeepLargestConnectedComponent.__call__)NNTNra) rbrcrdr=rer+rfrUrgr_r/r0r<rr/r r7rNrOrPrNUMPYCUPYrRr;rL __classcell__r9r9rir:r s +"r c@s8eZdZdZejgZ     ddddZdddZdS)r!a Use `skimage.morphology.remove_small_objects` to remove small objects from images. See: https://scikit-image.org/docs/dev/api/skimage.morphology.html#remove-small-objects. Data should be one-hotted. Args: min_size: objects smaller than this size (in number of voxels; or surface area/volume value in whatever units your image is if by_measure is True) are removed. connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If ``None``, a full connectivity of ``input.ndim`` is used. For more details refer to linked scikit-image documentation. independent_channels: Whether or not to consider channels as independent. If true, then conjoining islands from different labels will be removed if they are below the threshold. If false, the overall size islands made from all non-background voxels will be used. by_measure: Whether the specified min_size is in number of voxels. if this is True then min_size represents a surface area or volume value of whatever units your image is in (mm^3, cm^2, etc.) default is False. e.g. if min_size is 3, by_measure is True and the units of your data is mm, objects smaller than 3mm^3 are removed. pixdim: the pixdim of the input image. if a single number, this is used for all axes. If a sequence of numbers, the length of the sequence must be equal to the image dimensions. Example:: .. code-block:: python from monai.transforms import RemoveSmallObjects, Spacing, Compose from monai.data import MetaTensor data1 = torch.tensor([[[0, 0, 0, 0, 0], [0, 1, 1, 0, 1], [0, 0, 0, 1, 1]]]) affine = torch.as_tensor([[2,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]], dtype=torch.float64) data2 = MetaTensor(data1, affine=affine) # remove objects smaller than 3mm^3, input is MetaTensor trans = RemoveSmallObjects(min_size=3, by_measure=True) out = trans(data2) # remove objects smaller than 3mm^3, input is not MetaTensor trans = RemoveSmallObjects(min_size=3, by_measure=True, pixdim=(2, 1, 1)) out = trans(data1) # remove objects smaller than 3 (in pixel) trans = RemoveSmallObjects(min_size=3) out = trans(data2) # If the affine of the data is not identity, you can also add Spacing before. trans = Compose([ Spacing(pixdim=(1, 1, 1)), RemoveSmallObjects(min_size=3) ]) @raTFNmin_sizer_rfindependent_channelsr+ by_measurepixdim+Sequence[float] | float | np.ndarray | Noner/r0cCs"||_||_||_||_||_dSN)r~rfrrr)r8r~rfrrrr9r9r:r;s  zRemoveSmallObjects.__init__r<rcCst||j|j|j|j|jS)z Args: img: shape must be (C, spatial_dim1[, spatial_dim2, ...]). Data should be one-hotted. Returns: An array with shape (C, spatial_dim1[, spatial_dim2, ...]). )rr~rfrrrr8r<r9r9r:rLs zRemoveSmallObjects.__call__)r}raTFN) r~r_rfr_rr+rr+rrr/r0rx r7rNrOrPrrzrRr;rLr9r9r9r:r!es8 r!c@s0eZdZdZejejgZd ddZdd d Z d S)r"a This transform filters out labels and can be used as a processing step to view only certain labels. The list of applied labels defines which labels will be kept. Note: All labels which do not match the `applied_labels` are set to the background label (0). For example: Use LabelFilter with applied_labels=[1, 5, 9]:: [1, 2, 3] [1, 0, 0] [4, 5, 6] => [0, 5 ,0] [7, 8, 9] [0, 0, 9] rbIterable[int] | intr/r0cCst||_dS)z Initialize the LabelFilter class with the labels to filter on. Args: applied_labels: Label(s) to filter on. N)rrb)r8rbr9r9r:r;szLabelFilter.__init__r<rcCst|tjtjfst|jdt|dt|tjrct|t d}t|dd}t tdrPtj |j |j d}tt|||td|}t||dd S||}t||d }|Sttt||j |d S) aQ Filter the image on the `applied_labels`. Args: img: Pytorch tensor or numpy array of any shape. Raises: NotImplementedError: The provided image was not a Pytorch Tensor or numpy array. Returns: Pytorch tensor or numpy array of the same shape as the input. z can not handle data of type r2r>Fisindevicerlr)r[npndarrayrErFNotImplementedErrorrjr6rrhasattr as_tensorrbrwherertensortordetachcpunumpyasarray)r8r<rsZ appl_lblsrKr9r9r:rLs    "zLabelFilter.__call__N)rbrr/r0rx) r7rNrOrPrrQrzrRr;rLr9r9r9r:r"s    r"cs6eZdZdZejgZddfd d Zdd dZZ S)ra* This transform fills holes in the image and can be used to remove artifacts inside segments. An enclosed hole is defined as a background pixel/voxel which is only enclosed by a single class. The definition of enclosed can be defined with the connectivity parameter:: 1-connectivity 2-connectivity diagonal connection close-up [ ] [ ] [ ] [ ] [ ] | \ | / | <- hop 2 [ ]--[x]--[ ] [ ]--[x]--[ ] [x]--[ ] | / | \ hop 1 [ ] [ ] [ ] [ ] It is possible to define for which labels the hole filling should be applied. The input image is assumed to be a PyTorch Tensor or numpy array with shape [C, spatial_dim1[, spatial_dim2, ...]]. If C = 1, then the values correspond to expected labels. If C > 1, then a one-hot-encoding is expected where the index of C matches the label indexing. Note: The label 0 will be treated as background and the enclosed holes will be set to the neighboring class label. The performance of this method heavily depends on the number of labels. It is a bit faster if the list of `applied_labels` is provided. Limiting the number of `applied_labels` results in a big decrease in processing time. For example: Use FillHoles with default parameters:: [1, 1, 1, 2, 2, 2, 3, 3] [1, 1, 1, 2, 2, 2, 3, 3] [1, 0, 1, 2, 0, 0, 3, 0] => [1, 1 ,1, 2, 0, 0, 3, 0] [1, 1, 1, 2, 2, 2, 3, 3] [1, 1, 1, 2, 2, 2, 3, 3] The hole in label 1 is fully enclosed and therefore filled with label 1. The background label near label 2 and 3 is not fully enclosed and therefore not filled. NrbIterable[int] | int | NonerfrUr/r0cs&t|r t|nd|_||_dS)a Initialize the connectivity and limit the labels for which holes are filled. Args: applied_labels: Labels for which to fill holes. Defaults to None, that is filling holes for all labels. connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. Defaults to a full connectivity of ``input.ndim``. N)rhr;rrbrf)r8rbrfrir9r:r;!s  zFillHoles.__init__r<rcCs@t|td}t|tj^}}t||j|j}t||^}}|S)a Fill the holes in the provided image. Note: The value 0 is assumed as background label. Args: img: Pytorch Tensor or numpy array of shape [C, spatial_dim1[, spatial_dim2, ...]]. Raises: NotImplementedError: The provided image was not a Pytorch Tensor or numpy array. Returns: Pytorch Tensor or numpy array of shape [C, spatial_dim1[, spatial_dim2, ...]]. r>) rrrrrrrbrfr)r8r<img_nprJout_nprKr9r9r:rL.s zFillHoles.__call__)NN)rbrrfrUr/r0rx) r7rNrOrPrrzrRr;rLr|r9r9rir:rs ' rc@s.eZdZdZejgZddddZdd d Zd S)r#a Return the contour of binary input images that only compose of 0 and 1, with Laplacian kernel set as default for edge detection. Typical usage is to plot the edge of label or segmentation output. Args: kernel_type: the method applied to do edge detection, default is "Laplace". Raises: NotImplementedError: When ``kernel_type`` is not "Laplace". Laplace kernel_typestrr/r0cCs|dkrtd||_dS)Nrz2Currently only kernel_type="Laplace" is supported.)rr)r8rr9r9r:r;Ts zLabelToContour.__init__r<rcCst|td}t|dd}t|jd}|d}|dkr/tjgdgdgdgtjd}n|d krDd tjd d d tjd}d |d <nt |j d t ||}|j dddt |d|^}}|S)a Args: img: torch tensor data to extract the contour, with shape: [channels, height, width[, depth]] Raises: ValueError: When ``image`` ndim is not one of [3, 4]. Returns: A torch tensor with the same shape as img, note: 1. it's the binary classification result of whether a pixel is edge or not. 2. in order to keep the original shape of mask image, we use padding as default. 3. the edge detection is just approximate because it defects inherent to Laplace kernel, ideally the edge should be thin enough, but now it has a thickness. r>Frar)rororo)roror@gg:@)rararaz! can only handle 2D or 3D images.rg?)minmax)rrlenrp unsqueezerErfloat32onesrDrjr clamp_rsqueeze)r8r<rs spatial_dimskernelZ contour_imgoutputrJr9r9r:rLYs  $  zLabelToContour.__call__N)r)rrr/r0rxrMr9r9r9r:r#Es  r#c@s(eZdZed ddZed d d Zd S)Ensembler<+Sequence[NdarrayOrTensor] | NdarrayOrTensorr/ torch.TensorcCs`t|trt|dtjrdd|D}n t|tjr t|}t|tr,t|}|S|}|S)z`Get either a sequence or single instance of np.ndarray/torch.Tensor. Return single torch.Tensor.rcSsg|]}t|qSr9)rEr.0rtr9r9r: sz.Ensemble.get_stacked_torch..)r[rrrrErstack)r<rKr9r9r:get_stacked_torch|s  zEnsemble.get_stacked_torchorig_imgrcCs(t|tr |dn|}t||^}}|S)Nr)r[rr)r<rZ orig_img_rKrJr9r9r: post_convertszEnsemble.post_convertN)r<rr/r)r<rrrr/r)r7rNrO staticmethodrrr9r9r9r:rzs   rc@.eZdZdZejgZddddZdd d ZdS)r$a Execute mean ensemble on the input data. The input data can be a list or tuple of PyTorch Tensor with shape: [C[, H, W, D]], Or a single PyTorch Tensor with shape: [E, C[, H, W, D]], the `E` dimension represents the output data from different models. Typically, the input data is model output of segmentation task or classification task. And it also can support to add `weights` for the input data. Args: weights: can be a list or tuple of numbers for input data with shape: [E, C, H, W[, D]]. or a Numpy ndarray or a PyTorch Tensor data. the `weights` will be added to input data from highest dimension, for example: 1. if the `weights` only has 1 dimension, it will be added to the `E` dimension of input data. 2. if the `weights` has 2 dimensions, it will be added to `E` and `C` dimensions. it's a typical practice to add weights for different classes: to ensemble 3 segmentation model outputs, every output has 4 channels(classes), so the input data shape can be: [3, 4, H, W, D]. and add different `weights` for different classes, so the `weights` shape can be: [3, 4]. for example: `weights = [[1, 2, 3, 4], [4, 3, 2, 1], [1, 1, 1, 1]]`. Nweights(Sequence[float] | NdarrayOrTensor | Noner/r0cCs(|durtj|tjd|_dSd|_dS)Nr@)rErrGr)r8rr9r9r:r;s(zMeanEnsemble.__init__r<rrcCs||}|jdur;|j|j|_t|jj}t||jD]}|d7}q#|jj|}|||j ddd}t j |dd}| ||S)N)rarTr]rC) rrrrrqrprange ndimensionreshapemeanrEr)r8r<rsrprJrout_ptr9r9r:rLs      zMeanEnsemble.__call__r)rrr/r0r<rr/rrMr9r9r9r:r$s  r$c@r)r'af Execute vote ensemble on the input data. The input data can be a list or tuple of PyTorch Tensor with shape: [C[, H, W, D]], Or a single PyTorch Tensor with shape: [E[, C, H, W, D]], the `E` dimension represents the output data from different models. Typically, the input data is model output of segmentation task or classification task. Note: This vote transform expects the input data is discrete values. It can be multiple channels data in One-Hot format or single channel data. It will vote to select the most common data between items. The output data has the same shape as every item of the input data. Args: num_classes: if the input is single channel data instead of One-Hot, we can't get class number from channel, need to explicitly specify the number of classes to vote. Nr^rUr/r0cCs ||_dSr)r^)r8r^r9r9r:r;s zVoteEnsemble.__init__r<rrcCs||}|jdur/d}|dkr|jddkrtdn|dkr'd}t||jdd}tj| dd}|jdurFtj |d|d}nt |}| ||S)NTraz7no need to specify num_classes for One-Hot format data.FrCrr]) rr^rrpwarningswarnr rErrGrSr`r)r8r<rsZ has_ch_dimrr9r9r:rLs       zVoteEnsemble.__call__r)r^rUr/r0rrMr9r9r9r:r's  r'c@s6eZdZdZejgZ    ddddZdddZdS)r%a- Performs probability based non-maximum suppression (NMS) on the probabilities map via iteratively selecting the coordinate with highest probability and then move it as well as its surrounding values. The remove range is determined by the parameter `box_size`. If multiple coordinates have the same highest probability, only one of them will be selected. Args: spatial_dims: number of spatial dimensions of the input probabilities map. Defaults to 2. sigma: the standard deviation for gaussian filter. It could be a single value, or `spatial_dims` number of values. Defaults to 0.0. prob_threshold: the probability threshold, the function will stop searching if the highest probability is no larger than the threshold. The value should be no less than 0.0. Defaults to 0.5. box_size: the box size (in pixel) to be removed around the pixel with the maximum probability. It can be an integer that defines the size of a square or cube, or a list containing different values for each dimensions. Defaults to 48. Return: a list of selected lists, where inner lists contain probability and coordinates. For example, for 3D input, the inner lists are in the form of [probability, x, y, z]. Raises: ValueError: When ``prob_threshold`` is less than 0.0. ValueError: When ``box_size`` is a list or tuple, and its length is not equal to `spatial_dims`. ValueError: When ``box_size`` has a less than 1 value. rr?0rr_sigma?Sequence[float] | float | Sequence[torch.Tensor] | torch.Tensorprob_thresholdrGbox_sizeint | Sequence[int]r/r0cCs||_||_|jdkrt||d|_|dkrtd||_t|tr,t |g||_ nt ||kr6tdt ||_ |j dkrGtd|j d|_ |j |j |_dS)Nr)rrz*prob_threshold should be no less than 0.0.zCthe sequence length of box_size should be the same as spatial_dims.z!box_size should be larger than 0.r)rrr filterrDrr[r_rrrrr box_lower_bd box_upper_bd)r8rrrrr9r9r:r; s      zProbNMS.__init__prob_maprcs|jdkrt|tjstj|tjd}|j|j||}|j }g}| |j krt | |}|t|}t|tjrD|n|}t|tjrP|n|}||gt|||jdd||jd|tfddt|jD}d||<| |j ks+|S)zZ prob_map: the input probabilities map, it must have shape (H[, W, ...]). rr@Nc3s"|] }t||VqdSr)slicerZ idx_max_rangeZ idx_min_ranger9r: ;s z#ProbNMS.__call__..)rr[rErFrrGrrrrprrrrSrqrritemappendlistrcliprrr)r8rZprob_map_shapeoutputsmax_idxZprob_maxslicesr9rr:rL$s&     zProbNMS.__call__N)rrrr) rr_rrrrGrrr/r0)rrrr9r9r9r:r%s r%c@s6eZdZdZejgZ     ddddZddZdS)r(zV Utility transform to automatically invert the previously applied transforms. NT transformInvertibleTransform | Nonenearest_interpbool | Sequence[bool]rstr | torch.device | None post_funcr. to_tensorr/r0cCs<t|ts td||_||_||_||_||_t|_ dS)aY Args: transform: the previously applied transform. nearest_interp: whether to use `nearest` interpolation mode when inverting the spatial transforms, default to `True`. If `False`, use the same interpolation mode as the original transform. device: move the inverted results to a target device before `post_func`, default to `None`. post_func: postprocessing for the inverted result, should be a callable function. to_tensor: whether to convert the inverted data into PyTorch Tensor first, default to `True`. zAtransform is not invertible, can't invert transform for the data.N) r[r rDrrrrrr _totensor)r8rrrrrr9r9r:r;Hs  zInvert.__init__cCst|ts|S|jrt|jddd|_|}|j|}|jr*t|ts*| |}t|t j r7|j |j d}t|jrA||}|S)Nnearest) trans_infomode align_cornersr)r[rrrapplied_operationsrrinverserrrErFrrr4r)r8datainvertedr9r9r:rLbs      zInvert.__call__)NTNNT) rrrrrrrr.rrr/r0rMr9r9r9r:r(As r(csNeZdZdZejgZdddddejfdfdd Z dddZ d ddZ Z S)!r&aCalculate Sobel gradients of a grayscale image with the shape of CxH[xWxDx...] or BxH[xWxDx...]. Args: kernel_size: the size of the Sobel kernel. Defaults to 3. spatial_axes: the axes that define the direction of the gradient to be calculated. It calculate the gradient along each of the provide axis. By default it calculate the gradient for all spatial axes. normalize_kernels: if normalize the Sobel kernel to provide proper gradients. Defaults to True. normalize_gradients: if normalize the output gradient to 0 and 1. Defaults to False. padding_mode: the padding mode of the image when convolving with Sobel kernels. Defaults to `"reflect"`. Acceptable values are ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. See ``torch.nn.Conv1d()`` for more information. dtype: kernel data type (torch.dtype). Defaults to `torch.float32`. rNTFreflect kernel_sizer_ spatial_axesrcnormalize_kernelsr+normalize_gradients padding_moderrA torch.dtyper/r0cs:t||_||_||_||_|||\|_|_dSr) rhr;paddingrrr _get_kernel kernel_diff kernel_smooth)r8rrrrrrArir9r:r;s zSobelGradients.__init__!tuple[torch.Tensor, torch.Tensor]cCs|dkr td|d|ddkrtd|dtjgdgg|d}tjgd gg|d}tjgd gg|d}|jrU|jsItd |d|d }|d }|d }|dd}t|D]}tj||dd }tj||dd }q_||fS)Nrz,Sobel kernel size should be at least three. z was given.rrz+Sobel kernel size should be an odd number. )rorrar@)rarrazQ`dtype` for Sobel kernel should be floating point when `normalize_kernel==True`. g@g@)r) rDrErris_floating_pointrFconv1dr)r8sizerArrZkernel_expansionexpandrJr9r9r:rs(    zSobelGradients._get_kernelimagerrcsZt|td}|jdtttt d}|jdur&tt}n'tt|jt|}|rAtd|dd|dfdd t|jD}| d}|j |j }|j |j }g}|D]5} |g} || | <t|| |jd } |jr| } | | kr| | 8} | } | dkr| | } || qdtj|dd }t|d|d}|S) Nr>rarz5The provide axes to calculate gradient is not valid: z. The image has z% spatial dimensions so it should be: r2cs g|] }|dkr |n|qS)rr9)raxn_spatial_dimsr9r:rs z+SobelGradients.__call__..)rrC)rrndimrrrsetrrDrrrrrr rrrrrrEcatrr)r8rZ image_tensorZvalid_spatial_axesrZ invalid_axisrrZ grad_listrkernelsgradZgrad_minZgrad_maxgradsr9rr:rLsD      zSobelGradients.__call__)rr_rrcrr+rr+rrrArr/r0)r/r)rrr/r) r7rNrOrPrrQrRrErr;rrLr|r9r9rir:r&vs r&cs:eZdZdZejejgZd dfdd Zdd d Z Z S)r)a Applies the Euclidean distance transform on the input. Either GPU based with CuPy / cuCIM or CPU based with scipy. To use the GPU implementation, make sure cuCIM is available and that the data is a `torch.tensor` on a GPU device. Note that the results of the libraries can differ, so stick to one if possible. For details, check out the `SciPy`_ and `cuCIM`_ documentation and / or :func:`monai.transforms.utils.distance_transform_edt`. .. _SciPy: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.distance_transform_edt.html .. _cuCIM: https://docs.rapids.ai/api/cucim/nightly/api/#cucim.core.operations.morphology.distance_transform_edt NsamplingNone | float | list[float]r/r0cst||_dSr)rhr;r)r8rrir9r:r;s  zDistanceTransformEDT.__init__r<rcCst||jdS)aA Args: img: Input image on which the distance transform shall be run. Has to be a channel first array, must have shape: (num_channels, H, W [,D]). Can be of any type but will be converted into binary: 1 wherever image equates to True, 0 elsewhere. Input gets passed channel-wise to the distance-transform, thus results from this function will differ from directly calling ``distance_transform_edt()`` in CuPy or SciPy. sampling: Spacing of elements along each dimension. If a sequence, must be of length equal to the input rank -1; if a single number, this is used for all axes. If not specified, a grid spacing of unity is implied. Returns: An array with the same shape and data type as img )r<r)rrrr9r9r:rLszDistanceTransformEDT.__call__r)rrr/r0rxryr9r9rir:r)s  r))ArP __future__rrcollections.abcrrrrrrEtorch.nn.functionalnn functionalrmonai.config.type_definitionsrmonai.data.meta_objrmonai.data.meta_tensorrmonai.networksr monai.networks.layersr r r monai.transforms.inverser monai.transforms.transformrmonai.transforms.utility.arrayrmonai.transforms.utilsrrrrrr0monai.transforms.utils_pytorch_numpy_unificationr monai.utilsrrrrrmonai.utils.type_conversionr__all__rrr r!r"rr#rr$r'r%r(r&r)r9r9r9r:sD           GkvX:N5+1X5n