o  iN#@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;mGdddee$Z?Gddde?Z@Gddde?ZAGddde?ZBGdddee$ZCGdd d eCZDGd!d"d"eCZEGd#d$d$eCZFGd%d&d&e%eCZGGd'd(d(eGZHGd)d*d*e%e e$e"ZIGd+d,d,eCZJGd-d.d.e%e e$e"ZKGd/d0d0e%e e$e"ZLGd1d2d2e%e e$e"ZMGd3d4d4ee$ZNGd5d6d6e&ZOdS)7zC 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_tensor ensure_tupleensure_tuple_repfall_back_tuplelook_up_option)Pad SpatialPad BorderPad DivisiblePadCrop SpatialCropCenterSpatialCropCenterScaleCropRandSpatialCrop RandScaleCropRandSpatialCropSamplesCropForegroundRandWeightedCropRandCropByPosNegLabelRandCropByLabelClassesResizeWithPadOrCrop BoundingRectc@sVeZdZdZejejgZdej dfdd d Z dddZ   dd ddZ d!ddZ 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. NFto_padtuple[tuple[int, int]] | NonemodestrlazyboolreturnNonecKs"t||||_||_||_dSN)r__init__r<r>kwargs)selfr<r>r@rFrH`/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/croppad/array.pyrEms  z Pad.__init__ spatial_shape Sequence[int]tuple[tuple[int, int]]cCstd|jjd)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.)NotImplementedError __class____name__)rGrJrHrHrIcompute_pad_widthys zPad.compute_pad_widthimg torch.Tensor str | None bool | Nonec Ks|dur|jn|}|dur"t|tr|n|jdd}||}|dur)|jn|}t|j} | |t |t d} |durC|j n|} t | |||| fi| 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)r< isinstancer peek_pending_shapeshaperPr>dictrFupdater&r r@rget_transform_info) rGrQr<r>r@rFZto_pad_rJZmode_kwargs_img_tlazy_rHrHrI__call__s    z Pad.__call__rWr c Cs||}|tjd}|dddks|dddkr<|dd}tt|dd|dt|}||t||}dd|ddD}ddt|jdd|ddD}t||d}| d ||WdS1stwYdS) NpaddedrrUcSsg|]}|dqSrrH.0irHrHrI zPad.inverse..cSsg|] \}}||dqS)rUrHrfrgjrHrHrIrh roi_startroi_endF) pop_transformr# EXTRA_INFOminmaxlenzipr[r0trace_transform) rGrW transformrcsernrocropperrHrHrIinverses    &  $z Pad.inverse)r<r=r>r?r@rArBrCrJrKrBrLNNN) rQrRr<r=r>rSr@rTrBrR)rWr rBr )rO __module__ __qualname____doc__r$TORCHNUMPYbackendr"CONSTANTrErPrbr{rHrHrHrIr+Qs   $r+cs8eZdZdZejejdfdfd d ZdddZ 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. F spatial_size7Sequence[int] | int | tuple[tuple[int, ...] | int, ...]methodr?r>r@rArBrCc s.||_t|t|_tjd||d|dSNr>r@rH)rr*r!rsuperrE)rGrrr>r@rFrNrHrIrEs zSpatialPad.__init__rJrKrLcst|j}|jtjkr2g}t|D]\}}t||d}|t|dt||dfqn fddt|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||dfqSrd)intrs)rfrgsp_irJrHrIrhs*z0SpatialPad.compute_pad_width..rr) r)rrr! SYMMETRIC enumeratersappendrtuple)rGrJr pad_widthrgrwidthrHrrIrPs  $zSpatialPad.compute_pad_width) rrrr?r>r?r@rArBrCr|) rOr~rrr!rr"rrErP __classcell__rHrHrrIr,s r,cs4eZdZdZejdfdfd d ZdddZZS)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. Fspatial_borderSequence[int] | intr>r?r@rArBrCc s"||_tjd||d|dSr)rrrE)rGrr>r@rFrrHrIrEszBorderPad.__init__rJrKrLc st|jtddDstddtddDtdkr/fdd|D}nDtt|krEd ddt|D}n.tt|d kr]fd dtt|D}ntd td t|dd t|dtdg|S)Ncss|]}t|tVqdSrD)rYrrfbrHrHrI z.BorderPad.compute_pad_width..z0self.spatial_border must contain only ints, got .css|]}td|VqdS)rN)rsrrHrHrIrrrUcs$g|]}tdtdfqSrdr)rf_rrHrIrhs$z/BorderPad.compute_pad_width..cSsg|] }t|t|fqSrHr)rfsprHrHrIrhrlrcs0g|]}td|td|dfqS)rrUrrerrHrIrhs$z#Unsupported spatial_border length: z/, available options are [1, len(spatial_shape)=z, 2*len(spatial_shape)=z].r)r'rall ValueErrorrrtrange)rGrJZdata_pad_widthrHrrIrPs(      zBorderPad.compute_pad_width)rrr>r?r@rArBrCr|) rOr~rrr"rrErPrrHrHrrIr-s r-cs>eZdZdZejZejej dfdfd d Z dddZ Z S)r.z 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. Fkrr>r?rr@rArBrCc s,||_t||_tjd||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` rNrH)rr!rrrE)rGrr>rr@rFrrHrIrE4s zDivisiblePad.__init__rJrKrLcCs&t||jd}t||jd}||S)N)rJr)rr)rrr,rrP)rGrJnew_sizeZ spatial_padrHrHrIrPSs zDivisiblePad.compute_pad_width) rrr>r?rr?r@rArBrCr|) rOr~rrr,rr"rr!rrErPrrHrHrrIr.*sr.c@sVeZdZdZejgZddddZe     dd ddZ d!d"ddZ d#ddZ dS)$r/a+ 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@rAcCst||dSrD)rrE)rGr@rHrHrIrEfsz Crop.__init__N roi_center,Sequence[int] | int | NdarrayOrTensor | Noneroi_sizernro roi_slicesSequence[slice] | NonerB tuple[slice]c Cs@|rtdd|Dstd|dt|S|durO|durOt|tjddd}t|tjddd}t|}tj|d d d }t|||} t| || } n+|dusW|dur[td t|tjdd } t| t| } t|tjdd } t| | } | dkrtt t | t | gStddt | | DS)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$|] }|jdup |jdkVqdS)NrU)step)rfrxrHrHrIrs"z&Crop.compute_slices..z8only slice steps of 1/None are currently supported, got rNTcpu)rWdtype wrap_sequencedevicerfloor) rounding_modezAplease specify either roi_center, roi_size or roi_start, roi_end.)rWrrrUcSs"g|] \}}tt|t|qSrH)slicer)rfrxryrHrHrIrhs"z'Crop.compute_slices..)rrr'r&torchint16 zeros_likedividemaximumnumelrritemrutolist) rrrnrorZ roi_center_tZ roi_size_tZ_zeroshalf roi_start_t roi_end_trHrHrIcompute_slicesis(     zCrop.compute_slicesrQrRslicestuple[slice, ...]rTcCst|}tt|tr|n|jdd}t||kr)|tdg|t|7}ttdg|d|}t|td}|durD|j n|}t |t ||| S) Apply the transform to `img`, assuming `img` is channel-first and slicing doesn't apply to the channel dim. rUNrV) listrtrYr rZr[rr&r r@rrr^)rGrQrr@Zslices_sdr`rarHrHrIrbs$ z Crop.__call__r cCsV||}|tjd}t|}|d ||WdS1s$wYdS)NcroppedF)rpr#rqr-rv)rGrQrwrinverse_transformrHrHrIr{s  $z Crop.inverseF)r@rA)NNNNN) rrrrrnrrorrrrBrrD)rQrRrrr@rTrBrRrQr rBr ) rOr~rrr$rrrE staticmethodrrbr{rHrHrHrIr/Ys / r/cs@eZdZdZ      ddfdd Zddfdd ZZS)r0a  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. NFrrrrnrorrr@rArBrCcs&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. )rrrnrorN)rrErr)rGrrrnrorr@rrHrIrEs   zSpatialCrop.__init__rQrRrTcs*|dur|jn|}tj|t|j|dS)rNrQrr@)r@rrbr'rrGrQr@rarrHrIrbszSpatialCrop.__call__)NNNNNF)rrrrrnrrorrrr@rArBrCrDrQrRr@rTrBrRrOr~rrrErbrrHrHrrIr0sr0csBeZdZdZddfd d Zdfdd Zddfdd ZZS)r1a 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. Frrr@rArBrCctj|d||_dSNr@)rrEr)rGrr@rrHrIrE zCenterSpatialCrop.__init__rrKrcs*t|j|}dd|D}tj||dS)NcSsg|]}|dqS)rrHrerHrHrIrhriz4CenterSpatialCrop.compute_slices..)rr)r)rrr)rGrrrrrHrIrs z CenterSpatialCrop.compute_slicesNrQrRrTcsF|dur|jn|}tj||t|tr|n|jdd|dS)rNrUr)r@rrbrrYr rZr[rrrHrIrbs $zCenterSpatialCrop.__call__r)rrr@rArBrC)rrKrBrrDr)rOr~rrrErrbrrHrHrrIr1s r1cs4eZdZdZddfdd Zddfdd ZZS)r2a% 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. F roi_scaleSequence[float] | floatr@rAcrr)rrEr)rGrr@rrHrIrE!rzCenterScaleCrop.__init__NrQrRrTrBcszt|tr |n|jdd}t|}ddtt|j||D}|dur)|jn|}t ||d}t j || ||dS)NrUcSg|] \}}t||qSrHrrfrrxrHrHrIrh(rlz,CenterScaleCrop.__call__..rr@r) rYr rZr[rtrur(rr@r1rrbr)rGrQr@img_sizendimrrarzrrHrIrb%s  zCenterScaleCrop.__call__r)rrr@rArDrrrHrHrrIr2s r2csFeZdZdZ    ddfdd ZdddZddfdd ZZS) r3aQ 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. NTFrr max_roi_sizeSequence[int] | int | None random_centerrA random_sizer@rBrCcs2t|||_||_||_||_d|_|dSrD)rrErrrr_size)rGrrrrr@rrHrIrEJs zRandSpatialCrop.__init__rrKcstj|_jrAjdur|ntj|tddtjDr0tdjddtfddt t |D_j rTt |j}t ||j_dSdS)Ncss|] \}}||kVqdSrDrHrjrHrHrIr^sz,RandSpatialCrop.randomize..zmin ROI size: z is larger than max ROI size: rc3s.|]}jjj||ddVqdS)rU)lowhighN)Rrandintrremax_sizerGrHrIr`s,)r)rrrranyrurrrrtrrr r_slices)rGrZ valid_sizerHrrI randomizeZs" zRandSpatialCrop.randomizerQrRrrTcst|tr |n|jdd}|r|||jdur td|dur'|jn|}|jr6t j ||j |dSt |j|d}t j || ||dS)rrUNzself._size not specified.rr)rYr rZr[rr RuntimeErrorr@rrrbrr1r)rGrQrr@rrarzrrHrIrbes   zRandSpatialCrop.__call__NTFF) rrrrrrArrAr@rArBrCrrKrBrCTNrQrRrrAr@rTrBrR)rOr~rrrErrbrrHrHrrIr3.s  r3csReZdZdZ    ddfdd ZddZdfdd Zd d!fdd ZZS)"r4a5 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. NTFrr max_roi_scaleSequence[float] | float | NonerrArr@rBrCcs&tjdd|||d||_||_dS)N)rrrrr@)rrErr)rGrrrrr@rrHrIrEs   zRandScaleCrop.__init__cCs\t|}ddtt|j||D|_|jdur)ddtt|j||D|_dSd|_dS)NcSrrHrrrHrHrIrhrlz2RandScaleCrop.get_max_roi_size..cSrrHrrrHrHrIrhrl)rtrur(rrrr)rGrrrHrHrIget_max_roi_sizes  " zRandScaleCrop.get_max_roi_sizerrKcs||t|dSrD)rrr)rGrrrHrIrs zRandScaleCrop.randomizerQrRrrTcsJ|t|tr |n|jdd|dur|jn|}tj|||dS)rrUN)rQrr@)rrYr rZr[r@rrb)rGrQrr@rarrHrIrbs&zRandScaleCrop.__call__r) rrrrrrArrAr@rArBrCrrr) rOr~rrrErrrbrrHrHrrIr4wsr4csjeZdZdZejZ    d&d'ddZ d(d)fdd Zej j d*ddZ d+d,ddZ d+d-d$d%Z Z S).r5a  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. NTFrr num_samplesrrrrrArr@rBrCcCs@t|||dkrtd|d||_t||||||_dS)NrUz"num_samples must be positive, got r)rrErrr3rz)rGrrrrrr@rHrHrIrEs zRandSpatialCropSamples.__init__seed int | Nonestatenp.random.RandomState | Nonecs t|||j|||SrD)rset_random_staterz)rGrrrrHrIrsz'RandSpatialCropSamples.set_random_statevaluecC||_||j_dSrD)_lazyrzr@)rGrrHrHrIr@ zRandSpatialCropSamples.lazyrW Any | NonecCsdSrDrH)rGrWrHrHrIrsz RandSpatialCropSamples.randomizerQrRrTlist[torch.Tensor]cCsdg}|dur |jn|}t|jD]}|j||d}tr*||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. NrTreplacer@) r@rrrzr metaKey PATCH_INDEXpush_transformr)rGrQr@retrargrrHrHrIrbs  zRandSpatialCropSamples.__call__r)rrrrrrrrArrAr@rArBrCNN)rrrrrBr5)rrArBrCrD)rWrrBrC)rQrRr@rTrBr)rOr~rrr3rrErrr@setterrrbrrHrHrrIr5s"   r5cseZdZdZedddddejdfd-ddZej j d.ddZ e ddZ d/dd Z  d0d1fd%d& Z d2d3d(d)Zd4fd+d, ZZS)5r6a 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. NrFrU select_fnrchannel_indicesIndexSelection | Nonemarginr allow_smallerrA return_coords k_divisibler>r?r@rBrCc KsZt||||_|durt|nd|_||_||_||_||_t d||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 `False`. The default value is changed from `True` to `False` in v1.5.0. 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. NrrH) rrErr'r r r r rr+padder) rGrr r r r rr>r@ pad_kwargsrHrHrIrE+s $zCropForeground.__init___valcCrrD)rrr@rGrrHrHrIr@XrzCropForeground.lazycCdSNFrHrGrHrHrIrequires_current_data]z$CropForeground.requires_current_datarQrRtuple[np.ndarray, np.ndarray]c 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)rrr r r r%npndarrayrasarrayrrr floor_divide) rGrQ box_startbox_endZ box_start_rZbox_end_Zorig_spatial_sizerrHrHrIcompute_bounding_boxasz#CropForeground.compute_bounding_boxr np.ndarrayrrSc sR|j||d}tj|||d}t| d} t|tt|tr%|n|j ddd} t t t | | } t| dt|trK|n|j dd} |jjd || ||d|} trt| tr|sz| j| jdtjd <| S| j}| j}|tj}||d <|j| |tj|tj|tj|tj||d | S) z: Crop and pad based on the bounding box. rmrrrUNr)rQr<r>r@rpad_info) orig_sizesp_sizeaffiner@ extra_inforH)rrrbrrrrYr rZr[rrrurr-rPrr applied_operationspopr#rqpending_operationsrget ORIG_SIZEr SHAPEAFFINE)rGrQrrr>r@rrrZ pad_to_startZ pad_to_endpadrrr" crop_infoextrarrHrIcrop_padts8 *    zCropForeground.crop_padrTc KsP||\}}|dur|jn|}|j||||fd|i|}|jr&|||fS|S)z Apply the transform to `img`, assuming `img` is channel-first and slicing doesn't change the channel dim. Nr@)r r@r1r ) rGrQr>r@rrrrarrHrHrIrbs  zCropForeground.__call__r cs>||}|tjd}|j||j|}t|S)Nr") get_most_recent_transformr#rqr(r'rrr{r)rGrQrwr"invrrHrIr{s    zCropForeground.inverse)rrr r r rr rAr rArrr>r?r@rArBrCrrA)rQrRrBrr) rQrRrr!rr!r>rSr@rArBrRrrQrRr>rSr@rTrBrRr)rOr~rrrr"rrEr/r@rpropertyrr r1rbr{rrHrHrrIr6s,$ -   - r6c@sVeZdZdZejZ   dd d dZd!ddZej j d"ddZ   d#d$ddZ dS)%r7a 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. rUNFrrrr weight_mapNdarrayOrTensor | Noner@rAcCs0t||t||_t||_||_g|_dSrD)rrEr'rrrr7centers)rGrrr7r@rHrHrIrEs    zRandWeightedCrop.__init__r rBrCcCs t|j|d|j|jd|_dS)Nr)rw n_samplesZr_state)rrrrr9)rGr7rHrHrIrs zRandWeightedCrop.randomizercC ||_dSrDrrrHrHrIr@ zRandWeightedCrop.lazyTrQrRrrTrcCst|tr |n|jdd}|rF|dur|j}|dur!tdt|tr*|n|jdd}||krAtd|d|d||t |j |}g}|durU|j n|} t |j D],\} } 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 rUNz8weight map must be provided for weighted patch sampling.z-image and weight map spatial shape mismatch: z vs rrrr@ crop_centerTr)rYr rZr[r7rwarningswarnrr)rr@rr9r0r rrrrr)rGrQr7rr@ img_shapeZw_shapeZ _spatial_sizeresultsrargcenterrzrret_rHrHrIrbs.       zRandWeightedCrop.__call__)rUNF)rrrrr7r8r@rA)r7r rBrCr4)NTN) rQrRr7r8rrAr@rTrBr) rOr~rrr0rrErrr@rrbrHrHrHrIr7s  r7c@seZdZdZejZ          d+d,ddZ    d-d.ddZej j d/dd Z e d!d"Z     # d0d1d)d*Z dS)2r8aL 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?rUFrrlabeltorch.Tensor | Noneposfloatnegrrimageimage_threshold fg_indicesr8 bg_indicesr rAr@rBrCc Cst|| ||_||_|dks|dkrtd|d|d||dkr)td||||_||_||_||_d|_ ||_ | |_ | |_ dS)Nrz)pos and neg must be nonnegative, got pos=z neg=rz%Incompatible values: pos=0 and neg=0.) rrErrIr pos_ratiorrNrOr9rPrQr ) rGrrIrKrMrrNrOrPrQr r@rHrHrIrENs   zRandCropByPosNegLabel.__init__c Cs|dur|jn|}|dur|jn|}|dus|dur+|dur"tdt|||j\}}d}|durBt|tr:|n|jdd}n|durVt|trO|n|jdd}|dur^tdt |j |j |j ||||j |j|_dS)Nzlabel must be provided.rUz9label or image must be provided to get the spatial shape.)rPrQrrrOrYr rZr[rrrrRrr r9)rGrIrPrQrNZ fg_indices_Z bg_indices__shaperHrHrIrls."  zRandCropByPosNegLabel.randomizercCr<rDr=rrHrHrIr@r>zRandCropByPosNegLabel.lazycCrrrHrrHrHrIrrz+RandCropByPosNegLabel.requires_current_dataTrQrRrrTrcCs|dur|j}|r|dur|j}|||||g}|jdurqt|tr(|n|jdd} t|j | d} |dur=|j n|} t |jD],\} } t | | | d}||}t rk|}| |jtj<| |jd<|j|d| d||qD|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. NrUdefaultr?r@Tr)rNrIrr9rYr rZr[r)rr@rr0r rrrrr)rGrQrIrNrPrQrr@rDrCrrargrErzrrFrHrHrIrbs*     zRandCropByPosNegLabel.__call__) NrGrGrUNrHNNFF)rrrIrJrKrLrMrLrrrNrJrOrLrPr8rQr8r rAr@rArBrC)NNNN) rIrJrPr8rQr8rNrJrBrCr4)NNNNTN)rQrRrIrJrNrJrPr8rQr8rrAr@rTrBrrOr~rrr0rrErrr@rr6rrbrHrHrHrIr8s<:     r8c@s~eZdZdZejZ           d-d.ddZ   d/d0dd Zej j d1d"d#Z e d$d%Z     d2d3d+d,Z dS)4r9a) 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. NrUrHFTrrratioslist[float | int] | NonerIrJ num_classesrrrrNrOrLindiceslist[NdarrayOrTensor] | Noner rArBmax_samples_per_classr@rBrCc CsXt|| ||_||_||_||_||_||_||_d|_ ||_ | |_ | |_ | |_ dSrD)rrErrWrIrYrrNrOr9rZr rBr\) rGrrWrIrYrrNrOrZr rBr\r@rHrHrIrE s  zRandCropByLabelClasses.__init__c Cs|dur|jn|}|dur |durtdt||j||j|j}d}|dur7t|tr/|n|j dd}n|durKt|trD|n|j dd}|durStdt |j |j |||j |j|j|j|_dS)Nzlabel must not be None.rUzBlabel or image must be provided to infer the output spatial shape.)rZrrrYrOr\rYr rZr[rrrrWrr rBr9)rGrIrZrNZindices_rSrHrHrIr)s""  z RandCropByLabelClasses.randomizercCr<rDr=rrHrHrIr@Ar>zRandCropByLabelClasses.lazycCrrrHrrHrHrIrErz,RandCropByLabelClasses.requires_current_datarQrRrrTrcCs|dur|j}|r|dur|j}||||g}|jdurrt|tr'|n|jdd}t|j |d} |dur<|j n|} t |jD].\} } t t | | | d} | |}trl|}| |jtj<| |jd<|j|d| d||qC|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. NrUrTr?r@Tr)rNrIrr9rYr rZr[r)rr@rr0rr rrrrr)rGrQrIrNrZrr@rDrCrrargrErzrrFrHrHrIrbIs*     zRandCropByLabelClasses.__call__) NNNrUNrHNFTNF)rrrWrXrIrJrYrrrrNrJrOrLrZr[r rArBrAr\rr@rArBrCr})rIrJrZr[rNrJrBrCr4)NNNTN)rQrRrIrJrNrJrZr[rrAr@rTrBrrVrHrHrHrIr9s:E    r9c@sreZdZdZeeejeej@Ze j e j dfdd d Z ejjdd dZ ddddZd ddZd ddZdS)!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. Frrrr?r>r@rAcKs8t||td||||d||_t||d|_dS)N)rrr>r@rrH)rrEr,rr1rz)rGrrr>r@rrHrHrIrEs zResizeWithPadOrCrop.__init__valcCs||j_||j_||_dSrD)rr@rzr)rGr]rHrHrIr@s zResizeWithPadOrCrop.lazyNrQrRrSrTrBc Ks|dur|jn|}|j|||f||d|}trg|}|s>|j}|j} | tj} |j || || d|d|S|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)r"r/)r#r&r@)r#r$r%r&r@)r@rrzr r'r(r*r#r+rr)r r,r-) rGrQr>r@rrarrFr"r/r#rHrHrIrbs0       zResizeWithPadOrCrop.__call__r cCs||}|||SrD)rpr)rGrQrwrHrHrIr{s  zResizeWithPadOrCrop.inversecCsP|tjd}|tjd}|j||j||j|}|j|S)Nr/r")r#rqr(r'rrr{rz)rGrQrwr/r"r3rHrHrIrs     z%ResizeWithPadOrCrop.inverse_transform)rrrr?r>r?r@rA)r]rArr5r)rOr~rrrsetr,rr1r!rr"rrErr@rrbr{rrHrHrHrIr:us   -r:c@s4eZdZdZejejgZefdddZ dd 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. rrrBrCcCr<rD)r)rGrrHrHrIrEs zBoundingRect.__init__rQr r!cCsTg}t|jdD]}t||j|d\}}|ddt||Dq tj|ddS)z] See also: :py:class:`monai.transforms.utils.generate_spatial_bounding_box`. r)rr cSsg|] }|D]}|qqSrHrH)rfrrgrHrHrIrhsz)BoundingRect.__call__..)axis)rr[rrrrurstack)rGrQbboxchannelstart_end_rHrHrIrbs zBoundingRect.__call__N)rrrBrC)rQr rBr!) rOr~rrr$rrrrrErbrHrHrHrIr;s  r;)Pr __future__rrAcollections.abcrr itertoolsrmathrtypingrnumpyrrZ 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*__all__r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;rHrHrHrIsT         ( 4e::/\5*I>S3W42l