U Ph26@sfdZddlmZddlmZmZmZmZddlm 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/m0Z0m1Z1ddl2m3Z3ddl4m5Z5m6Z6m7Z7m8Z8m9Z9ddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEg6Z:GdFdde0e*e/Z;GdGdde;ZGdJdde0e*e/Z?GdKdde?e1Z@GdLdde?ZAGdMdde?ZBGdNdde?ZCGdOdde@ZDGdPdde@ZEGdQdde1e0e/e-ZFGdRdde?ZGGdSdde1e0e/e-ZHGdTdde1e0e/e-ZIGdUd!d!e1e0e/e-ZJGdVdde;ZKGdWd d e0ZLe;ZMZNe<ZOZPe=ZQZRe>ZSZTe?ZUZVe@ZWZXeAZYZZeBZ[Z\eCZ]Z^eDZ_Z`eEZaZbeFZcZdeGZeZfeHZgZheIZiZjeJZkZleKZmZneLZoZpdS)Xz 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_SEEDMethodPytorchPadModedeprecated_arg_defaultensure_tuple_repPadd SpatialPadd BorderPadd DivisiblePaddCropd RandCropd SpatialCropdCenterSpatialCropdCenterScaleCropdRandScaleCropdRandSpatialCropdRandSpatialCropSamplesdCropForegrounddRandWeightedCropdRandCropByPosNegLabeldResizeWithPadOrCropd BoundingRectdRandCropByLabelClassesdPadDPadDict SpatialPadDSpatialPadDict BorderPadD BorderPadDict DivisiblePadDDivisiblePadDictCropDCropDict RandCropD RandCropDict SpatialCropDSpatialCropDictCenterSpatialCropDCenterSpatialCropDictCenterScaleCropDCenterScaleCropDictRandScaleCropDRandScaleCropDictRandSpatialCropDRandSpatialCropDictRandSpatialCropSamplesDRandSpatialCropSamplesDictCropForegroundDCropForegroundDictRandWeightedCropDRandWeightedCropDictRandCropByPosNegLabelDRandCropByPosNegLabelDictResizeWithPadOrCropDResizeWithPadOrCropDict BoundingRectDBoundingRectDictRandCropByLabelClassesDRandCropByLabelClassesDictc@steZdZdZejZejddfdddddddd d Ze j j ddd d d Z dddddddZ dddddZ 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. Fr rr boolNone)keyspaddermodeallow_missing_keyslazyreturncCs\t|||t|||dkr@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 ValueErrortyperdr*lenrcre)selfrcrdrerfrgrpX/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/croppad/dictionary.pyrj{s  z Padd.__init__valuerhcCs||_t|jtr||j_dSN)_lazyrkrdr"rgrorsrprprqrgs z Padd.lazyNMapping[Hashable, torch.Tensor] bool | Nonedict[Hashable, torch.Tensor]datargrhcCst|}|dkr|jn|}|dkrBt|jtsBtdt|j|||jD]D\}}t|jtr~|j||||d||<qP|j|||d||<qP|S)NTzN'self.padder' must inherit LazyTrait if lazy is True 'self.padder' is of type()rerg)re) dictrgrkrdr rlrm key_iteratorre)ror{rgdlazy_keymrprprq__call__s z Padd.__call__Mapping[Hashable, MetaTensor]dict[Hashable, MetaTensor]r{rhcCs0t|}||D]}|j||||<q|Srt)r|r}rdinverseror{r~rrprprqrsz Padd.inverse)N)__name__ __module__ __qualname____doc__rbackendr(CONSTANTrjr"rgsetterrrrprprprqr+qsc @s8eZdZdZejejddfdddddddd d d Zd S) 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 Sequence[int] | intstrr rarb)rc spatial_sizemethodrerfrgrhc 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. rgrdrerfrgN)rr+rj) rorcrrrerfrgkwargsrdrprprqrjs"zSpatialPadd.__init__N) rrrrr' SYMMETRICr(rrjrprprprqr,s  c@s8eZdZdZejZejddfdddddddd d Zd S) 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 rr rarb)rcspatial_borderrerfrgrhcKs.tf||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. )rrgrN)rr+rj)rorcrrerfrgrrdrprprqrjs%zBorderPadd.__init__N) rrrrrrr(rrjrprprprqr-s c @s>eZdZdZejZejej ddfdddddddd d d Z d S) 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 rr rrarb)rckrerrfrgrhc Ks0tf|||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` )rrrgrN)rr+rj) rorcrrerrfrgrrdrprprqrj#s"zDivisiblePadd.__init__N) rrrrrrr(rr'rrjrprprprqr.sc@sheZdZdZejZddddddddZejj dd d d d ZdddddddZ dddddZ d S)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 rrarccropperrfrgcCs$t|||t||||_dSrt)r#rjr"rrorcrrfrgrprprqrjZs zCropd.__init__rbrrcCs||_t|jtr||j_dSrt)rurkrr"rgrvrprprqrg_s z Cropd.lazyNrwrxryrzcCsDt|}|dkr|jn|}||D]}|j|||d||<q$|SNrg)r|rgr}r)ror{rgr~rrrprprqres zCropd.__call__rrrcCs0t|}||D]}|j||||<q|Srt)r|r}rrrrprprqrlsz Cropd.inverse)FF)N) rrrrrrrjr"rgrrrrprprprqr/IscspeZdZdZejZddddddfdd Zdd d dd fd d ZdddddZdddddddZ Z S)r0a/ 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 rrarcstj||||ddS)Nrrfrg)superrjr __class__rprqrjszRandCropd.__init__N int | Nonenp.random.RandomState | Noneseedstaterhcs,t||t|jtr(|j|||Srt)rset_random_staterkrr$rorrrrprqrs zRandCropd.set_random_statez Sequence[int]rb)img_sizerhcCst|jtr|j|dSrt)rkrr$ randomize)rorrprprqrs zRandCropd.randomizerwrxryrzcCst|}|||}|t|tr,|n |jdd|dkrJ|jn|}|dkrvt|jt svt dt |j| |D]F}t|jt rddini}t|jt r||d<|j||f|||<q|S)NTzP'self.cropper' must inherit LazyTrait if lazy is True 'self.cropper' is of type(rFrg)r| first_keyrrkr peek_pending_shapeshapergrr rlrmr}r$)ror{rgr~ first_itemrrrrprprqrs& zRandCropd.__call__)FF)NN)N) rrrrrrrjrrr __classcell__rprprrqr0ss c s8eZdZdZd dddddddddd fd d ZZS) r1aR 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 zSequence[int] | NonezSequence[slice] | Nonerarb) rc roi_centerroi_size roi_startroi_end roi_slicesrfrgrhc 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)rrrj) rorcrrrrrrfrgrrrprqrjszSpatialCropd.__init__)NNNNNFFrrrrrjrrprprrqr1scs0eZdZdZd ddddddfdd ZZS) r2a 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 rrarb)rcrrfrgrhcs$t||d}tj||||ddSNrr)rrrj)rorcrrfrgrrrprqrjs zCenterSpatialCropd.__init__)FFrrprprrqr2scs0eZdZdZd ddddddfdd ZZS) r3aj 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 Sequence[float] | floatrarb)rc roi_scalerfrgrhcs$t||d}tj||||ddSr)rrrj)rorcrrfrgrrrprqrjs zCenterScaleCropd.__init__)FFrrprprrqr3sc s6eZdZdZd dddddddd d fd d ZZS)r5a 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 rSequence[int] | int | Nonerarb)rcr max_roi_size random_center random_sizerfrgrhc s*t|||||d}tj||||ddSr)rrrj) rorcrrrrrfrgrrrprqrj/s zRandSpatialCropd.__init__)NTFFFrrprprrqr5 s%c s6eZdZdZd dddddddd d fd d ZZS)r4aB 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 rzSequence[float] | float | Nonerarb)rcr max_roi_scalerrrfrgrhc s*t|||||d}tj||||ddSr)rrrj) rorcrrrrrfrgrrrprqrjZs zRandScaleCropd.__init__)NTFFFrrprprrqr4=s c @steZdZdZejZdddddd d d d d d d d Zejj d d dddZddd dddZ dddddddZ dS)r6a 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 rintrrarb) rcr num_samplesrrrrfrgrhc Cs4t|||t||t||||||d|_dSr)r#rjr"rr) rorcrrrrrrfrgrprprqrjs  z RandSpatialCropSamplesd.__init__rrcCs||_||j_dSrtrurrgrvrprprqrgszRandSpatialCropSamplesd.lazyz Any | NonercCs|jjtdd|_dS)Nuint32)dtype)Rrandintr&sub_seed)ror{rprprqrsz!RandSpatialCropSamplesd.randomizerwrx"list[dict[Hashable, torch.Tensor]]rzcsfddt|jjD}t|jjD]6}tt|jD]}t||||<qBq&||dkrt|jn|}| t D]@}|jj |j dt |j||dD]\}}||||<qq|S)Ncsg|] }tqSrpr|.0_r{rprq sz4RandSpatialCropSamplesd.__call__..)rr)rangerrsetrc differencerrrgr}r|rr enumerateror{rgretirrimrprrqrsz RandSpatialCropSamplesd.__call__)NTFFF)N)N) rrrrrrrjr"rgrrrrprprprqr6hs' cseZdZdZeddddddedd dd ejd d ddf d ddddddddddddd fdd Ze j j dddddZ e ddZ d$ddd d!d"d#ZZS)%r7a 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. allow_smallerTFz1.2z1.5) old_default new_defaultsincereplacedNrrZforeground_start_coordZforeground_end_coordr rrzIndexSelection | Nonerrar str | Nonerb) rc source_key select_fnchannel_indicesmarginr k_divisiblerestart_coord_key end_coord_keyrfrgrhc  sX||_| |_| |_tf|||||| 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 `True`. 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. )rrrrrrgrN) rrrrrrjr*rnrcre)rorcrrrrrrrerrrfrg pad_kwargsrrrprqrjs. zCropForegroundd.__init__rrcCs||_||j_dSrtrrvrprprqrg szCropForegroundd.lazycCsdSNTrprorprprqrequires_current_datasz%CropForegroundd.requires_current_datarwrxryrzc Cst|}||jj||jd\}}|jdk r8|||j<|jdk rL|||j<|dkrZ|jn|}|||jD]&\}}|jj ||||||d||<ql|S)N)img)r box_startbox_endrerg) r|rcompute_bounding_boxrrrrgr}recrop_pad) ror{rgr~rrrrrrprprqrs     zCropForegroundd.__call__)N)rrrrr)r%r(rrjr"rgrpropertyrrrrprprrqr7s$.< cseZdZdZejZd ddddddd d d Zd!d dddfdd ZdddddZe j j dddddZ d"ddddddZ Z S)#r8aG 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 rrrra)rcw_keyrrrfrgcCs4t|||t||||_t|||d|_dSr)r#rjr"rrr)rorcrrrrfrgrprprqrj<s  zRandWeightedCropd.__init__Nrrrcs t|||j|||SrtrrrrrrprqrJsz"RandWeightedCropd.set_random_stater rb) weight_maprhcCs|j|dSrtrr)rorrprprqrQszRandWeightedCropd.randomizerrcCs||_||j_dSrtrrvrprprqrgTszRandWeightedCropd.lazyrwrxrrzcsfddt|jjD}t|jjD]6}tt|jD]}t||||<qBq&|j|jd|dkr~|j n|}| D]2}t |j|d|dD]\}}||||<qq|S)Ncsg|] }tqSrprrrrprqr]sz.RandWeightedCropd.__call__..)rFrrg) rrrrrcrrrrrgr}rrrprrqrYs zRandWeightedCropd.__call__)rFF)NN)N)rrrrrrrjrrr"rgrrrrprprrqr8$scseZdZdZejZd'ddd d d d d d d d d d d ddddZd(ddddfdd Zd)ddddddddZe j j d ddddZ e dd Z d*d!d"d#d$d%d&ZZS)+r9a( 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 rrfloatrrrarb)rc label_keyrposnegr image_keyimage_thresholdfg_indices_keybg_indices_keyrrfrgrhc CsNt||| t|| ||_||_| |_| |_t|||||| | d|_dS)N)rrrrrrrg) r#rjr"rrrrrr)rorcrrrrrrrrrrrfrgrprprqrjs zRandCropByPosNegLabeld.__init__rrrcs t|||j|||Srtrrrrprqrsz'RandCropByPosNegLabeld.set_random_statetorch.Tensor | NonezNdarrayOrTensor | None)label fg_indices bg_indicesimagerhcCs|jj||||ddS)N)rrrrr)rorrrrrprprqrsz RandCropByPosNegLabeld.randomizerrcCs||_||j_dSrtrrvrprprqrgszRandCropByPosNegLabeld.lazycCsdSrrprrprprqrsz,RandCropByPosNegLabeld.requires_current_datarwrxrrzc st||jd}|jd}||j|||jfddt|j j D}t|j j D]6}t  t |j D]}t||||<qqj|dkr|jn|}|D]2}t|j |d|dD]\}} | |||<qq|S)Ncsg|] }tqSrprrr~rprqrsz3RandCropByPosNegLabeld.__call__..Fr)r|poprrrgetrrrrrrrcrrrgr}r) ror{rgrrrrrrrrprrqrs  zRandCropByPosNegLabeld.__call__) rrrNrNNFFF)NN)NNNN)N)rrrrrrrjrrr"rgrrrrrrprprrqr9ks67*!   cseZdZdZejZd)ddd d d d d dd dddd dddddZd*d dddfdd Zd+dddddddZe j j ddddd Z e d!d"Z d,d#d$d%d&d'd(ZZS)-r<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 rrzlist[float | int] | Nonerrrrrarb)rcrrratios num_classesrrr indices_keyrrfwarnmax_samples_per_classrgrhc CsLt||| t||||_||_| |_t|||||| | | |d |_dS)N) rrrrrrrrrg)r#rjr"rrrrr)rorcrrrrrrrrrrfrrrgrprprqrjEs  z RandCropByLabelClassesd.__init__rrcs t|||j|||Srtrrrrprqrgsz(RandCropByLabelClassesd.set_random_statez torch.Tensorzlist[NdarrayOrTensor] | Noner)rindicesrrhcCs|jj|||ddS)N)rrrr)rorrrrprprqrnsz!RandCropByLabelClassesd.randomizerrcCs||_||j_dSrtrrvrprprqrgsszRandCropByLabelClassesd.lazycCsdSrrprrprprqrxsz-RandCropByLabelClassesd.requires_current_datazMapping[Hashable, Any]rxrrzcst|||j|jd|jfddt|jj D}t|jj D]6}t  t |j D]}t ||||<qrqV|dkr|jn|}|D]2}t|j|d|dD]\}}||||<qq|S)Ncsg|] }tqSrprrrrprqrsz4RandCropByLabelClassesd.__call__..Fr)r|rrrrrrrrrrrcrrrgr}rrrprrqr|s( z RandCropByLabelClassesd.__call__) NNrNrNFFTNF)NN)NN)N)rrrrrrrjrrr"rgrrrrrrprprrqr<s2M,# c s@eZdZdZejdejdfdddddddd fd d ZZ S) r:a 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 rr rarrb)rcrrerfrrgrhc  s4tf||d|d|i}tj|||||ddS)N)rrrgr)rrrj) rorcrrerfrrgrZ padcropperrrprqrjs zResizeWithPadOrCropd.__init__) rrrrr(rr'rrjrrprprrqr:s csJeZdZdZejZdedfdddddfd d Zd d d ddZZ 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 rrra)rcbbox_key_postfixrrfcs$t||t|d|_||_dS)N)r)rrjrr r )rorcr rrfrrprqrjs zBoundingRectd.__init__z"Mapping[Hashable, NdarrayOrTensor]zdict[Hashable, NdarrayOrTensor]rcCsZt|}||D]B}|||}|d|j}||krLtd|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)ror{r~rr Z key_to_addrprprqrs zBoundingRectd.__call__) rrrrrrr%rjrrrprprrqr;s  )qr __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)r*__all__r+r,r-r.r/r0r1r2r3r5r4r6r7r8r9r<r:r;r=r>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrQrRrOrPrSrTrUrVrWrXrYrZr_r`r[r\r]r^rprprprq s     L  :D/41*1/0+WeG ,(