o  i@sdZddlmZddlmZmZmZmZddlm Z ddl m Z ddl Z ddlZddlmZmZmZddlmZdd lmZdd lmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(dd l)m*Z*dd l+m,Z,m-Z-dd l.m/Z/m0Z0m1Z1ddl2m3Z3ddl4m5Z5m6Z6m7Z7m8Z8gdZ9Gddde0e*e/Z:Gddde:Z;Gddde:ZGddde>e1Z?Gddde>Z@Gdd d e>ZAGd!d"d"e>ZBGd#d$d$e?ZCGd%d&d&e?ZDGd'd(d(e1e0e/e-ZEGd)d*d*e>ZFGd+d,d,e1e0e/e-ZGGd-d.d.e1e0e/e-ZHGd/d0d0e1e0e/e-ZIGd1d2d2e:ZJGd3d4d4e0ZKe:ZLZMe;ZNZOe<ZPZQe=ZRZSe>ZTZUe?ZVZWe@ZXZYeAZZZ[eBZ\Z]eCZ^Z_eDZ`ZaeEZbZceFZdZeeGZfZgeHZhZieIZjZkeJZlZmeKZnZodS)5z A collection of dictionary-based wrappers around the "vanilla" transforms for crop and pad operations defined in :py:class:`monai.transforms.croppad.array`. Class names are ended with 'd' to denote dictionary-based transforms. ) annotations)CallableHashableMappingSequence)deepcopy)AnyN)IndexSelectionKeysCollection SequenceStr)NdarrayOrTensor) MetaTensor) BorderPad BoundingRectCenterScaleCropCenterSpatialCropCropCropForeground DivisiblePadPadRandCropByLabelClassesRandCropByPosNegLabel RandScaleCropRandSpatialCropRandSpatialCropSamplesRandWeightedCropResizeWithPadOrCrop SpatialCrop SpatialPad)InvertibleTransform) LazyTraitMultiSampleTrait) LazyTransform MapTransform Randomizable) is_positive)MAX_SEEDMethodPytorchPadModeensure_tuple_rep)6Padd SpatialPadd BorderPadd DivisiblePaddCropd RandCropd SpatialCropdCenterSpatialCropdCenterScaleCropdRandScaleCropdRandSpatialCropdRandSpatialCropSamplesdCropForegrounddRandWeightedCropdRandCropByPosNegLabeldResizeWithPadOrCropd BoundingRectdRandCropByLabelClassesdPadDPadDict SpatialPadDSpatialPadDict BorderPadD BorderPadDict DivisiblePadDDivisiblePadDictCropDCropDict RandCropD RandCropDict SpatialCropDSpatialCropDictCenterSpatialCropDCenterSpatialCropDictCenterScaleCropDCenterScaleCropDictRandScaleCropDRandScaleCropDictRandSpatialCropDRandSpatialCropDictRandSpatialCropSamplesDRandSpatialCropSamplesDictCropForegroundDCropForegroundDictRandWeightedCropDRandWeightedCropDictRandCropByPosNegLabelDRandCropByPosNegLabelDictResizeWithPadOrCropDResizeWithPadOrCropDict BoundingRectDBoundingRectDictRandCropByLabelClassesDRandCropByLabelClassesDictc@sReZdZdZejZejddfdddZe j j dddZ d d!ddZ d"ddZ dS)#r*z Dictionary-based wrapper of :py:class:`monai.transforms.Pad`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Fkeysr padderrmoder allow_missing_keysboollazyreturnNonecCs\t|||t|||dur t|ts tdt|d||_t|t |j |_ dS)aj Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` padder: pad transform for the input image. 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 It also can be a sequence of string, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. TzD'padder' must inherit LazyTrait if lazy is True 'padder' is of type()N) r#__init__r" isinstancer ValueErrortyperar)lenr`rb)selfr`rarbrcreroe/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/croppad/dictionary.pyri{s  z Padd.__init__valuecC"||_t|jtr||j_dSdSN)_lazyrjrar"rernrqrororpre  z Padd.lazyNdataMapping[Hashable, torch.Tensor] bool | Nonedict[Hashable, torch.Tensor]cCst|}|dur |jn|}|dur!t|jts!tdt|j|||jD]"\}}t|jtr?|j||||d||<q(|j|||d||<q(|S)NTzN'self.padder' must inherit LazyTrait if lazy is True 'self.padder' is of type()rbre)rb) dictrerjrar rkrl key_iteratorrb)rnrwredlazy_keymrororp__call__s z Padd.__call__Mapping[Hashable, MetaTensor]dict[Hashable, MetaTensor]cC0t|}||D] }|j||||<q |Srs)r{r|rainversernrwr}rrororprz Padd.inverse) r`r rarrbr rcrdrerdrfrgrqrdrfrgrsrwrxreryrfrzrwrrfr)__name__ __module__ __qualname____doc__rbackendr(CONSTANTrir"resetterrrrorororpr*qs   r*c@s(eZdZdZejejddfdddZdS)r+a1 Dictionary-based wrapper of :py:class:`monai.transforms.SpatialPad`. 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. Fr`r spatial_sizeSequence[int] | intmethodstrrbr rcrdrerfrgc Ks0t||fd|i|}tj||||||ddS)aW Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` 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. 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 It also can be a sequence of string, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. 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. rerarbrcreN)rr*ri) rnr`rrrbrcrekwargsrarororpri"zSpatialPadd.__init__N)r`r rrrrrbr rcrdrerdrfrg) rrrrr' SYMMETRICr(rrirorororpr+s r+c@s*eZdZdZejZejddfdddZdS)r,a Pad the input data by adding specified borders to every dimension. Dictionary-based wrapper of :py:class:`monai.transforms.BorderPad`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Fr`r spatial_borderrrbr rcrdrerfrgcKs.td||d|}tj||||||ddS)a# Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` spatial_border: specified size for every spatial border. 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 It also can be a sequence of string, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. 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. )rrerNro)rr*ri)rnr`rrbrcrerrarororpris%zBorderPadd.__init__N) r`r rrrbr rcrdrerdrfrg) rrrrrrr(rrirorororpr,sr,c@s.eZdZdZejZejej ddfdddZ dS)r-a Pad the input data, so that the spatial sizes are divisible by `k`. Dictionary-based wrapper of :py:class:`monai.transforms.DivisiblePad`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Fr`r krrbr rrrcrdrerfrgc Ks0td|||d|}tj||||||ddS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` 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 It also can be a sequence of string, each element corresponds to a key in ``keys``. method: {``"symmetric"``, ``"end"``} Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``. allow_missing_keys: don't raise exception if key is missing. 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` )rrrerNro)rr*ri) rnr`rrbrrcrerrarororpri#rzDivisiblePadd.__init__N)r`r rrrbr rrrcrdrerdrfrg) rrrrrrr(rr'rrirorororpr-sr-c@sJeZdZdZejZddd d Zejj dddZdd ddZ d!ddZ dS)"r.aP Dictionary-based wrapper of abstract class :py:class:`monai.transforms.Crop`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` cropper: crop transform for the input image. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Fr`r cropperrrcrdrecCs$t|||t||||_dSrs)r#rir"rrnr`rrcrerororpriZs  zCropd.__init__rqrfrgcCrrrs)rtrjrr"rerurororpre_rvz Cropd.lazyNrwrxryrzcCsDt|}|dur |jn|}||D] }|j|||d||<q|SNre)r{rer|r)rnrwrer}r~rrororpres zCropd.__call__rrcCrrs)r{r|rrrrororprlrz Cropd.inverseFFr`r rrrcrdrerdrrsrr) rrrrrrrir"rerrrrorororpr.Is   r.csPeZdZdZejZdd fd d Zd!d"fdd Zd#ddZd$d%ddZ Z S)&r/a/ Base class for random crop transform. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` cropper: random crop transform for the input image. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Fr`r rrrcrdrecstj||||ddS)Nrrcre)superrir __class__rorpriszRandCropd.__init__Nseed int | Nonestatenp.random.RandomState | Nonerfcs,t||t|jtr|j|||Srs)rset_random_staterjrr$rnrrrrorprs zRandCropd.set_random_stateimg_size Sequence[int]rgcCs t|jtr|j|dSdSrs)rjrr$ randomize)rnrrororprs zRandCropd.randomizerwrxryrzcCst|}|||}|t|tr|n|jdd|dur%|jn|}|dur;t|jt s;t dt |j| |D]%}t|jt rLddini}t|jt rX||d<|j||fi|||<q@|S)NTzP'self.cropper' must inherit LazyTrait if lazy is True 'self.cropper' is of type(rFre)r{ first_keyrrjr peek_pending_shapeshapererr rkrlr|r$)rnrwrer}Z first_itemr~rrrororprs & zRandCropd.__call__rrNN)rrrrrfr/)rrrfrgrsr) rrrrrrrirrr __classcell__rororrpr/ss r/cs2eZdZdZ       ddfdd ZZS)r0aR Dictionary-based wrapper of :py:class:`monai.transforms.SpatialCrop`. 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 -ve 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. NFr`r roi_centerSequence[int] | int | Noneroi_size roi_startroi_end roi_slicesSequence[slice] | Nonercrdrerfrgc s,t||||||d} tj|| ||ddS)ab Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` 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. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. rrN)rrri) rnr`rrrrrrcrerrrorpriszSpatialCropd.__init__)NNNNNFF)r`r rrrrrrrrrrrcrdrerdrfrgrrrrrirrororrpr0sr0cs&eZdZdZ ddfd d ZZS)r1a Dictionary-based wrapper of :py:class:`monai.transforms.CenterSpatialCrop`. 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: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform roi_size: the 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]. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Fr`r rrrcrdrerfrgc$t||d}tj||||ddSNrr)rrri)rnr`rrcrerrrorpris zCenterSpatialCropd.__init__r) r`r rrrcrdrerdrfrgrrororrpr1sr1cs(eZdZdZ  ddfd d ZZS)r2aj Dictionary-based wrapper of :py:class:`monai.transforms.CenterScaleCrop`. Note: as using the same scaled ROI to crop, all the input data specified by `keys` should have the same spatial shape. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform 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. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Fr`r roi_scaleSequence[float] | floatrcrdrerfrgcrr)rrri)rnr`rrcrerrrorpris zCenterScaleCropd.__init__r) r`r rrrcrdrerdrfrgrrororrpr2s r2c.eZdZdZ     ddfdd ZZS)r4a Dictionary-based version :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 size to limit the randomly generated ROI. Suppose all the expected fields specified by `keys` have same shape. 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: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform 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_scale * image spatial size, max_roi_scale * image spatial size + 1)`. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. NTFr`r rr max_roi_sizer random_centerrd random_sizercrerfrgc *t|||||d}tj||||ddSr)rrri) rnr`rrrrrcrerrrorpri/ zRandSpatialCropd.__init__NTFFF)r`r rrrrrrdrrdrcrdrerdrfrgrrororrpr4 s%r4cr)r3aB Dictionary-based version :py:class:`monai.transforms.RandScaleCrop`. 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. Suppose all the expected fields specified by `keys` have same shape. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform 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)`. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. NTFr`r rr max_roi_scaleSequence[float] | float | Nonerrdrrcrerfrgc rr)rrri) rnr`rrrrrcrerrrorpriZrzRandScaleCropd.__init__r)r`r rrrrrrdrrdrcrdrerdrfrgrrororrpr3=s r3c@sXeZdZdZejZ     d"d#ddZejj d$ddZd%d&ddZ d%d'd d!Z dS)(r5a Dictionary-based version :py:class:`monai.transforms.RandSpatialCropSamples`. 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. Suppose all the expected fields specified by `keys` have same shape, and add `patch_index` to the corresponding metadata. It will return a list of dictionaries for all the 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: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform 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)`. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. Raises: ValueError: When ``num_samples`` is nonpositive. NTFr`r rr num_samplesintrrrrdrrcrerfrgc Cs4t|||t||t||||||d|_dSr)r#rir"rr) rnr`rrrrrrcrerororpris    z RandSpatialCropSamplesd.__init__rqcC||_||j_dSrsrtrrerurororpre zRandSpatialCropSamplesd.lazyrw Any | NonecCs|jjtdd|_dS)Nuint32)dtype)Rrandintr&sub_seed)rnrwrororprsz!RandSpatialCropSamplesd.randomizerxry"list[dict[Hashable, torch.Tensor]]csfddt|jjD}t|jjD]}tt|jD] }t||||<q!q||dur:|jn|}| t D]"}|jj t |j dt|j||dD] \}}||||<qZqC|S)Ncg|]}tqSror{.0_rwrorp z4RandSpatialCropSamplesd.__call__..)rr)rangerrsetr` differencerrrer|r{rrr enumeraternrwreretirr~imrorrprsz RandSpatialCropSamplesd.__call__r)r`r rrrrrrrrdrrdrcrdrerdrfrgrrs)rwrrfrgrwrxreryrfr) rrrrrrrir"rerrrrorororpr5hs'   r5c sdeZdZdZeddddejddddf d+fdd Zej j d,d!d"Z e d#d$Z d-d.d)d*Z ZS)/r6a Dictionary-based version :py:class:`monai.transforms.CropForeground`. Crop only the foreground object of the expected images. The typical usage is to help training and evaluation if the valid part is small in the whole medical image. The valid part can be determined by any field in the data with `source_key`, for example: - Select values > 0 in image field as the foreground and crop on all fields specified by `keys`. - Select label = 3 in label field as the foreground to crop on all fields specified by `keys`. - Select label > 0 in the third channel of a One-Hot label field as the foreground to crop all `keys` fields. Users can define arbitrary function to select expected foreground from the whole source image or specified channels. And it can also add margin to every dim of the bounding box of foreground object. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NrFrZforeground_start_coordZforeground_end_coordr`r source_keyr select_fnrchannel_indicesIndexSelection | Nonemarginr allow_smallerrd k_divisiblerbr start_coord_key str | None end_coord_keyrcrerfrgc  sX||_| |_| |_td|||||| d| }tj||| | dt|t|j|_ dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` source_key: data source to generate the bounding box of foreground, can be image or label, etc. 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. 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 it also can be a sequence of string, each element corresponds to a key in ``keys``. start_coord_key: key to record the start coordinate of spatial bounding box for foreground. end_coord_key: key to record the end coordinate of spatial bounding box for foreground. allow_missing_keys: don't raise exception if key is missing. 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. )rrrrrrerNro) rrrrrrir)rmr`rb)rnr`rrrrrrrbrrrcre pad_kwargsrrrorpris. zCropForegroundd.__init__rqcCrrsrrurororpre rzCropForegroundd.lazycCdSNTrornrororprequires_current_dataz%CropForegroundd.requires_current_datarwrxryrzc Cst|}||jj||jd\}}|jdur|||j<|jdur&|||j<|dur-|jn|}|||jD]\}}|jj ||||||d||<q6|S)N)img)r box_startbox_endrbre) r{rcompute_bounding_boxrrrrer|rbcrop_pad) rnrwrer}rrr~rrrororprs     zCropForegroundd.__call__)r`r rrrrrrrrrrdrrrbr rrrrrcrdrerdrfrgrrsr)rrrrr%r(rrir"rerpropertyrrrrororrpr6s$=  r6csheZdZdZejZ   d'd(ddZ d)d*fdd Zd+ddZe j j d,dd Z d-d.d%d&Z Z S)/r7aG 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: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` w_key: key for the weight map. The corresponding value will be used as the sampling weights, it should be a single-channel array in size, for example, `(1, spatial_dim_0, spatial_dim_1, ...)` 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. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. See Also: :py:class:`monai.transforms.RandWeightedCrop` rFr`r w_keyrrrrrrcrdrecCs4t|||t||||_t|||d|_dSr)r#rir"rrr)rnr`rrrrcrerororpri<s zRandWeightedCropd.__init__Nrrrrrfc t|||j|||SrsrrrrrrorprJz"RandWeightedCropd.set_random_state weight_mapr rgcCs|j|dSrsrr)rnrrororprQszRandWeightedCropd.randomizerqcCrrsrrurororpreTrzRandWeightedCropd.lazyrwrxryrcsfddt|jjD}t|jjD]}tt|jD] }t||||<q!q|j|jd|dur?|j n|}| D]}t |j|d|dD] \}}||||<qTqF|S)Ncrrorrrrorpr]rz.RandWeightedCropd.__call__..)rFrre) rrrrr`rrrrrer|rrrorrprYs zRandWeightedCropd.__call__)rFF) r`r rrrrrrrcrdrerdr)rrrrrfr7)rr rfrgrrsr)rrrrrrrirrr"rerrrrororrpr7$s   r7cseZdZdZejZ          d8d9ddZ d:d;fd#d$ Z    dd.d/Z e d0d1Z d?d@d6d7ZZS)Ar8a( Dictionary-based version :py:class:`monai.transforms.RandCropByPosNegLabel`. Crop random fixed sized regions with the center being a foreground or background voxel based on the Pos Neg Ratio. Suppose all the expected fields specified by `keys` have same shape, and add `patch_index` to the corresponding metadata. And will return a list of dictionaries for all the cropped images. 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 the expected size, and the cropped results of several images may not have exactly the 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: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` label_key: name of key for label image, this will be used for finding foreground/background. 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 `data[label_key]` 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]. 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_key: if image_key is not None, use ``label == 0 & image > image_threshold`` to select the negative sample(background) center. so the crop center will only exist on valid image area. image_threshold: if enabled image_key, use ``image > image_threshold`` to determine the valid image content area. fg_indices_key: if provided pre-computed foreground indices of `label`, will ignore above `image_key` and `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices_key` and `bg_indices_key` together, expect to be 1 dim array of spatial indices after flattening. a typical usage is to call `FgBgToIndicesd` transform first and cache the results. bg_indices_key: if provided pre-computed background indices of `label`, will ignore above `image_key` and `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices_key` and `bg_indices_key` together, expect to be 1 dim array of spatial indices after flattening. a typical usage is to call `FgBgToIndicesd` 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). allow_missing_keys: don't raise exception if key is missing. 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. ?rNFr`r label_keyrrrposfloatnegrr image_keyrimage_thresholdfg_indices_keybg_indices_keyrrdrcrerfrgc CsNt||| t|| ||_||_| |_| |_t|||||| | d|_dS)N)rrr rr rre) r#rir"rr r r rr)rnr`rrrr rr r r r rrcrerororpris  zRandCropByPosNegLabeld.__init__rrrrcrrsrrrrorprrz'RandCropByPosNegLabeld.set_random_statelabeltorch.Tensor | None fg_indicesNdarrayOrTensor | None bg_indicesimagecCs|jj||||ddS)N)rrrrr)rnrrrrrororprsz RandCropByPosNegLabeld.randomizerqcCrrsrrurororprerzRandCropByPosNegLabeld.lazycCrrrorrororprrz,RandCropByPosNegLabeld.requires_current_datarwrxryrc st||jd}|jd}||j|||jfddt|j j D}t|j j D]}t  t |j D] }t||||<qCq5|durX|jn|}|D]}t|j |d|dD] \}} | |||<qmq_|S)Ncrrorrr}rorprrz3RandCropByPosNegLabeld.__call__..Fr)r{popr r rgetrr rrrrr`rrrer|r) rnrwrerrrrrr~rrorrprs  zRandCropByPosNegLabeld.__call__) rrrNrNNFFF)r`r rrrrrrr rrrr rr rr rr rrrdrcrdrerdrfrgr)rrrrrfr8)NNNN) rrrrrrrrrfrgrrsr)rrrrrrrirrr"rerrrrrrororrpr8ks67 !    r8cseZdZdZejZ           d:d;d d!Z dd-d.Ze j j d?d0d1Z e d2d3Z d@dAd8d9ZZS)Br;a Dictionary-based version :py:class:`monai.transforms.RandCropByLabelClasses`. 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]`:: cropper = RandCropByLabelClassesd( keys=["image", "label"], label_key="label", spatial_size=[3, 3], ratios=[1, 2, 3, 1], num_classes=4, num_samples=2, ) data = { "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]] ]), } result = cropper(data) 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: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` label_key: name of key for label image, this will be used for finding indices of every class. 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. 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_key: if image_key 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_key`, use ``image > image_threshold`` to determine the valid image content area and select class indices only in this area. indices_key: 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. allow_missing_keys: don't raise exception if key is missing. warn: if `True` prints a warning if a class is not present in the label. max_samples_per_class: maximum length of indices 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. NrrFTr`r rrrrratioslist[float | int] | None num_classesrrrr rr r indices_keyrrdrcwarnmax_samples_per_classrerfrgc CsLt||| t||||_||_| |_t|||||| | | |d |_dS)N) rrrrr rrrre)r#rir"rr rrr)rnr`rrrrrr r rrrcrrrerororpriEs   z RandCropByLabelClassesd.__init__rrrcrrsrrrrorprgrz(RandCropByLabelClassesd.set_random_stater torch.Tensorindiceslist[NdarrayOrTensor] | NonerrcCs|jj|||ddS)N)rrrr)rnrrrrororprnsz!RandCropByLabelClassesd.randomizerqcCrrsrrurororpresrzRandCropByLabelClassesd.lazycCrrrorrororprxrz-RandCropByLabelClassesd.requires_current_datarwMapping[Hashable, Any]ryrcst|||j|jd|jfddt|jj D}t|jj D]}t  t |j D] }t ||||<q9q+|durN|jn|}|D]}t|j|d|dD] \}}||||<qcqU|S)Ncrrorrrrorprrz4RandCropByLabelClassesd.__call__..Fr)r{rrrrrr rrrrr`rrrer|rrrorrpr|s( z RandCropByLabelClassesd.__call__) NNrNrNFFTNF)r`r rrrrrrrrrrr rr rrrrrdrcrdrrdrrrerdrfrgr)rrrrrfr;)rrrrrrrfrgrrs)rwr reryrfr)rrrrrrrirrr"rerrrrrrororrpr;s0M #   r;cs0eZdZdZejdejdfdfdd ZZ S)r9a Dictionary-based wrapper of :py:class:`monai.transforms.ResizeWithPadOrCrop`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform 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). 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 It also can be a sequence of string, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. 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. pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Fr`r rrrbr rcrdrrrerfrgc  s6td||d|d|i}tj|||||ddS)N)rrrerro)rrri) rnr`rrbrcrrerZ padcropperrrorpris   zResizeWithPadOrCropd.__init__)r`r rrrbr rcrdrrrerdrfrg) rrrrr(rr'rrirrororrpr9sr9cs:eZdZdZejZdedfdfd d ZdddZZ S)r:a Dictionary-based wrapper of :py:class:`monai.transforms.BoundingRect`. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform bbox_key_postfix: the output bounding box coordinates will be written to the value of `{key}_{bbox_key_postfix}`. select_fn: function to select expected foreground, default is to select values > 0. allow_missing_keys: don't raise exception if key is missing. bboxFr`r bbox_key_postfixrrrrcrdcs$t||t|d|_||_dS)N)r)rrirr!r")rnr`r"rrcrrorpris  zBoundingRectd.__init__rw"Mapping[Hashable, NdarrayOrTensor]rfdict[Hashable, NdarrayOrTensor]cCsZt|}||D]!}|||}|d|j}||vr&td|d|||<q |S)z] See also: :py:class:`monai.transforms.utils.generate_spatial_bounding_box`. rzBounding box data with key z already exists.)r{r|r!r"KeyError)rnrwr}rr!Z key_to_addrororprs zBoundingRectd.__call__)r`r r"rrrrcrd)rwr#rfr$) rrrrrrr%rirrrororrpr:s  r:)pr __future__rcollections.abcrrrrcopyrtypingrnumpynptorch monai.configr r r monai.config.type_definitionsr monai.data.meta_tensorr Zmonai.transforms.croppad.arrayrrrrrrrrrrrrrrrrrmonai.transforms.inversermonai.transforms.traitsr r!monai.transforms.transformr"r#r$monai.transforms.utilsr% monai.utilsr&r'r(r)__all__r*r+r,r-r.r/r0r1r2r4r3r5r6r7r8r;r9r:r<r=r>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrPrQrNrOrRrSrTrUrVrWrXrYr^r_rZr[r\r]rorororpsn     L  :D/41*1/0+WeG ,(