U Ph#@sdZddlmZddlZddlmZmZddlmZddl m Z ddl m Z ddl ZddlZddlmZdd lmZdd lmZdd lmZdd lmZmZdd lmZmZddlmZm Z ddl!m"Z"ddl#m$Z$m%Z%m&Z&ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ddl0m1Z2ddl0m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?ddddddddddddd d!d"d#d$gZ@Gd%ddee$ZAGd&ddeAZBGd'ddeAZCGd(ddeAZDGd)ddee$ZEGd*ddeEZFGd+ddeEZGGd,ddeEZHGd-dde%eEZIGd.ddeIZJGd/dde%e e$e"ZKGd0ddeEZLGd1d d e%e e$e"ZMGd2d!d!e%e e$e"ZNGd3d"d"e%e e$e"ZOGd4d#d#ee$ZPGd5d$d$e&ZQdS)6zC A collection of "vanilla" transforms for crop and pad operations. ) annotationsN)CallableSequence)chainceil)Any)IndexSelection)NdarrayOrTensor)get_track_meta) MetaTensor)get_random_patchget_valid_patch_size) crop_funcpad_func)InvertibleTransformTraceableTransform)MultiSampleTrait) LazyTransform Randomizable Transform)compute_divisible_spatial_size#generate_label_classes_crop_centers#generate_pos_neg_label_crop_centersgenerate_spatial_bounding_box is_positivemap_binary_to_indicesmap_classes_to_indicesweighted_patch_samples) ImageMetaKey) LazyAttrMethodPytorchPadMode TraceKeysTransformBackendsconvert_data_typeconvert_to_tensordeprecated_arg_default ensure_tupleensure_tuple_repfall_back_tuplelook_up_option pytorch_afterPad SpatialPad BorderPad DivisiblePadCrop SpatialCropCenterSpatialCropCenterScaleCropRandSpatialCrop RandScaleCropRandSpatialCropSamplesCropForegroundRandWeightedCropRandCropByPosNegLabelRandCropByLabelClassesResizeWithPadOrCrop BoundingRectc@sreZdZdZejejgZdej dfdddddd d Z d d d ddZ dddddddddZ dddddZ dS)r-a Perform padding for a given an amount of padding in each dimension. `torch.nn.functional.pad` is used unless the mode or kwargs are not available in torch, in which case `np.pad` will be used. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: to_pad: the amount to pad in each dimension (including the channel) [(low_H, high_H), (low_W, high_W), ...]. if None, must provide in the `__call__` at runtime. mode: available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html requires pytorch >= 1.10 for best compatibility. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. NFztuple[tuple[int, int]] | NonestrboolNone)to_padmodelazyreturncKs"t||||_||_||_dSN)r__init__rArBkwargs)selfrArBrCrGrIS/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/croppad/array.pyrFos z Pad.__init__ Sequence[int]tuple[tuple[int, int]] spatial_shaperDcCstd|jjddS)z dynamically compute the pad width according to the spatial shape. the output is the amount of padding for all dimensions including the channel. Args: spatial_shape: spatial shape of the original image. z subclass z must implement this method.N)NotImplementedError __class____name__)rHrNrIrIrJcompute_pad_width{s zPad.compute_pad_width torch.Tensor str | None bool | None)imgrArBrCrDc Ks|dkr|jn|}|dkrDt|tr,|n |jdd}||}|dkrR|jn|}t|j} | |t |t d} |dkr|j n|} t | |||| f| S)as Args: img: data to be transformed, assuming `img` is channel-first and padding doesn't apply to the channel dim. to_pad: the amount to be padded in each dimension [(low_H, high_H), (low_W, high_W), ...]. default to `self.to_pad`. mode: available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html lazy: a flag to override the lazy behaviour for this call, if set. Defaults to None. kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Ndata track_meta)rA isinstancer peek_pending_shapeshaperRrBdictrGupdater&r rCrget_transform_info) rHrVrArBrCrGZto_pad_rNZmode_kwargs_img_tlazy_rIrIrJ__call__s    z Pad.__call__r rYrDc Cs||}|tjd}|dddks8|dddkrx|dd}tt|dd|dt|}||t||}dd|ddD}ddt|jdd|ddD}t||d}| d||W5QRSQRXdS) NpaddedrrWcSsg|] }|dqSrrI.0irIrIrJ szPad.inverse..cSsg|]\}}||dqS)rWrIrirjjrIrIrJrks roi_startroi_endF) pop_transformr# EXTRA_INFOminmaxlenzipr]r2trace_transform) rHrY transformrfserorpcropperrIrIrJinverses    &  z Pad.inverse)NNN)rQ __module__ __qualname____doc__r$TORCHNUMPYbackendr"CONSTANTrFrRrdr|rIrIrIrJr-Ss  $csJeZdZdZejejdfddddddfdd Zd d d d dZ Z S)r.a Performs padding to the data, symmetric for all sides or all on one side for each dimension. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_size: the spatial size of output data after padding, if a dimension of the input data size is larger than the pad size, will not pad that dimension. If its components have non-positive values, the corresponding size of input image will be used (no padding). for example: if the spatial size of input data is [30, 30, 30] and `spatial_size=[32, 25, -1]`, the spatial size of output data will be [32, 30, 30]. method: {``"symmetric"``, ``"end"``} Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``. mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Fz7Sequence[int] | int | tuple[tuple[int, ...] | int, ...]r>r?r@) spatial_sizemethodrBrCrDc s.||_t|t|_tjf||d|dSNrBrC)rr+r!rsuperrF)rHrrrBrCrGrPrIrJrFs zSpatialPad.__init__rKrLrMcst|j}|jtjkrdg}t|D]<\}}t||d}|t|dt||dfq$nfddt|D}t dg|S)z dynamically compute the pad width according to the spatial shape. Args: spatial_shape: spatial shape of the original image. rcs*g|]"\}}dtt||dfqSrg)intrt)rirjsp_irNrIrJrksz0SpatialPad.compute_pad_width..rr) r*rrr! SYMMETRIC enumeratertappendrtuple)rHrNr pad_widthrjrwidthrIrrJrRs  &zSpatialPad.compute_pad_width) rQr}r~rr!rr"rrFrR __classcell__rIrIrrJr.s  csDeZdZdZejdfdddddfdd Zd d d d dZZS)r/a Pad the input data by adding specified borders to every dimension. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_border: specified size for every spatial border. Any -ve values will be set to 0. It can be 3 shapes: - single int number, pad all the borders with the same size. - length equals the length of image shape, pad every spatial dimension separately. for example, image shape(CHW) is [1, 4, 4], spatial_border is [2, 1], pad every border of H dim with 2, pad every border of W dim with 1, result shape is [1, 8, 6]. - length equals 2 x (length of image shape), pad every border of every dimension separately. for example, image shape(CHW) is [1, 4, 4], spatial_border is [1, 2, 3, 4], pad top of H dim with 1, pad bottom of H dim with 2, pad left of W dim with 3, pad right of W dim with 4. the result shape is [1, 7, 11]. mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. FSequence[int] | intr>r?r@)spatial_borderrBrCrDc s"||_tjf||d|dSr)rrrF)rHrrBrCrGrrIrJrFszBorderPad.__init__rKrLrMc st|jtddDs,tddtddDtdkr^fdd|D}ntt|krd ddt|D}n\tt|d krfd dtt|D}n,td td t|dd t|dtdg|S)Ncss|]}t|tVqdSrE)r[rribrIrIrJ sz.BorderPad.compute_pad_width..z0self.spatial_border must contain only ints, got .css|]}td|VqdS)rN)rtrrIrIrJrsrWcs$g|]}tdtdfqSrgr)ri_rrIrJrksz/BorderPad.compute_pad_width..cSsg|]}t|t|fqSrIr)risprIrIrJrksrcs0g|](}td|td|dfqS)rrWrrhrrIrJrk!sz#Unsupported spatial_border length: z/, available options are [1, len(spatial_shape)=z, 2*len(spatial_shape)=z].r)r(rall ValueErrorrrurange)rHrNZdata_pad_widthrIrrJrRs     &zBorderPad.compute_pad_width) rQr}r~rr"rrFrRrrIrIrrJr/s csPeZdZdZejZejej dfddddddfdd Z d d d d dZ Z S)r0z Pad the input data, so that the spatial sizes are divisible by `k`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Frr>r?r@)krBrrCrDc s,||_t||_tjf||d|dS)aS Args: k: the target k for each spatial dimension. if `k` is negative or 0, the original size is preserved. if `k` is an int, the same `k` be applied to all the input spatial dimensions. mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html method: {``"symmetric"``, ``"end"``} Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. See also :py:class:`monai.transforms.SpatialPad` rN)rr!rrrF)rHrrBrrCrGrrIrJrF6s zDivisiblePad.__init__rKrLrMcCs&t||jd}t||jd}||S)N)rNr)rr)rrr.rrR)rHrNnew_sizeZ spatial_padrIrIrJrRUszDivisiblePad.compute_pad_width) rQr}r~rr.rr"rr!rrFrRrrIrIrrJr0,sc @sleZdZdZejgZdddddZedddddd d d d d Z ddddddddZ dddddZ dS)r1a+ Perform crop operations on the input image. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Fr?rCcCst||dSrE)rrF)rHrCrIrIrJrFhsz Crop.__init__N&Sequence[int] | NdarrayOrTensor | NoneSequence[slice] | None tuple[slice]) roi_centerroi_sizerorp roi_slicesrDc Cs\|r.tdd|Ds&td|dt|S|dk r|dk rt|tjddd}t|tjddd}t|}td d rtj|d d d n t |d }t |||} t | || } nV|dks|dkrtdt|tjdd} t | t| } t|tjdd} t | | } | d kr8tt t | t | gStddt| | DSdS)a~ Compute the crop slices based on specified `center & size` or `start & end` or `slices`. Args: roi_center: voxel coordinates for center of the crop ROI. roi_size: size of the crop ROI, if a dimension of ROI size is larger than image size, will not crop that dimension of the image. roi_start: voxel coordinates for start of the crop ROI. roi_end: voxel coordinates for end of the crop ROI, if a coordinate is out of image, use the end coordinate of image. roi_slices: list of slices for each of the spatial dimensions. css"|]}|jdkp|jdkVqdS)NrW)step)riryrIrIrJrsz&Crop.compute_slices..z8only slice steps of 1/None are currently supported, got rNTcpu)rYdtype wrap_sequencedevicerWrfloor) rounding_modezAplease specify either roi_center, roi_size or roi_start, roi_end.)rYrrcSs"g|]\}}tt|t|qSrI)slicer)riryrzrIrIrJrksz'Crop.compute_slices..)rrr(r&torchint16 zeros_liker,divide floor_dividemaximumnumelrritemrvtolist) rrrorprZ roi_center_tZ roi_size_t_zeroshalf roi_start_t roi_end_trIrIrJcompute_slicesks.    zCrop.compute_slicesrSztuple[slice, ...]rU)rVslicesrCrDcCst|}tt|tr|n |jdd}t||krR|tdg|t|7}ttdg|d|}t|td}|dkr|j n|}t |t ||| S) Apply the transform to `img`, assuming `img` is channel-first and slicing doesn't apply to the channel dim. rWNrX) listrur[r r\r]rr&r rCrrr`)rHrVrrCZslices_sdrbrcrIrIrJrds$ z Crop.__call__r rVrDc CsJ||}|tjd}t|}|d||W5QRSQRXdS)NcroppedF)rqr#rrr/rw)rHrVrxrinverse_transformrIrIrJr|s   z Crop.inverse)F)NNNNN)N) rQr}r~rr$rrrF staticmethodrrdr|rIrIrIrJr1[s 3c sLeZdZdZdddddddddfd d Zdd d d d fdd ZZS)r2a  General purpose cropper to produce sub-volume region of interest (ROI). If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped results of several images may not have exactly the same shape. It can support to crop ND spatial (channel-first) data. The cropped region can be parameterised in various ways: - a list of slices for each spatial dimension (allows for use of negative indexing and `None`) - a spatial center and size - the start and end coordinates of the ROI This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NFrrr?r@)rrrorprrCrDcs&t||j|||||d|_dS)a Args: roi_center: voxel coordinates for center of the crop ROI. roi_size: size of the crop ROI, if a dimension of ROI size is larger than image size, will not crop that dimension of the image. roi_start: voxel coordinates for start of the crop ROI. roi_end: voxel coordinates for end of the crop ROI, if a coordinate is out of image, use the end coordinate of image. roi_slices: list of slices for each of the spatial dimensions. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. )rrrorprN)rrFrr)rHrrrorprrCrrIrJrFs zSpatialCrop.__init__rSrUrVrCrDcs*|dkr|jn|}tj|t|j|dS)rNrVrrC)rCrrdr(rrHrVrCrcrrIrJrdszSpatialCrop.__call__)NNNNNF)NrQr}r~rrFrdrrIrIrrJr2s csXeZdZdZdddddfdd Zd d d fd d Zdddddfdd ZZS)r3a Crop at the center of image with specified ROI size. If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped results of several images may not have exactly the same shape. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: roi_size: the spatial size of the crop region e.g. [224,224,128] if a dimension of ROI size is larger than image size, will not crop that dimension of the image. If its components have non-positive values, the corresponding size of input image will be used. for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`, the spatial size of output data will be [32, 40, 40]. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Frr?r@)rrCrDcstj|d||_dSNr)rrFr)rHrrCrrIrJrFszCenterSpatialCrop.__init__rKr)rrDcs*t|j|}dd|D}tj||dS)NcSsg|] }|dqS)rrIrhrIrIrJrk sz4CenterSpatialCrop.compute_slices..)rr)r*rrr)rHrrrrrIrJrs z CenterSpatialCrop.compute_slicesNrSrUrcsF|dkr|jn|}tj||t|tr0|n |jdd|dS)rNrWr)rCrrdrr[r r\r]rrrIrJrd s $zCenterSpatialCrop.__call__)F)N)rQr}r~rrFrrdrrIrIrrJr3scsBeZdZdZddddfdd Zdd d d d fd d ZZS)r4a% Crop at the center of image with specified scale of ROI size. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: roi_scale: specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5] or a number for all dims. If its components have non-positive values, will use `1.0` instead, which means the input image size. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. FSequence[float] | floatr?) roi_scalerCcstj|d||_dSr)rrFr)rHrrCrrIrJrF'szCenterScaleCrop.__init__NrSrUrcszt|tr|n |jdd}t|}ddtt|j||D}|dkrR|jn|}t ||d}t j || ||dS)NrWcSsg|]\}}t||qSrIrrirryrIrIrJrk.sz,CenterScaleCrop.__call__..rrCr) r[r r\r]rurvr)rrCr3rrdr)rHrVrCimg_sizendimrrcr{rrIrJrd+s   zCenterScaleCrop.__call__)F)NrrIrIrrJr4s cs\eZdZdZdddddddd fd d Zd dd ddZddddddfdd ZZS)r5aQ Crop image with random size or specific size ROI. It can crop at a random position as center or at the image center. And allows to set the minimum and maximum size to limit the randomly generated ROI. Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size, will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped results of several images may not have exactly the same shape. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: roi_size: if `random_size` is True, it specifies the minimum crop region. if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128] if a dimension of ROI size is larger than image size, will not crop that dimension of the image. If its components have non-positive values, the corresponding size of input image will be used. for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`, the spatial size of output data will be [32, 40, 40]. max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size` can specify the max crop region size. if None, defaults to the input image size. if its components have non-positive values, the corresponding size of input image will be used. random_center: crop at random position as center or the image center. random_size: crop with random size or specific size ROI. if True, the actual size is sampled from `randint(roi_size, max_roi_size + 1)`. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. NTFrSequence[int] | int | Noner?r@)r max_roi_size random_center random_sizerCrDcs2t|||_||_||_||_d|_|dSrE)rrFrrrr_size)rHrrrrrCrrIrJrFPs zRandSpatialCrop.__init__rKrrDcstj|_jrjdkr"|n tj|tddtjDr`tdjddtfddt t |D_j rt |j}t ||j_dS)Ncss|]\}}||kVqdSrErIrlrIrIrJrdsz,RandSpatialCrop.randomize..zmin ROI size: z is larger than max ROI size: rc3s,|]$}jjj||ddVqdS)rW)lowhighN)Rrandintrrhmax_sizerHrIrJrfs)r*rrrranyrvrrrrurrr r_slices)rHrZ valid_sizerIrrJ randomize`s" zRandSpatialCrop.randomizerSrUrVrrCrDcst|tr|n |jdd}|r.|||jdkr@td|dkrN|jn|}|jrlt j ||j |dSt |j|d}t j || ||dS)rrWNzself._size not specified.rr)r[r r\r]rr RuntimeErrorrCrrrdrr3r)rHrVrrCrrcr{rrIrJrdks   zRandSpatialCrop.__call__)NTFF)TN)rQr}r~rrFrrdrrIrIrrJr54s csheZdZdZdddddddd fd d Zd d Zdddfdd Zddddddfdd ZZS)r6a5 Subclass of :py:class:`monai.transforms.RandSpatialCrop`. Crop image with random size or specific size ROI. It can crop at a random position as center or at the image center. And allows to set the minimum and maximum scale of image size to limit the randomly generated ROI. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: roi_scale: if `random_size` is True, it specifies the minimum crop size: `roi_scale * image spatial size`. if `random_size` is False, it specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5]. If its components have non-positive values, will use `1.0` instead, which means the input image size. max_roi_scale: if `random_size` is True and `roi_scale` specifies the min crop region size, `max_roi_scale` can specify the max crop region size: `max_roi_scale * image spatial size`. if None, defaults to the input image size. if its components have non-positive values, will use `1.0` instead, which means the input image size. random_center: crop at random position as center or the image center. random_size: crop with random size or specified size ROI by `roi_scale * image spatial size`. if True, the actual size is sampled from `randint(roi_scale * image spatial size, max_roi_scale * image spatial size + 1)`. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. NTFrzSequence[float] | float | Noner?r@)r max_roi_scalerrrCrDcs&tjdd|||d||_||_dS)N)rrrrrC)rrFrr)rHrrrrrCrrIrJrFszRandScaleCrop.__init__cCsZt|}ddtt|j||D|_|jdk rPddtt|j||D|_nd|_dS)NcSsg|]\}}t||qSrIrrrIrIrJrksz2RandScaleCrop.get_max_roi_size..cSsg|]\}}t||qSrIrrrIrIrJrks)rurvr)rrrr)rHrrrIrIrJget_max_roi_sizes   zRandScaleCrop.get_max_roi_sizerKrcs||t|dSrE)rrr)rHrrrIrJrs zRandScaleCrop.randomizerSrUrcsJ|t|tr|n |jdd|dkr4|jn|}tj|||dS)rrWN)rVrrC)rr[r r\r]rCrrd)rHrVrrCrcrrIrJrds&zRandScaleCrop.__call__)NTFF)TN) rQr}r~rrFrrrdrrIrIrrJr6}sc seZdZdZejZdddddddd d d d Zd d dddfdd Zej j dd dddZ d!dd dddZ d"ddddddZ Z S)#r7a  Crop image with random size or specific size ROI to generate a list of N samples. It can crop at a random position as center or at the image center. And allows to set the minimum size to limit the randomly generated ROI. It will return a list of cropped images. Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size, will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped results of several images may not have exactly the same shape. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: roi_size: if `random_size` is True, it specifies the minimum crop region. if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128] if a dimension of ROI size is larger than image size, will not crop that dimension of the image. If its components have non-positive values, the corresponding size of input image will be used. for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`, the spatial size of output data will be [32, 40, 40]. num_samples: number of samples (crop regions) to take in the returned list. max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size` can specify the max crop region size. if None, defaults to the input image size. if its components have non-positive values, the corresponding size of input image will be used. random_center: crop at random position as center or the image center. random_size: crop with random size or specific size ROI. The actual size is sampled from `randint(roi_size, img_size)`. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Raises: ValueError: When ``num_samples`` is nonpositive. NTFrrrr?r@)r num_samplesrrrrCrDcCs@t|||dkr$td|d||_t||||||_dS)NrWz"num_samples must be positive, got r)rrFrrr5r{)rHrrrrrrCrIrIrJrFs zRandSpatialCropSamples.__init__ int | Noneznp.random.RandomState | None)seedstaterDcs t|||j|||SrE)rset_random_stater{)rHrrrrIrJrsz'RandSpatialCropSamples.set_random_state)valuerDcCs||_||j_dSrE)_lazyr{rC)rHrrIrIrJrCszRandSpatialCropSamples.lazyz Any | NonerecCsdSrErI)rHrYrIrIrJrsz RandSpatialCropSamples.randomizerSrUlist[torch.Tensor]rcCsdg}|dkr|jn|}t|jD]>}|j||d}trT||jtj<|j|d|d| |q |S)z Apply the transform to `img`, assuming `img` is channel-first and cropping doesn't change the channel dim. NrTreplacerC) rCrrr{r metaKey PATCH_INDEXpush_transformr)rHrVrCretrcrjrrIrIrJrds  zRandSpatialCropSamples.__call__)NTFF)NN)N)N)rQr}r~rr5rrFrrrCsetterrrdrrIrIrrJr7s"c seZdZdZeddddddedd ddd ejdfd d d ddd dddd ddZe j j ddddZ e ddZ dddddZd*ddddddd fd!d" Zd+ddd#dd$d%d&Zd'd'dfd(d) ZZS),r8a Crop an image using a bounding box. The bounding box is generated by selecting foreground using select_fn at channels channel_indices. margin is added in each spatial dimension of the bounding box. The typical usage is to help training and evaluation if the valid part is small in the whole medical image. Users can define arbitrary function to select expected foreground from the whole image or specified channels. And it can also add margin to every dim of the bounding box of foreground object. For example: .. code-block:: python image = np.array( [[[0, 0, 0, 0, 0], [0, 1, 2, 1, 0], [0, 1, 3, 2, 0], [0, 1, 2, 1, 0], [0, 0, 0, 0, 0]]]) # 1x5x5, single channel 5x5 image def threshold_at_one(x): # threshold at 1 return x > 1 cropper = CropForeground(select_fn=threshold_at_one, margin=0) print(cropper(image)) [[[2, 1], [3, 2], [2, 1]]] This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. allow_smallerTFz1.2z1.5) old_default new_defaultsincereplacedNrrWrzIndexSelection | Nonerr?r>r@) select_fnchannel_indicesmarginr return_coords k_divisiblerBrCrDc KsZt||||_|dk r"t|nd|_||_||_||_||_t f||d| |_ dS)a Args: select_fn: function to select expected foreground, default is to select values > 0. channel_indices: if defined, select foreground only on the specified channels of image. if None, select foreground on the whole image. margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims. allow_smaller: when computing box size with `margin`, whether to allow the image edges to be smaller than the final box edges. If `False`, part of a padded output box might be outside of the original image, if `True`, the image edges will be used as the box edges. Default to `True`. return_coords: whether return the coordinates of spatial bounding box for foreground. k_divisible: make each spatial dimension to be divisible by k, default to 1. if `k_divisible` is an int, the same `k` be applied to all the input spatial dimensions. mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Nr) rrFrr(rrrrrr-padder) rHrrrrrrrBrC pad_kwargsrIrIrJrF1s$ zCropForeground.__init___valcCs||_||j_dSrE)rrrCrHrrIrIrJrC^szCropForeground.lazycCsdSNFrIrHrIrIrJrequires_current_datacsz$CropForeground.requires_current_datarSztuple[np.ndarray, np.ndarray]rc Cst||j|j|j|j\}}t|tjtjdd^}}t|tjtjdd^}}||}t t | |j d}|t t ||d}||}||fS)z Compute the start points and end points of bounding box to crop. And adjust bounding box coords to be divisible by `k`. T) output_typerr)rr)rrrrrr%npndarrayrasarrayrrrr) rHrV box_startbox_endZ box_start_rZbox_end_Zorig_spatial_sizerrIrIrJcompute_bounding_boxgsz#CropForeground.compute_bounding_box np.ndarrayrT)rVrrrBrCrDc sT|j||d}tj|||d}t| d} t|tt|trJ|n |j ddd} t t t | | } t| dt|tr|n |j dd} |jjf|| ||d|} trPt| trP|s| j| jdtjd <nZ| j}| j}|tj}||d <|j| |tj|tj|tj|tj||d | S) z: Crop and pad based on the bounding box. rnrrrWNr)rVrArBrCrpad_info) orig_sizesp_sizeaffinerC extra_info)rrrdrrrr[r r\r]rrrvrr/rRrr applied_operationspopr#rrpending_operationsrget ORIG_SIZEr SHAPEAFFINE)rHrVrrrBrCrrrZ pad_to_startZ pad_to_endpadrrr crop_infoextrarrIrJcrop_padzs8 (     zCropForeground.crop_padrUrVrBrCrDc KsP||\}}|dkr|jn|}|j||||fd|i|}|jrL|||fS|S)z Apply the transform to `img`, assuming `img` is channel-first and slicing doesn't change the channel dim. NrC)rrCr$r) rHrVrBrCrrrrcrrIrIrJrds  zCropForeground.__call__r cs>||}|tjd}|j||j|}t|S)Nr) get_most_recent_transformr#rrrrrrr|r)rHrVrxrinvrrIrJr|s    zCropForeground.inverse)NF)NN)rQr}r~rr'rr"rrFr1rCrpropertyr rr$rdr|rrIrIrrJr8s."", -c@sjeZdZdZejZdddddd d d Zd d dddZej j ddddZ dddddddddZ dS)r9a Samples a list of `num_samples` image patches according to the provided `weight_map`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_size: the spatial size of the image patch e.g. [224, 224, 128]. If its components have non-positive values, the corresponding size of `img` will be used. num_samples: number of samples (image patches) to take in the returned list. weight_map: weight map used to generate patch samples. The weights must be non-negative. Each element denotes a sampling weight of the spatial location. 0 indicates no sampling. It should be a single-channel array in shape, for example, `(1, spatial_dim_0, spatial_dim_1, ...)`. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. rWNFrrNdarrayOrTensor | Noner?)rr weight_maprCcCs0t||t||_t||_||_g|_dSrE)rrFr(rrrr*centers)rHrrr*rCrIrIrJrFs    zRandWeightedCrop.__init__r r@)r*rDcCs t|j|d|j|jd|_dS)Nr)rw n_samplesZr_state)rrrrr+)rHr*rIrIrJrs zRandWeightedCrop.randomizercCs ||_dSrErr rIrIrJrCszRandWeightedCrop.lazyTrSrUr)rVr*rrCrDcCst|tr|n |jdd}|r|dkr2|j}|dkrBtdt|trT|n |jdd}||krtd|d|d||t |j |}g}|dkr|j n|} t |j D]Z\} } t| || d} | |} tr| }| |jtj<| |jd<|j|d | d || q|S) a Args: img: input image to sample patches from. assuming `img` is a channel-first array. weight_map: weight map used to generate patch samples. The weights must be non-negative. Each element denotes a sampling weight of the spatial location. 0 indicates no sampling. It should be a single-channel array in shape, for example, `(1, spatial_dim_0, spatial_dim_1, ...)` randomize: whether to execute random operations, default to `True`. lazy: a flag to override the lazy behaviour for this call, if set. Defaults to None. Returns: A list of image patches rWNz8weight map must be provided for weighted patch sampling.z-image and weight map spatial shape mismatch: z vs rrrrC crop_centerTr)r[r r\r]r*rwarningswarnrr*rrCrr+r2r rrrrr)rHrVr*rrC img_shapeZw_shapeZ _spatial_sizeresultsrcrjcenterr{rret_rIrIrJrds.       zRandWeightedCrop.__call__)rWNF)NTN) rQr}r~rr2rrFrrrCrrdrIrIrIrJr9s c@seZdZdZejZd ddd d d dd d d d d d d ddZd!dd d dd dddZej j d dddZ e ddZ d"dddd d d dddddZ dS)#r:aL Crop random fixed sized regions with the center being a foreground or background voxel based on the Pos Neg Ratio. And will return a list of arrays for all the cropped images. For example, crop two (3 x 3) arrays from (5 x 5) array with pos/neg=1:: [[[0, 0, 0, 0, 0], [0, 1, 2, 1, 0], [[0, 1, 2], [[2, 1, 0], [0, 1, 3, 0, 0], --> [0, 1, 3], [3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0]] [0, 0, 0]] [0, 0, 0, 0, 0]]] If a dimension of the expected spatial size is larger than the input image size, will not crop that dimension. So the cropped result may be smaller than expected size, and the cropped results of several images may not have exactly same shape. And if the crop ROI is partly out of the image, will automatically adjust the crop center to ensure the valid crop ROI. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_size: the spatial size of the crop region e.g. [224, 224, 128]. if a dimension of ROI size is larger than image size, will not crop that dimension of the image. if its components have non-positive values, the corresponding size of `label` will be used. for example: if the spatial size of input data is [40, 40, 40] and `spatial_size=[32, 64, -1]`, the spatial size of output data will be [32, 40, 40]. label: the label image that is used for finding foreground/background, if None, must set at `self.__call__`. Non-zero indicates foreground, zero indicates background. pos: used with `neg` together to calculate the ratio ``pos / (pos + neg)`` for the probability to pick a foreground voxel as a center rather than a background voxel. neg: used with `pos` together to calculate the ratio ``pos / (pos + neg)`` for the probability to pick a foreground voxel as a center rather than a background voxel. num_samples: number of samples (crop regions) to take in each list. image: optional image data to help select valid area, can be same as `img` or another image array. if not None, use ``label == 0 & image > image_threshold`` to select the negative sample (background) center. So the crop center will only come from the valid image areas. image_threshold: if enabled `image`, use ``image > image_threshold`` to determine the valid image content areas. fg_indices: if provided pre-computed foreground indices of `label`, will ignore above `image` and `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices` and `bg_indices` together, expect to be 1 dim array of spatial indices after flattening. a typical usage is to call `FgBgToIndices` transform first and cache the results. bg_indices: if provided pre-computed background indices of `label`, will ignore above `image` and `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices` and `bg_indices` together, expect to be 1 dim array of spatial indices after flattening. a typical usage is to call `FgBgToIndices` transform first and cache the results. allow_smaller: if `False`, an exception will be raised if the image is smaller than the requested ROI in any dimension. If `True`, any smaller dimensions will be set to match the cropped size (i.e., no cropping in that dimension). lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Raises: ValueError: When ``pos`` or ``neg`` are negative. ValueError: When ``pos=0`` and ``neg=0``. Incompatible values. N?rWFrtorch.Tensor | Nonefloatrr)r?r@) rlabelposnegrimageimage_threshold fg_indices bg_indicesrrCrDc Cst|| ||_||_|dks(|dkr>td|d|d||dkrRtd||||_||_||_||_d|_ ||_ | |_ | |_ dS)Nrz)pos and neg must be nonnegative, got pos=z neg=rz%Incompatible values: pos=0 and neg=0.) rrFrr;r pos_ratiorr>r?r+r@rAr) rHrr;r<r=rr>r?r@rArrCrIrIrJrFTs  zRandCropByPosNegLabel.__init__)r;r@rAr>rDc Cs|dkr|jn|}|dkr |jn|}|dks4|dkrV|dkrDtdt|||j\}}d}|dk rt|trt|n |jdd}n(|dk rt|tr|n |jdd}|dkrtdt |j |j |j ||||j |j|_dS)Nzlabel must be provided.rWz9label or image must be provided to get the spatial shape.)r@rArrr?r[r r\r]rrrrBrrr+)rHr;r@rAr>Z fg_indices_Z bg_indices__shaperIrIrJrrs." zRandCropByPosNegLabel.randomizercCs ||_dSrEr.r rIrIrJrCszRandCropByPosNegLabel.lazycCsdSr rIr rIrIrJr sz+RandCropByPosNegLabel.requires_current_dataTrSrUr)rVr;r>r@rArrCrDcCs|dkr|j}|r0|dkr |j}|||||g}|jdk rt|trP|n |jdd} t|j | d} |dkrz|j n|} t |jD]X\} } t | | | d}||}t r|}| |jtj<| |jd<|j|d| d||q|S)a@ Args: img: input data to crop samples from based on the pos/neg ratio of `label` and `image`. Assumes `img` is a channel-first array. label: the label image that is used for finding foreground/background, if None, use `self.label`. image: optional image data to help select valid area, can be same as `img` or another image array. use ``label == 0 & image > image_threshold`` to select the negative sample(background) center. so the crop center will only exist on valid image area. if None, use `self.image`. fg_indices: foreground indices to randomly select crop centers, need to provide `fg_indices` and `bg_indices` together. bg_indices: background indices to randomly select crop centers, need to provide `fg_indices` and `bg_indices` together. randomize: whether to execute the random operations, default to `True`. lazy: a flag to override the lazy behaviour for this call, if set. Defaults to None. NrWdefaultr/r0Tr)r>r;rr+r[r r\r]r*rrCrr2r rrrrr)rHrVr;r>r@rArrCr4r3rrcrjr5r{rr6rIrIrJrds*     zRandCropByPosNegLabel.__call__) Nr7r7rWNr8NNFF)NNNN)NNNNTNrQr}r~rr2rrFrrrCrr(r rdrIrIrIrJr:s::&  c@seZdZdZejZd!ddd d d d d d ddd ddd ddZd"d d d ddddZej j ddddZ e ddZ d#dd d d dddddd Z dS)$r;a) Crop random fixed sized regions with the center being a class based on the specified ratios of every class. The label data can be One-Hot format array or Argmax data. And will return a list of arrays for all the cropped images. For example, crop two (3 x 3) arrays from (5 x 5) array with `ratios=[1, 2, 3, 1]`:: image = np.array([ [[0.0, 0.3, 0.4, 0.2, 0.0], [0.0, 0.1, 0.2, 0.1, 0.4], [0.0, 0.3, 0.5, 0.2, 0.0], [0.1, 0.2, 0.1, 0.1, 0.0], [0.0, 0.1, 0.2, 0.1, 0.0]] ]) label = np.array([ [[0, 0, 0, 0, 0], [0, 1, 2, 1, 0], [0, 1, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] ]) cropper = RandCropByLabelClasses( spatial_size=[3, 3], ratios=[1, 2, 3, 1], num_classes=4, num_samples=2, ) label_samples = cropper(img=label, label=label, image=image) The 2 randomly cropped samples of `label` can be: [[0, 1, 2], [[0, 0, 0], [0, 1, 3], [1, 2, 1], [0, 0, 0]] [1, 3, 0]] If a dimension of the expected spatial size is larger than the input image size, will not crop that dimension. So the cropped result may be smaller than expected size, and the cropped results of several images may not have exactly same shape. And if the crop ROI is partly out of the image, will automatically adjust the crop center to ensure the valid crop ROI. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_size: the spatial size of the crop region e.g. [224, 224, 128]. if a dimension of ROI size is larger than image size, will not crop that dimension of the image. if its components have non-positive values, the corresponding size of `label` will be used. for example: if the spatial size of input data is [40, 40, 40] and `spatial_size=[32, 64, -1]`, the spatial size of output data will be [32, 40, 40]. ratios: specified ratios of every class in the label to generate crop centers, including background class. if None, every class will have the same ratio to generate crop centers. label: the label image that is used for finding every class, if None, must set at `self.__call__`. num_classes: number of classes for argmax label, not necessary for One-Hot label. num_samples: number of samples (crop regions) to take in each list. image: if image is not None, only return the indices of every class that are within the valid region of the image (``image > image_threshold``). image_threshold: if enabled `image`, use ``image > image_threshold`` to determine the valid image content area and select class indices only in this area. indices: if provided pre-computed indices of every class, will ignore above `image` and `image_threshold`, and randomly select crop centers based on them, expect to be 1 dim array of spatial indices after flattening. a typical usage is to call `ClassesToIndices` transform first and cache the results for better performance. allow_smaller: if `False`, an exception will be raised if the image is smaller than the requested ROI in any dimension. If `True`, any smaller dimensions will remain unchanged. warn: if `True` prints a warning if a class is not present in the label. max_samples_per_class: maximum length of indices to sample in each class to reduce memory consumption. Default is None, no subsampling. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. NrWr8FTrzlist[float | int] | Noner9rrr:zlist[NdarrayOrTensor] | Noner?r@) rratiosr; num_classesrr>r?indicesrr2max_samples_per_classrCrDc CsXt|| ||_||_||_||_||_||_||_d|_ ||_ | |_ | |_ | |_ dSrE)rrFrrGr;rHrr>r?r+rIrr2rJ) rHrrGr;rHrr>r?rIrr2rJrCrIrIrJrFs zRandCropByLabelClasses.__init__)r;rIr>rDc Cs|dkr|jn|}|dkr@|dkr*tdt||j||j|j}d}|dk rnt|tr^|n |j dd}n(|dk rt|tr|n |j dd}|dkrtdt |j |j |||j |j|j|j|_dS)Nzlabel must not be None.rWzBlabel or image must be provided to infer the output spatial shape.)rIrrrHr?rJr[r r\r]rrrrGrrr2r+)rHr;rIr>Zindices_rCrIrIrJr/s8" z RandCropByLabelClasses.randomizercCs ||_dSrEr.r rIrIrJrCGszRandCropByLabelClasses.lazycCsdSr rIr rIrIrJr Ksz,RandCropByLabelClasses.requires_current_datarSrUr)rVr;r>rIrrCrDcCs|dkr|j}|r.|dkr |j}||||g}|jdk rt|trN|n |jdd}t|j |d} |dkrx|j n|} t |jD]\\} } t t | | | d} | |}tr|}| |jtj<| |jd<|j|d| d||q|S)a Args: img: input data to crop samples from based on the ratios of every class, assumes `img` is a channel-first array. label: the label image that is used for finding indices of every class, if None, use `self.label`. image: optional image data to help select valid area, can be same as `img` or another image array. use ``image > image_threshold`` to select the centers only in valid region. if None, use `self.image`. indices: list of indices for every class in the image, used to randomly select crop centers. randomize: whether to execute the random operations, default to `True`. lazy: a flag to override the lazy behaviour for this call, if set. Defaults to None. NrWrDr/r0Tr)r>r;rr+r[r r\r]r*rrCrr2rr rrrrr)rHrVr;r>rIrrCr4r3rrcrjr5r{rr6rIrIrJrdOs*     zRandCropByLabelClasses.__call__) NNNrWNr8NFTNF)NNN)NNNTNrFrIrIrIrJr;s8E( c@seZdZdZeeejeej@Ze j e j dfdddddddZ ejjdd d d Zdd ddd dddZdddddZdddddZd S)r<a Resize an image to a target spatial size by either centrally cropping the image or padding it evenly with a user-specified mode. When the dimension is smaller than the target size, do symmetric padding along that dim. When the dimension is larger than the target size, do central cropping along that dim. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_size: the spatial size of output data after padding or crop. If has non-positive values, the corresponding size of input image will be used (no padding). method: {``"symmetric"``, ``"end"``} Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``. mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Frr>r?rrrBrCcKs8t||tf||||d||_t||d|_dS)NrKr)rrFr.rr3r{)rHrrrBrCrrIrIrJrFs zResizeWithPadOrCrop.__init__)valcCs||j_||j_||_dSrE)rrCr{r)rHrLrIrIrJrCszResizeWithPadOrCrop.lazyNrSrTrUr%c Ks|dkr|jn|}|j|||f||d|}tr|}|sz|j}|j} | tj} |j || || d|dnR|j }|j } | tj} |j || |t j | t j |t j || d|d|S)a  Args: img: data to pad or crop, assuming `img` is channel-first and padding or cropping doesn't apply to the channel dim. mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html lazy: a flag to override the lazy behaviour for this call, if set. Defaults to None. pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Nr)rr")rrrC)rrrrrC)rCrr{r rrrr#rrrr rr ) rHrVrBrCrrcrr6rr"rrIrIrJrds4        zResizeWithPadOrCrop.__call__r rcCs||}|||SrE)rqr)rHrVrxrIrIrJr|s zResizeWithPadOrCrop.inversecCsP|tjd}|tjd}|j||j||j|}|j|S)Nr"r)r#rrrrrrr|r{)rHrVrxr"rr'rIrIrJrs    z%ResizeWithPadOrCrop.inverse_transform)NN)rQr}r~rrsetr.rr3r!rr"rrFrrCrrdr|rrIrIrIrJr<{s -c@s@eZdZdZejejgZefdddddZ ddd d d Z d S) r=a Compute coordinates of axis-aligned bounding rectangles from input image `img`. The output format of the coordinates is (shape is [channel, 2 * spatial dims]): [[1st_spatial_dim_start, 1st_spatial_dim_end, 2nd_spatial_dim_start, 2nd_spatial_dim_end, ..., Nth_spatial_dim_start, Nth_spatial_dim_end], ... [1st_spatial_dim_start, 1st_spatial_dim_end, 2nd_spatial_dim_start, 2nd_spatial_dim_end, ..., Nth_spatial_dim_start, Nth_spatial_dim_end]] The bounding boxes edges are aligned with the input image edges. This function returns [0, 0, ...] if there's no positive intensity. Args: select_fn: function to select expected foreground, default is to select values > 0. rr@)rrDcCs ||_dSrE)r)rHrrIrIrJrFszBoundingRect.__init__r rrcCsTg}t|jdD]2}t||j|d\}}|ddt||Dqtj|ddS)z] See also: :py:class:`monai.transforms.utils.generate_spatial_bounding_box`. r)rrcSsg|]}|D]}|q qSrIrI)rirrjrIrIrJrk sz)BoundingRect.__call__..)axis)rr]rrrrvrstack)rHrVbboxchannelstart_end_rIrIrJrds zBoundingRect.__call__N) rQr}r~rr$rrrrrFrdrIrIrIrJr=s )Rr __future__rr1collections.abcrr itertoolsrmathrtypingrnumpyrr monai.configr monai.config.type_definitionsr monai.data.meta_objr monai.data.meta_tensorr monai.data.utilsr r#monai.transforms.croppad.functionalrrmonai.transforms.inverserrmonai.transforms.traitsrmonai.transforms.transformrrrmonai.transforms.utilsrrrrrrrr monai.utilsrrr r!r"r#r$r%r&r'r(r)r*r+r,__all__r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=rIrIrIrJ st         ( <e::/`5*I>S3W42l