o  ik@sdZddlmZddlmZddlmZmZmZddl m Z ddl m Z ddl mZddlZddlZdd lmZdd lmZmZdd lmZdd lmZdd lmZmZddlmZm Z m!Z!m"Z"ddl#m$Z$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*m+Z+ddl,m-Z-m.Z.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8m9Z9ddl:m;Z;mZ>e9dde8\Z?Z@gdZAGddde$ZBGddde$ZCGddde%ZDGdd d e$ZEGd!d"d"e%ZFGd#d$d$e$ZGGd%d&d&e%ZHGd'd(d(e%ZIGd)d*d*e$ZJGd+d,d,e$ZKGd-d.d.e$ZLGd/d0d0e%ZMGd1d2d2e%ZNGd3d4d4e%ZOGd5d6d6e%ZPGd7d8d8e%ZQGd9d:d:e$ZRGd;d<dd>e%ZTGd?d@d@e%ZUGdAdBdBe%ZVGdCdDdDe%ZWGdEdFdFe%ZXGdGdHdHe$ZYGdIdJdJe%ZZGdKdLdLe$Z[GdMdNdNe$Z\GdOdPdPe%e'Z]GdQdRdRe$Z^GdSdTdTe%e'Z_GdUdVdVe$e'Z`GdWdXdXe$ZaGdYdZdZeaZbGd[d\d\eaZcGd]d^d^e%ZdGd_d`d`e$ZeGdadbdbe$ZfGdcdddde%ZgGdedfdfe%ZhGdgdhdhe%ZidS)iz@ A collection of "vanilla" transforms for intensity adjustment. ) annotations)abstractmethod)CallableIterableSequence)partial)Any)warnN) DtypeLike)NdarrayOrTensor NdarrayTensor)get_track_meta)UltrasoundConfidenceMap)get_random_patchget_valid_patch_size)GaussianFilterHilbertTransform MedianFilterSavitzkyGolayFilter)RandomizableTransform Transform)Fourier equalize_hist is_positive rescale_array soft_clip)clip percentilewhere)TransformBackends) ensure_tupleensure_tuple_repensure_tuple_sizefall_back_tuple) min_versionoptional_import)convert_data_typeconvert_to_dst_typeconvert_to_tensorget_equivalent_dtypeskimagez0.19.0)(RandGaussianNoiseRandRicianNoiseShiftIntensityRandShiftIntensityStdShiftIntensityRandStdShiftIntensity RandBiasFieldScaleIntensityRandScaleIntensityScaleIntensityFixedMeanRandScaleIntensityFixedMeanNormalizeIntensityThresholdIntensityScaleIntensityRangeClipIntensityPercentilesAdjustContrastRandAdjustContrastScaleIntensityRangePercentiles MaskIntensityDetectEnvelopeSavitzkyGolaySmooth MedianSmoothGaussianSmoothRandGaussianSmoothGaussianSharpenRandGaussianSharpenRandHistogramShift GibbsNoiseRandGibbsNoiseKSpaceSpikeNoiseRandKSpaceSpikeNoiseRandCoarseTransformRandCoarseDropoutRandCoarseShuffleHistogramNormalizeIntensityRemapRandIntensityRemapForegroundMaskComputeHoVerMaps UltrasoundConfidenceMapTransformcsTeZdZdZejejgZdddej dfdddZ ddfdd Z ddddZ Z S)r+u Add Gaussian noise to image. Args: prob: Probability to add Gaussian noise. mean: Mean or “centre” of the distribution. std: Standard deviation (spread) of distribution. dtype: output data type, if None, same as input image. defaults to float32. sample_std: If True, sample the spread of the Gaussian distribution uniformly from 0 to std. 皙?Tprobfloatmeanstddtyper sample_stdboolreturnNonecCs.t||||_||_||_d|_||_dSN)r__init__rWrXrYnoiserZ)selfrUrWrXrYrZrbb/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/intensity/array.pyr_es  zRandGaussianNoise.__init__Nimgr float | Nonecsltd|js dS|jr|jd|jn|j}|jj|dur#|jn|||j d}t ||j d^|_ }dS)NrsizerY) super randomize _do_transformrZRuniformrXnormalrWshaper&rYr`)rardrWrXr`_ __class__rbrcrjts "zRandGaussianNoise.randomizerjcCstt|td}|r|j||dur|jn|d|js|S|jdur%tdt||jd^}}t |j|^}}||S)/ Apply the transform to `img`.  track_metaN)rdrW-please call the `randomize()` function first.rh) r(r rjrWrkr` RuntimeErrorr&rYr')rardrWrjrpr`rbrbrc__call__}s zRandGaussianNoise.__call__) rUrVrWrVrXrVrYr rZr[r\r]r^)rdr rWrer\r]NT)rdr rWrerjr[r\r __name__ __module__ __qualname____doc__rTORCHNUMPYbackendnpfloat32r_rjrx __classcell__rbrbrqrcr+Vs   r+csVeZdZdZejejgZddddddej fdddZ dddZ dd fdd Z Z S)!r,a Add Rician noise to image. Rician noise in MRI is the result of performing a magnitude operation on complex data with Gaussian noise of the same variance in both channels, as described in `Noise in Magnitude Magnetic Resonance Images `_. This transform is adapted from `DIPY `_. See also: `The rician distribution of noisy mri data `_. Args: prob: Probability to add Rician noise. mean: Mean or "centre" of the Gaussian distributions sampled to make up the Rician noise. std: Standard deviation (spread) of the Gaussian distributions sampled to make up the Rician noise. channel_wise: If True, treats each channel of the image separately. relative: If True, the spread of the sampled Gaussian distributions will be std times the standard deviation of the image or channel's intensity histogram. sample_std: If True, sample the spread of the Gaussian distributions uniformly from 0 to std. dtype: output data type, if None, same as input image. defaults to float32. rSrT?FTrUrVrWSequence[float] | floatrX channel_wiser[relativerZrYr r\r]cCsBt||||_||_||_||_||_||_||_||dSr^) rr_rUrWrXrrrZrY)rarUrWrXrrrZrYrbrbrcr_s zRandRicianNoise.__init__rdr c Cst|jtj}|j}|jr|jd|n|}|jj|||dj |dd|_ |jj|||dj |dd|_ t |t jrYt j|j |jd}t j|j |jd}t ||d|dSt||j d|j dS)NrrfFcopydevice)r)rYrndarrayrorZrlrmrnastypeZ_noise1Z_noise2 isinstancetorchTensortensorrsqrt) rardrWrXZdtype_npZim_shape_stdn1n2rbrbrc _add_noises zRandRicianNoise._add_noiserjcs<t|t|jd}|rtd|js|S|jrMt|jt |}t|j t |}t |D]\}}|j ||||j rB||| n||d||<q-|St|jttfs`tdt|jdt|j ttfsstdt|j d|j r|j | n|j }t|ttfstdt|d|j ||j|d}|S)rsrurYN)rWrXz;If channel_wise is False, mean must be a float or int, got .z:If channel_wise is False, std must be a float or int, got z'std must be a float or int number, got )r(r rYrirjrkrr!rWlenrX enumeraterrrintrVrwtypeitem)rardrj_meanridrXrqrbrcrxs( 4 zRandRicianNoise.__call__)rUrVrWrrXrrr[rr[rZr[rYr r\r])rdr rWrVrXrVTrdr rjr[r\r )r{r|r}r~rrrrrrr_rrxrrbrbrqrcr,s   r,c@s4eZdZdZejejgZddd d ZddddZ d S)r-aq Shift intensity uniformly for the entire image with specified `offset`. Args: offset: offset value to shift the intensity of image. safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`. E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`. FoffsetrVsafer[r\r]cC||_||_dSr^)rr)rarrrbrbrcr_ zShiftIntensity.__init__Nrdr recCsBt|td}|dur|jn|}||}t||j|jd^}}|S)rsrtN)datarYr)r(r rr&rYr)rardroutrprbrbrcrxs zShiftIntensity.__call__)F)rrVrr[r\r]r^)rdr rrer\r r{r|r}r~rrrrr_rxrbrbrbrcr-s  r-csJeZdZdZejejgZ ddd dZddfdd Z d d!ddZ Z S)"r.z? Randomly shift intensity with randomly picked offset. FrSoffsetstuple[float, float] | floatrr[rUrVrr\r]cCst||t|ttfrt| |t| |f|_nt|dkr)t d|dt|t|f|_|jd|_ ||_ t |j ||_ dS)a Args: offsets: offset range to randomly shift. if single number, offset value is picked from (-offsets, offsets). safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`. E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`. prob: probability of shift. channel_wise: if True, shift intensity on each channel separately. For each channel, a random offset will be chosen. Please ensure that the first dimension represents the channel of the image if True. rz3offsets should be a number or pair of numbers, got rrN)rr_rrrVminmaxrr ValueError_offsetrr-_shifter)rarrrUrrbrbrcr_ s   zRandShiftIntensity.__init__Nr Any | Nonec`tdjs dSjrfddt|jdD_dSjjj dj dd_dS)Nc(g|]}jjjdjddqSrlowhigh)rlrmr.0rprarbrc )(z0RandShiftIntensity.randomize..rrr) rirjrkrrangerorrlrmrrarrqrrcrj$ ""zRandShiftIntensity.randomizeTrdr factorrerjc Cst|td}|r|||js|S|jrAg}t|D]\}}|||dur,|j|n|j||}||qt |}|S|||durK|jn|j|}|S)a  Apply the transform to `img`. Args: img: input image to shift intensity. factor: a factor to multiply the random offset, then shift. can be some image specific value at runtime, like: max(img), etc. rtN) r(r rjrkrrrrappendrstack) rardrrjrrr out_channelretrbrbrcrx-s  (   zRandShiftIntensity.__call__)FrSF) rrrr[rUrVrr[r\r]r^rrr\r]ry)rdr rrerjr[r\r ) r{r|r}r~rrrrr_rjrxrrbrbrqrcr.s   r.c@sDeZdZdZejejgZddej fdd d Z dddZ dddZ dS)r/a Shift intensity for the image with a factor and the standard deviation of the image by: ``v = v + factor * std(v)``. This transform can focus on only non-zero values or the entire image, and can also calculate the std on each channel separately. Args: factor: factor shift by ``v = v + factor * std(v)``. nonzero: whether only count non-zero values. channel_wise: if True, calculate on each channel separately. Please ensure that the first dimension represents the channel of the image if True. dtype: output data type, if None, same as input image. defaults to float32. FrrVnonzeror[rrYr r\r]cC||_||_||_||_dSr^rrrrY)rarrrrYrbrbrcr_[s zStdShiftIntensity.__init__rdr cCsxt|tjrtj}ttjdd}ntj}tj}|jr|dkn||jt d}| r:|j |||}|||||<|S)NFunbiasedrrh) rrronesrrXrrror[anyr)rardrrXslicesrrbrbrc _stdshiftcs zStdShiftIntensity._stdshiftcCsJt|t|jd}|jrt|D] \}}||||<q|S||}|S)rsr)r(r rYrrr)rardrrrbrbrcrxss zStdShiftIntensity.__call__N) rrVrr[rr[rYr r\r]rdr r\r ) r{r|r}r~rrrrrrr_rrxrbrbrbrcr/Js  r/csReZdZdZejejgZdddej fdddZ ddfdd Z dd ddZ Z S)!r0z Shift intensity for the image with a factor and the standard deviation of the image by: ``v = v + factor * std(v)`` where the `factor` is randomly picked. rSFfactorsrrUrVrr[rrYr r\r]cCst||t|ttfrt| |t| |f|_nt|dkr)t d|dt|t|f|_|jd|_ ||_ ||_ ||_ dS)a Args: factors: if tuple, the randomly picked range is (min(factors), max(factors)). If single number, the range is (-factors, factors). prob: probability of std shift. nonzero: whether only count non-zero values. channel_wise: if True, calculate on each channel separately. dtype: output data type, if None, same as input image. defaults to float32. r3factors should be a number or pair of numbers, got rrN)rr_rrrVrrrrrrrrrY)rarrUrrrYrbrbrcr_s    zRandStdShiftIntensity.__init__Nrrc8td|js dS|jj|jd|jdd|_dSNrrrrirjrkrlrmrrrrqrbrcrj "zRandStdShiftIntensity.randomizeTrdr rjcCsJt|t|jd}|r||js|St|j|j|j|jd}||dS)rsrrrd) r(r rYrjrkr/rrr)rardrjZshifterrbrbrcrxs zRandStdShiftIntensity.__call__) rrrUrVrr[rr[rYr r\r]r^rrrrzrbrbrqrcr0s  r0c@s>eZdZdZejejgZddddej fdddZ dddZ dS)r2z Scale the intensity of input image to the given value range (minv, maxv). If `minv` and `maxv` not provided, use `factor` to scale image by ``v = v * (1 + factor)``. rTrNFminvremaxvrrr[rYr r\r]cC"||_||_||_||_||_dS)a Args: minv: minimum value of output data. maxv: maximum value of output data. factor: factor scale by ``v = v * (1 + factor)``. In order to use this parameter, please set both `minv` and `maxv` into None. channel_wise: if True, scale on each channel separately. Please ensure that the first dimension represents the channel of the image if True. dtype: output data type, if None, same as input image. defaults to float32. N)rrrrrY)rarrrrrYrbrbrcr_s  zScaleIntensity.__init__rdr cst|td}t|dd}jdusjdur5jr)fdd|D}t|}nt|jjjd}nj durA|dj n|}t ||jpK|jdd }|S) z Apply the transform to `img`. Raises: ValueError: When ``self.minv=None`` or ``self.maxv=None`` and ``self.factor=None``. Incompatible values. rtFNcs"g|] }t|jjjdqS)rh)rrrrYrrrrbrcr"z+ScaleIntensity.__call__..rhrdstrYr) r(r rrrrrrrYrr')rardimg_trrrbrrcrxs  zScaleIntensity.__call__) rrerrerrerr[rYr r\r]r r{r|r}r~rrrrrrr_rxrbrbrbrcr2s  r2c@s@eZdZdZejejgZddddej fdddZ ddddZ dS)r4z Scale the intensity of input image by ``v = v * (1 + factor)``, then shift the output so that the output image has the same mean as the input. rFTrrVpreserve_ranger[ fixed_meanrrYr r\r]cCr)a Args: factor: factor scale by ``v = v * (1 + factor)``. preserve_range: clips the output array/tensor to the range of the input array/tensor fixed_mean: subtract the mean intensity before scaling with `factor`, then add the same value after scaling to ensure that the output has the same mean as the input. channel_wise: if True, scale on each channel separately. `preserve_range` and `fixed_mean` are also applied on each channel separately if `channel_wise` is True. Please ensure that the first dimension represents the channel of the image if True. dtype: output data type, if None, same as input image. defaults to float32. N)rrrrrY)rarrrrrYrbrbrcr_s  z ScaleIntensityFixedMean.__init__Nrdr c Cs$|dur|n|j}t|td}t|dd}|jrWg}|D]3}|jr*|}|}|jr5|}||}|d|} |jrB| |} |jrKt | ||} | | qt |} n,|jrb|}|}|jrm|}||}|d|} |jrz| |} |jrt | ||} t | ||jp|jdd} | S)z Apply the transform to `img`. Args: img: the input tensor/array factor: factor scale by ``v = v * (1 + factor)`` NrtFrrr)rr(r rrrrrrWrrrrr'rY) rardrrrrZclip_minZclip_maxmnrrrbrbrcrxs@        z ScaleIntensityFixedMean.__call__) rrVrr[rr[rr[rYr r\r]r^rrrbrbrbrcr4s  r4csNeZdZdZejZddddejfdddZddfdd Z d d!ddZ Z S)"r5a Randomly scale the intensity of input image by ``v = v * (1 + factor)`` where the `factor` is randomly picked. Subtract the mean intensity before scaling with `factor`, then add the same value after scaling to ensure that the output has the same mean as the input. rSrTFrUrVrrrr[rrYr r\r]cCst||t|ttfrt| |t| |f|_nt|dkr%t dt|t|f|_|jd|_ ||_ ||_ ||_ t|j |j |j |j d|_dS)aQ Args: factors: factor range to randomly scale by ``v = v * (1 + factor)``. if single number, factor value is picked from (-factors, factors). preserve_range: clips the output array/tensor to the range of the input array/tensor fixed_mean: subtract the mean intensity before scaling with `factor`, then add the same value after scaling to ensure that the output has the same mean as the input. channel_wise: if True, scale on each channel separately. `preserve_range` and `fixed_mean` are also applied on each channel separately if `channel_wise` is True. Please ensure that the first dimension represents the channel of the image if True. dtype: output data type, if None, same as input image. defaults to float32. rz.factors should be a number or pair of numbers.r)rrrrYN)rr_rrrVrrrrrrrrrYr4scaler)rarUrrrrYrbrbrcr_Vs    z$RandScaleIntensityFixedMean.__init__Nrrcrrrrrqrbrcrj{rz%RandScaleIntensityFixedMean.randomizerdr rjcCs@t|td}|r ||jst||jddS|||jS)rsrtrhr)r(r rjrkr&rYrrrardrjrbrbrcrxs z$RandScaleIntensityFixedMean.__call__) rUrVrrrr[rr[rYr r\r]r^rrr) r{r|r}r~r4rrrr_rjrxrrbrbrqrcr5Ms %r5csJeZdZdZejZddejfdddZddfdd Z ddddZ Z S) r3z| Randomly scale the intensity of input image by ``v = v * (1 + factor)`` where the `factor` is randomly picked. rSFrrrUrVrr[rYr r\r]cCst||t|ttfrt| |t| |f|_nt|dkr)t d|dt|t|f|_|jd|_ ||_ ||_ dS)a Args: factors: factor range to randomly scale by ``v = v * (1 + factor)``. if single number, factor value is picked from (-factors, factors). prob: probability of scale. channel_wise: if True, scale on each channel separately. Please ensure that the first dimension represents the channel of the image if True. dtype: output data type, if None, same as input image. defaults to float32. rrrrN) rr_rrrVrrrrrrrrY)rarrUrrYrbrbrcr_s    zRandScaleIntensity.__init__Nrrcr)Ncrr)rlrmrrrrbrcrrz0RandScaleIntensity.randomize..rrr) rirjrkrrrorrlrmrrrqrrcrjrzRandScaleIntensity.randomizeTrdr rjcCst|td}|r|||jst||jddS|jrBg}t|D]\}}tdd|j ||jd|}| |q#t |}|Stdd|j |jd|}|S)rsrtrhrN)rrrrY) r(r rjrkr&rYrrr2rrrr)rardrjrrrrrrbrbrcrxs   zRandScaleIntensity.__call__) rrrUrVrr[rYr r\r]r^rrr) r{r|r}r~r2rrrr_rjrxrrbrbrqrcr3s  r3csVeZdZdZejgZddejdfd!ddZ d"ddZ d#fdd Z d$d%dd Z Z S)&r1a Random bias field augmentation for MR images. The bias field is considered as a linear combination of smoothly varying basis (polynomial) functions, as described in `Automated Model-Based Tissue Classification of MR Images of the Brain `_. This implementation adapted from `NiftyNet `_. Referred to `Longitudinal segmentation of age-related white matter hyperintensities `_. Args: degree: degree of freedom of the polynomials. The value should be no less than 1. Defaults to 3. coeff_range: range of the random coefficients. Defaults to (0.0, 0.1). dtype: output data type, if None, same as input image. defaults to float32. prob: probability to do random bias field. )rTrSrSdegreer coeff_rangetuple[float, float]rYr rUrVr\r]cCsBt|||dkrtd|d||_||_||_dg|_dS)Nrz%degree should be no less than 1, got rr)rr_rrrrY_coeff)rarrrYrUrbrbrcr_s  zRandBiasField.__init__ spatial_shape Sequence[int]coeffSequence[float]c Cs>t|}t|df|}dd|D}|dkr/||t|d<tjj|d|d|S|dkrgdg}t|dD]"}t|d|D]} t|d|| D] } ||| | gqTqHq>t|dkrm|dd}t |} ||| dddf| dddf| dddff<tjj |d|d|d|St d ) zC products of polynomials as bias field estimations rcSs g|] }tjdd|tjdqS)rrh)rlinspacer)rdimrbrbrcrs z8RandBiasField._generate_random_field..rrr)rrrNzonly supports 2D or 3D fields) rrzeros tril_indices polynomiallegendre leggrid2drrr leggrid3dNotImplementedError) rarrrrankZ coeff_matcoordsptsrjkZnp_ptsrbrbrc_generate_random_fields(    2 z$RandBiasField._generate_random_fieldimg_sizecsbtdjs dSttfddtdt|dD}jj gj |R _ dS)Ncsg|] }j||qSrb)rrrrrbrcrsz+RandBiasField.randomize..r) rirjrkrrprodrrrlrmrtolistr)rarZn_coeffrqrrcrjs *"zRandBiasField.randomizeTrdr rjr[cst|td}|rj|jdddjs|S|j^}tjfddt|Ddd}t|tj ^}}|t |}t ||j pF|j d ^}}|S) rsrtrN)rcs g|] }jjjdqS))rrr)rrrrrarrbrcr$sz*RandBiasField.__call__..raxissrcrrY) r(r rjrorkrrrr&rexpr'rY)rardrj num_channelsZ _bias_fieldsimg_nprprrbrrcrxs   zRandBiasField.__call__) rrrrrYr rUrVr\r])rrrrrrrrr\r]rr)r{r|r}r~rrrrrr_rrjrxrrbrbrqrcr1s r1c@sbeZdZdZejejgZddddej fdddZ e ddZ e ddZ ddddZdddZdS)r6a Normalize input based on the `subtrahend` and `divisor`: `(img - subtrahend) / divisor`. Use calculated mean or std value of the input image if no `subtrahend` or `divisor` provided. This transform can normalize only non-zero values or entire image, and can also calculate mean and std on each channel separately. When `channel_wise` is True, the first dimension of `subtrahend` and `divisor` should be the number of image channels if they are not None. If the input is not of floating point type, it will be converted to float32 Args: subtrahend: the amount to subtract by (usually the mean). divisor: the amount to divide by (usually the standard deviation). nonzero: whether only normalize non-zero values. channel_wise: if True, calculate on each channel separately, otherwise, calculate on the entire image directly. default to False. dtype: output data type, if None, same as input image. defaults to float32. NF subtrahend!Sequence | NdarrayOrTensor | Nonedivisorrr[rrYr r\r]cC"||_||_||_||_||_dSr^)rrrrrY)rarrrrrYrbrbrcr_E  zNormalizeIntensity.__init__cCs<t|tjr t|St|}|dkr|S|S)Nr)rrrrWrrVnumelrxrbrbrcrSs  zNormalizeIntensity._meancCs@t|tjr t|Stj|dd}|dkr|S|S)NFrr)rrrrXrrVrrrrbrbrcrZs  zNormalizeIntensity._stdrdr c Cst|tjd^}}|jr|dk}||}|s|Snd}|}|dur%|n||}t|tjtj frBt ||^}}|durB||}|durH|n| |}t |rY|dkrXd}nt|tjtj frwt ||^}}|durq||}d||dk<|dur|||||<|S|||}|S)NrhrrTr) r&rrrrrrrrrr'risscalar) rardsubdivrprZ masked_img_sub_divrbrbrc _normalizeas:   zNormalizeIntensity._normalizec Cs"t|td}|jp |j}t|}|jr}|jdur.t|j|kr.td|dt|jd|jdurHt|j|krHtd|dt|jd|jjsUt |t j d^}}t |D]"\}}|j ||jdurj|j|nd|jduru|j|ndd||<qYn | ||j|j}t|||dd }|S) zw Apply the transform to `img`, assuming `img` is a channel-first array if `self.channel_wise` is True, rtNzimg has z channels, but subtrahend has z components.z channels, but divisor has rh)rrr)r(r rYrrrrris_floating_pointr&rrrrr') rardrrYZimg_lenrprrrrbrbrcrxs(  zNormalizeIntensity.__call__) rrrrrr[rr[rYr r\r])NNr)r{r|r}r~rrrrrrr_ staticmethodrrrrxrbrbrbrcr60s     "r6c@s2eZdZdZejejgZddd d ZdddZ dS)r7a Filter the intensity values of whole image to below threshold or above threshold. And fill the remaining parts of the image to the `cval` value. Args: threshold: the threshold to filter intensity values. above: filter values above the threshold or below the threshold, default is True. cval: value to fill the remaining parts of the image, default is 0. TrT thresholdrVabover[cvalr\r]cC>t|ttfstdt|d|d||_||_||_dS)Nz-threshold must be a float or int number, got  r)rrrVrrrrr )rarrr rbrbrcr_  zThresholdIntensity.__init__rdr cCsLt|td}|jr||jkn||jk}t|||j}t||jd^}}|S)rsrtrh)r(r rrrr r&rY)rardmaskresrprbrbrcrxs zThresholdIntensity.__call__N)TrT)rrVrr[r rVr\r]rrrbrbrbrcr7s  r7c@s<eZdZdZejejgZdddej fdddZ dddZ dS)r8a Apply specific intensity scaling to the whole numpy array. Scaling from [a_min, a_max] to [b_min, b_max] with clip option. When `b_min` or `b_max` are `None`, `scaled_array * (b_max - b_min) + b_min` will be skipped. If `clip=True`, when `b_min`/`b_max` is None, the clipping is not performed on the corresponding edge. Args: a_min: intensity original range min. a_max: intensity original range max. b_min: intensity target range min. b_max: intensity target range max. clip: whether to perform clip after scaling. dtype: output data type, if None, same as input image. defaults to float32. NFa_minrVa_maxb_minreb_maxrr[rYr r\r]cCs(||_||_||_||_||_||_dSr^r&r'r(r)rrY)rar&r'r(r)rrYrbrbrcr_s   zScaleIntensityRange.__init__rdr cCst|td}|jp |j}|j|jdkr,tdt|jdur$||jS||j|jS||j|j|j}|jdurL|jdurL||j|j|j}|j rWt ||j|j}t ||dd}|S)rsrtrTzDivide by zero (a_min == a_max)Nrhr) r(r rYr'r&r Warningr(r)rr&)rardrYrrbrbrcrxs    zScaleIntensityRange.__call__)r&rVr'rVr(rer)rerr[rYr r\r]rrrbrbrbrcr8s  r8c@sFeZdZdZejejgZdddej fdddZ dddZ dddZ dS)r9a Apply clip based on the intensity distribution of input image. If `sharpness_factor` is provided, the intensity values will be soft clipped according to f(x) = x + (1/sharpness_factor)*softplus(- c(x - minv)) - (1/sharpness_factor)*softplus(c(x - maxv)) From https://medium.com/life-at-hopper/clip-it-clip-it-good-1f1bf711b291 Soft clipping preserves the order of the values and maintains the gradient everywhere. For example: .. code-block:: python :emphasize-lines: 11, 22 image = torch.Tensor( [[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]]) # Hard clipping from lower and upper image intensity percentiles hard_clipper = ClipIntensityPercentiles(30, 70) print(hard_clipper(image)) metatensor([[[2., 2., 3., 4., 4.], [2., 2., 3., 4., 4.], [2., 2., 3., 4., 4.], [2., 2., 3., 4., 4.], [2., 2., 3., 4., 4.], [2., 2., 3., 4., 4.]]]) # Soft clipping from lower and upper image intensity percentiles soft_clipper = ClipIntensityPercentiles(30, 70, 10.) print(soft_clipper(image)) metatensor([[[2.0000, 2.0693, 3.0000, 3.9307, 4.0000], [2.0000, 2.0693, 3.0000, 3.9307, 4.0000], [2.0000, 2.0693, 3.0000, 3.9307, 4.0000], [2.0000, 2.0693, 3.0000, 3.9307, 4.0000], [2.0000, 2.0693, 3.0000, 3.9307, 4.0000], [2.0000, 2.0693, 3.0000, 3.9307, 4.0000]]]) See Also: - :py:class:`monai.transforms.ScaleIntensityRangePercentiles` NFlowerreuppersharpness_factorrr[return_clipping_valuesrYr r\r]cCs|dur |dur td|dur|dks|dkrtd|dur,|dks(|dkr,td|dur<|dur<||kr.rrrr2) r(r rrrr5r'r/r2metarardrrbrrcrxws   z!ClipIntensityPercentiles.__call__)r,rer-rer.rerr[r/r[rYr r\r]r) r{r|r}r~rrrrrrr_r5rxrbrbrbrcr9s . 2r9c@s4eZdZdZejejgZddd d ZddddZ d S)r:aN Changes image intensity with gamma transform. Each pixel/voxel intensity is updated as:: x = ((x - min) / intensity_range) ^ gamma * intensity_range + min Args: gamma: gamma value to adjust the contrast as function. invert_image: whether to invert the image before applying gamma augmentation. If True, multiply all intensity values with -1 before the gamma transform and again after the gamma transform. This behaviour is mimicked from `nnU-Net `_, specifically `this `_ function. retain_stats: if True, applies a scaling factor and an offset to all intensity values after gamma transform to ensure that the output intensity distribution has the same mean and standard deviation as the intensity distribution of the input. This behaviour is mimicked from `nnU-Net `_, specifically `this `_ function. FgammarV invert_imager[ retain_statsr\r]cCr!)Nz)gamma must be a float or int number, got r"r)rrrVrrr<r=r>)rar<r=r>rbrbrcr_r#zAdjustContrast.__init__Nrdr c Cst|td}|dur |n|j}|jr| }|jr!|}|}d}|}||}||t |||||}|jrT||}||d}|||}|jrZ| }|S)zn Apply the transform to `img`. gamma: gamma value to adjust the contrast as function. rtNgHz>g:0yE>) r(r r<r=r>rWrXrrrV) rardr<rsdepsilonimg_minZ img_rangerrbrbrcrxs$    zAdjustContrast.__call__)FF)r<rVr=r[r>r[r\r]r^rrrbrbrbrcr:s   r:csJeZdZdZejZ    ddddZddfdd Zdd ddZZ S)!r;a Randomly changes image intensity with gamma transform. Each pixel/voxel intensity is updated as: x = ((x - min) / intensity_range) ^ gamma * intensity_range + min Args: prob: Probability of adjustment. gamma: Range of gamma values. If single number, value is picked from (0.5, gamma), default is (0.5, 4.5). invert_image: whether to invert the image before applying gamma augmentation. If True, multiply all intensity values with -1 before the gamma transform and again after the gamma transform. This behaviour is mimicked from `nnU-Net `_, specifically `this `_ function. retain_stats: if True, applies a scaling factor and an offset to all intensity values after gamma transform to ensure that the output intensity distribution has the same mean and standard deviation as the intensity distribution of the input. This behaviour is mimicked from `nnU-Net `_, specifically `this `_ function. rS?g@FrUrVr<rr=r[r>r\r]cCst||t|ttfr|dkrtd|d|f|_nt|dkr(tdt|t |f|_d|_ ||_ ||_ t |j |j |j d|_dS)NrCzWif gamma is a number, must greater than 0.5 and value is picked from (0.5, gamma), got rz,gamma should be a number or pair of numbers.r)r=r>)rr_rrrVrr<rrr gamma_valuer=r>r:adjust_contrast)rarUr<r=r>rbrbrcr_s     zRandAdjustContrast.__init__Nrrcrr)rirjrkrlrmr<rDrrqrbrcrjrzRandAdjustContrast.randomizeTrdr rjcCsDt|td}|r ||js|S|jdurtd|||jS)rsrtNz?gamma_value is not set, please call `randomize` function first.)r(r rjrkrDrwrErrbrbrcrxs zRandAdjustContrast.__call__)rSrBFF) rUrVr<rr=r[r>r[r\r]r^rrr) r{r|r}r~r:rr_rjrxrrbrbrqrcr;s r;c@s@eZdZdZejZdddejfdddZdddZ dddZ dS)r<a Apply range scaling to a numpy array based on the intensity distribution of the input. By default this transform will scale from [lower_intensity_percentile, upper_intensity_percentile] to `[b_min, b_max]`, where {lower,upper}_intensity_percentile are the intensity values at the corresponding percentiles of ``img``. The ``relative`` parameter can also be set to scale from [lower_intensity_percentile, upper_intensity_percentile] to the lower and upper percentiles of the output range [b_min, b_max]. For example: .. code-block:: python :emphasize-lines: 11, 22 image = torch.Tensor( [[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]]) # Scale from lower and upper image intensity percentiles # to output range [b_min, b_max] scaler = ScaleIntensityRangePercentiles(10, 90, 0, 200, False, False) print(scaler(image)) metatensor([[[ 0., 50., 100., 150., 200.], [ 0., 50., 100., 150., 200.], [ 0., 50., 100., 150., 200.], [ 0., 50., 100., 150., 200.], [ 0., 50., 100., 150., 200.], [ 0., 50., 100., 150., 200.]]]) # Scale from lower and upper image intensity percentiles # to lower and upper percentiles of the output range [b_min, b_max] rel_scaler = ScaleIntensityRangePercentiles(10, 90, 0, 200, False, True) print(rel_scaler(image)) metatensor([[[ 20., 60., 100., 140., 180.], [ 20., 60., 100., 140., 180.], [ 20., 60., 100., 140., 180.], [ 20., 60., 100., 140., 180.], [ 20., 60., 100., 140., 180.], [ 20., 60., 100., 140., 180.]]]) See Also: - :py:class:`monai.transforms.ScaleIntensityRange` Args: lower: lower intensity percentile. upper: upper intensity percentile. b_min: intensity target range min. b_max: intensity target range max. clip: whether to perform clip after scaling. relative: whether to scale to the corresponding percentiles of [b_min, b_max]. channel_wise: if True, compute intensity percentile and normalize every channel separately. default to False. dtype: output data type, if None, same as input image. defaults to float32. Fr,rVr-r(rer)rr[rrrYr r\r]c Csd|dks|dkr td|dks|dkrtd||_||_||_||_||_||_||_||_dS)NrTr0r1) rr,r-r(r)rrrrY) rar,r-r(r)rrrrYrbrbrcr_Us  z'ScaleIntensityRangePercentiles.__init__rdr cCst||j}t||j}|j}|j}|jr?|jdus|jdur#td|j|j|jd|j}|j|j|jd|j}t|||||j|j d}||}t |dd}|S)Nz6If it is relative, b_min and b_max should not be None.r0r*Frt) rr,r-r(r)rrr8rrYr()rardr&r'r(r)scalarrbrbrcrms   z)ScaleIntensityRangePercentiles._normalizecsZt|td}t|dd}jrtfdd|D}nj|d}t||jddS)rsrtFcr6r7)rrrrbrcrr8z;ScaleIntensityRangePercentiles.__call__..rrr)r(r rrrrr'rYr;rbrrcrxs   z'ScaleIntensityRangePercentiles.__call__N)r,rVr-rVr(rer)rerr[rr[rr[rYr r\r]r) r{r|r}r~r8rrrr_rrxrbrbrbrcr<s> r<c@s8eZdZdZejejgZdefdd d Z ddd dZ dS)r=aP Mask the intensity values of input image with the specified mask data. Mask data must have the same spatial size as the input image, and all the intensity values of input image corresponding to the selected values in the mask data will keep the original value, others will be set to `0`. Args: mask_data: if `mask_data` is single channel, apply to every channel of input image. if multiple channels, the number of channels must match the input data. the intensity values of input image corresponding to the selected values in the mask data will keep the original value, others will be set to `0`. if None, must specify the `mask_data` at runtime. select_fn: function to select valid values of the `mask_data`, default is to select `values > 0`. N mask_dataNdarrayOrTensor | None select_fnrr\r]cCrr^)rGrI)rarGrIrbrbrcr_rzMaskIntensity.__init__rdr cCst|td}|dur|jn|}|durtdt||d^}}||}|jddkrG|jd|jdkrGtd|jdd|jdd t|||d dS) a& Args: mask_data: if mask data is single channel, apply to every channel of input image. if multiple channels, the channel number must match input data. mask_data will be converted to `bool` values by `mask_data > 0` before applying transform to input image. Raises: - ValueError: When both ``mask_data`` and ``self.mask_data`` are None. - ValueError: When ``mask_data`` and ``img`` channels differ and ``mask_data`` is not single channel. rtNzImust provide the mask_data when initializing the transform or at runtime.r rrrzZWhen mask_data is not single channel, mask_data channels must match img, got img channels=z mask_data channels=rr9)r(r rGrr'rIro)rardrGZ mask_data_rprbrbrcrxs  "zMaskIntensity.__call__)rGrHrIrr\r]r^)rdr rGrHr\r ) r{r|r}r~rrrrrr_rxrbrbrbrcr=s  r=c@s.eZdZdZejgZddd d ZdddZdS)r?aQ Smooth the input data along the given axis using a Savitzky-Golay filter. Args: window_length: Length of the filter window, must be a positive odd integer. order: Order of the polynomial to fit to each window, must be less than ``window_length``. axis: Optional axis along which to apply the filter kernel. Default 1 (first spatial dimension). mode: Optional padding mode, passed to convolution class. ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'``. See ``torch.nn.Conv1d()`` for more information. rr window_lengthrorderrmodestrcCs8|dkrtd||_||_||_||_td|_dS)Nraxis must be zero or positive.rT)rrKrLrrMrrr)rarKrLrrMrbrbrcr_szSavitzkyGolaySmooth.__init__rdr r\cCs`t|td}t|dd|_t|j|j|jd|j}||jd d}t ||d^}}|S)z Args: img: array containing input data. Must be real and in shape [channels, spatial1, spatial2, ...]. Returns: array containing smoothed result. rtFrrr9) r(r rrrKrLrrM unsqueezesqueezer')rardZ savgol_filterZsmoothedrrprbrbrcrxs  zSavitzkyGolaySmooth.__call__N)rr)rKrrLrrrrMrNr r{r|r}r~rrrr_rxrbrbrbrcr?s   r?c@s.eZdZdZejgZddd d ZdddZdS)r>aU Find the envelope of the input data along the requested axis using a Hilbert transform. Args: axis: Axis along which to detect the envelope. Default 1, i.e. the first spatial dimension. n: FFT size. Default img.shape[axis]. Input will be zero-padded or truncated to this size along dimension ``axis``. rNrrn int | Noner\r]cCs |dkrtd||_||_dS)NrrO)rrrS)rarrSrbrbrcr_s zDetectEnvelope.__init__rdr cCs\t|td}t|tj^}}t|jd|j}||d d }t ||d^}}|S)z Args: img: numpy.ndarray containing input data. Must be real and in shape [channels, spatial1, spatial2, ...]. Returns: np.ndarray containing envelope of data in img along the specified axis. rtrrrJ) r(r r&rrrrrSrPrQabsr')rardrrpZhilbert_transformrrbrbrcrxs  zDetectEnvelope.__call__)rN)rrrSrTr\r])rdr rRrbrbrbrcr>s  r>c@s.eZdZdZejgZddddZdd d Zd S)r@a Apply median filter to the input data based on specified `radius` parameter. A default value `radius=1` is provided for reference. See also: :py:func:`monai.networks.layers.median_filter` Args: radius: if a list of values, must match the count of spatial dimensions of input data, and apply every value in the list to 1 spatial dimension. if only 1 value provided, use it for all spatial dimensions. rradiusSequence[int] | intr\r]cCs ||_dSr^)rV)rarVrbrbrcr_)s zMedianSmooth.__init__rdr c Csft|td}t|tjtjd^}}|jd}t|j|}t ||d}||}t |||j d^}}|S)Nrtrhr) spatial_dimsr) r(r r&rrrVndimr!rVrr'rY) rardrrprXrZmedian_filter_instanceout_trrbrbrcrx,s   zMedianSmooth.__call__N)r)rVrWr\r]rdr r\r rRrbrbrbrcr@s  r@c@s.eZdZdZejgZddd d ZdddZdS)rAa: Apply Gaussian smooth to the input data based on specified `sigma` parameter. A default value `sigma=1.0` is provided for reference. Args: sigma: if a list of values, must match the count of spatial dimensions of input data, and apply every value in the list to 1 spatial dimension. if only 1 value provided, use it for all spatial dimensions. approx: discrete Gaussian kernel type, available options are "erf", "sampled", and "scalespace". see also :py:meth:`monai.networks.layers.GaussianFilter`. rerfsigmarapproxrNr\r]cCrr^r^r_)rar^r_rbrbrcr_GrzGaussianSmooth.__init__rdr cst|td}t|tjtjd^}t|jtr#fdd|jD}n tj |jj d}t j d||j d}|dd}t|||jd ^}}|S) Nrtrhcsg|] }tj|jdqS)r)r as_tensorr)rsrrbrcrPz+GaussianSmooth.__call__..rrr_rr)r(r r&rrrVrr^rrarrrYr_rPrQr'rY)rardrpr^gaussian_filterr[rrbrcrcrxKs zGaussianSmooth.__call__N)rr])r^rr_rNr\r]r\rRrbrbrbrcrA7s  rAcsLeZdZdZejZ     ddddZdd fdd Zd!d"ddZZ S)#rBaD Apply Gaussian smooth to the input data based on randomly selected `sigma` parameters. Args: sigma_x: randomly select sigma value for the first spatial dimension. sigma_y: randomly select sigma value for the second spatial dimension if have. sigma_z: randomly select sigma value for the third spatial dimension if have. prob: probability of Gaussian smooth. approx: discrete Gaussian kernel type, available options are "erf", "sampled", and "scalespace". see also :py:meth:`monai.networks.layers.GaussianFilter`. g?g?rSr]sigma_xrsigma_ysigma_zrUrVr_rNr\r]cCsLt||||_||_||_||_|jd|_|jd|_|jd|_dS)Nr) rr_rhrirjr_ryz)rarhrirjrUr_rbrbrcr_js   zRandGaussianSmooth.__init__Nrrcsttd|js dS|jj|jd|jdd|_|jj|jd|jdd|_|jj|j d|j dd|_ dSr) rirjrkrlrmrhrrirkrjrlrrqrbrcrj|s "zRandGaussianSmooth.randomizeTrdr rjr[cCsTt|td}|r ||js|St|j|j|jf|jdd}t ||j d|S)Nrtrvalsrr`) r(r rjrkr"rrkrlrYrAr_)rardrjr^rbrbrcrxszRandGaussianSmooth.__call__)rgrgrgrSr]) rhrrirrjrrUrVr_rNr\r]r^rrr) r{r|r}r~rArr_rjrxrrbrbrqrcrBZs  rBc@s6eZdZdZejgZ    ddddZdddZdS)rCa& Sharpen images using the Gaussian Blur filter. Referring to: http://scipy-lectures.org/advanced/image_processing/auto_examples/plot_sharpen.html. The algorithm is shown as below .. code-block:: python blurred_f = gaussian_filter(img, sigma1) filter_blurred_f = gaussian_filter(blurred_f, sigma2) img = blurred_f + alpha * (blurred_f - filter_blurred_f) A set of default values `sigma1=3.0`, `sigma2=1.0` and `alpha=30.0` is provide for reference. Args: sigma1: sigma parameter for the first gaussian kernel. if a list of values, must match the count of spatial dimensions of input data, and apply every value in the list to 1 spatial dimension. if only 1 value provided, use it for all spatial dimensions. sigma2: sigma parameter for the second gaussian kernel. if a list of values, must match the count of spatial dimensions of input data, and apply every value in the list to 1 spatial dimension. if only 1 value provided, use it for all spatial dimensions. alpha: weight parameter to compute the final result. approx: discrete Gaussian kernel type, available options are "erf", "sampled", and "scalespace". see also :py:meth:`monai.networks.layers.GaussianFilter`. @r>@r]sigma1rsigma2alpharVr_rNr\r]cCrr^rqrrrsr_)rarqrrrsr_rbrbrcr_s zGaussianSharpen.__init__rdr c st|td}t|tjtjd^}fddjjfD\}}|d}||}|j || d}t |||j d^}}|S)Nrtrhc3s.|]}tjd|jdjVqdS)rreN)rrYr_tor)rr^rrarbrc s  z+GaussianSharpen.__call__..rr) r(r r&rrrrqrrrPrsrQr'rY) rardrpZgf1Zgf2Z blurred_fZfilter_blurred_fr[rrbrvrcrxs   zGaussianSharpen.__call__N)rorrpr]) rqrrrrrsrVr_rNr\r]r\rRrbrbrbrcrCs  rCcsTeZdZdZejZ         d$d%ddZd&d'fdd Zd(d)d"d#ZZ S)*rDa Sharpen images using the Gaussian Blur filter based on randomly selected `sigma1`, `sigma2` and `alpha`. The algorithm is :py:class:`monai.transforms.GaussianSharpen`. Args: sigma1_x: randomly select sigma value for the first spatial dimension of first gaussian kernel. sigma1_y: randomly select sigma value for the second spatial dimension(if have) of first gaussian kernel. sigma1_z: randomly select sigma value for the third spatial dimension(if have) of first gaussian kernel. sigma2_x: randomly select sigma value for the first spatial dimension of second gaussian kernel. if only 1 value `X` provided, it must be smaller than `sigma1_x` and randomly select from [X, sigma1_x]. sigma2_y: randomly select sigma value for the second spatial dimension(if have) of second gaussian kernel. if only 1 value `Y` provided, it must be smaller than `sigma1_y` and randomly select from [Y, sigma1_y]. sigma2_z: randomly select sigma value for the third spatial dimension(if have) of second gaussian kernel. if only 1 value `Z` provided, it must be smaller than `sigma1_z` and randomly select from [Z, sigma1_z]. alpha: randomly select weight parameter to compute the final result. approx: discrete Gaussian kernel type, available options are "erf", "sampled", and "scalespace". see also :py:meth:`monai.networks.layers.GaussianFilter`. prob: probability of Gaussian sharpen. rCrrCg$@rpr]rSsigma1_xrsigma1_ysigma1_zsigma2_xrsigma2_ysigma2_zrsr_rNrUrVr\r]c Csjt|| ||_||_||_||_||_||_||_||_ d|_ d|_ d|_ d|_ d|_d|_d|_dSr^)rr_rzr{r|r}r~rrsr_x1y1z1x2y2z2a) rarzr{r|r}r~rrsr_rUrbrbrcr_s  zRandGaussianSharpen.__init__Nrrcs:td|js dS|jj|jd|jdd|_|jj|jd|jdd|_|jj|j d|j dd|_ t |j t sD|j |jfn|j }t |jt sS|j|jfn|j}t |jt sb|j|j fn|j}|jj|d|dd|_|jj|d|dd|_|jj|d|dd|_|jj|jd|jdd|_dSr)rirjrkrlrmrzrr{rr|rrr}rr~rrrrrsr)rarr}r~rrqrbrcrjs "zRandGaussianSharpen.randomizeTrdr rjr[cCst|td}|r ||js|S|jdus&|jdus&|jdus&|jdur*tdt |j |j |j f|j dd}t |j|j|jf|j dd}t|||j|jd|S)Nrtrvrrmrt)r(r rjrkrrrrrwr"rrrrYrCr_)rardrjrqrrrbrbrcrx s(zRandGaussianSharpen.__call__) rxrxrxrCrCrCryr]rS)rzrr{rr|rr}rr~rrrrsrr_rNrUrVr\r]r^rrr) r{r|r}r~rCrr_rjrxrrbrbrqrcrDs rDcsReZdZdZejejgZddd d ZdddZ d d!fdd Z d"d#ddZ Z S)$rEa Apply random nonlinear transform to the image's intensity histogram. Args: num_control_points: number of control points governing the nonlinear intensity mapping. a smaller number of control points allows for larger intensity shifts. if two values provided, number of control points selecting from range (min_value, max_value). prob: probability of histogram shift. rSnum_control_pointstuple[int, int] | intrUrVr\r]cCsxt||t|tr|dkrtd||f|_nt|dkr#tdt|dkr-tdt|t|f|_||dS)Nrz7num_control_points should be greater than or equal to 3z:num_control points should be a number or a pair of numbers) rr_rrrrrrr)rarrUrbrbrcr_(s     zRandHistogramShift.__init__rr xpfpc Cst|tjrtnt}t|tjrt|||S|dd|dd|dd|dd}|dd||dd}||d|dd}||dt |d}|||d|||j }|d|||dk<|d|||dk<|S)Nrr) rrrrrinterp searchsortedreshaperrro) rarrrnsmbindicesfrbrbrcr8s 0"zRandHistogramShift.interpNrrcstd|js dS|j|jd|jdd}tdd||_t |j|_ t d|dD]}|j |j |d|j |d|j |<q0dS)Nrr) rirjrkrlrandintrrrreference_control_pointsrfloating_control_pointsrrm)rarZnum_control_pointrrqrbrcrjIs  zRandHistogramShift.randomizeTrdrjr[c Cst|td}|r ||js|S|jdus|jdur tdt|dd}||}}||kr=t d|d|St |j|d^}}t |j|d^}}||||} ||||} | || | }t ||ddS)NrtrvFz(The image's intensity is a single value zD. The original image is simply returned, no histogram shift is done.r9r) r(r rjrkrrrwrrr r'r) rardrjrrAZimg_maxrrpypZreference_control_points_scaledZfloating_control_points_scaledrbrbrcrxUs(  zRandHistogramShift.__call__)rrS)rrrUrVr\r])rr rr rr r\r r^rrr) r{r|r}r~rrrrr_rrjrxrrbrbrqrcrEs   rEc@s<eZdZdZejejgZddddZdd d Z dddZ dS)rFa The transform applies Gibbs noise to 2D/3D MRI images. Gibbs artifacts are one of the common type of type artifacts appearing in MRI scans. The transform is applied to all the channels in the data. For general information on Gibbs artifacts, please refer to: `An Image-based Approach to Understanding the Physics of MR Artifacts `_. `The AAPM/RSNA Physics Tutorial for Residents `_ Args: alpha: Parametrizes the intensity of the Gibbs noise filter applied. Takes values in the interval [0,1] with alpha = 0 acting as the identity mapping. rSrsrVr\r]cCs"|dks|dkr td||_dS)Nrrz.alpha must take values in the interval [0, 1].)rrs)rarsrbrbrcr_s zGibbsNoise.__init__rdr cCsft|td}t|dd}t|jdd}|||}||}|||}t|||jd^}}|S)NrtFrr) r(r rro shift_fourier _apply_maskinv_shift_fourierr'rY)rardrn_dimsrrrprbrbrcrxs    zGibbsNoise.__call__rc Cs|jdd}d|jt|tdd}t|dd}tjtdd|D}ddt||D}tt |}||k}tj |d|jd d d }t |t j r`t|t j |jd ^}} ||} | S) zBuilds and applies a mask on the spatial dimensions. Args: k: k-space version of the image. Returns: masked version of the k-space image. rNr@css|]}td|VqdSrN)slicerrrbrbrcrwsz)GibbsNoise._apply_mask..cSsg|] \}}||dqS)rrb)rcoordcrbrbrcrrdz*GibbsNoise._apply_mask..rrr)rorsrrrarrayogridtuplezipsumrepeatrrrr&r) rarrorZcenterrZcoords_from_center_sqZdist_from_centerr$rpZk_maskedrbrbrcrs" zGibbsNoise._apply_maskN)rS)rsrVr\r]r)rr r\r ) r{r|r}r~rrrrr_rxrrbrbrbrcrFos    rFcs@eZdZdZejZddd d Zdfdd ZddddZZ S)rGa Naturalistic image augmentation via Gibbs artifacts. The transform randomly applies Gibbs noise to 2D/3D MRI images. Gibbs artifacts are one of the common type of type artifacts appearing in MRI scans. The transform is applied to all the channels in the data. For general information on Gibbs artifacts, please refer to: https://pubs.rsna.org/doi/full/10.1148/rg.313105115 https://pubs.rsna.org/doi/full/10.1148/radiographics.22.4.g02jl14949 Args: prob (float): probability of applying the transform. alpha (float, Sequence(float)): Parametrizes the intensity of the Gibbs noise filter applied. Takes values in the interval [0,1] with alpha = 0 acting as the identity mapping. If a length-2 list is given as [a,b] then the value of alpha will be sampled uniformly from the interval [a,b]. 0 <= a <= b <= 1. If a float is given, then the value of alpha will be sampled uniformly from the interval [0, alpha]. rSrTrrUrVrsfloat | Sequence[float]r\r]cCst|tr d|f}t|}t|dkrtd|ddks#|ddkr'td|d|dkr3td||_d|_tj||ddS) Nrrzalpha length must be 2.rz-alpha must take values in the interval [0, 1]z!When alpha = [a,b] we need a < b.rrU) rrVr rrrs sampled_alpharr_)rarUrsrbrbrcr_s  zRandGibbsNoise.__init__rrcs6td|js dS|j|jd|jd|_dS)zr (1) Set random variable to apply the transform. (2) Get alpha from uniform distribution. Nrr)rirjrkrlrmrsrrrqrbrcrjs  zRandGibbsNoise.randomizeTrdr rjr[cCs4t|td}|r|d|js|St|j|S)Nrt)r(r rjrkrFrrrbrbrcrxs  zRandGibbsNoise.__call__)rSr)rUrVrsrr\r])rrr\r]rrdr rjr[) r{r|r}r~rFrr_rjrxrrbrbrqrcrGs   rGc@sFeZdZdZejejgZddddZdd d Z dddZ dddZ dS)rHa Apply localized spikes in `k`-space at the given locations and intensities. Spike (Herringbone) artifact is a type of data acquisition artifact which may occur during MRI scans. For general information on spike artifacts, please refer to: `AAPM/RSNA physics tutorial for residents: fundamental physics of MR imaging `_. `Body MRI artifacts in clinical practice: A physicist's and radiologist's perspective `_. Args: loc: spatial location for the spikes. For images with 3D spatial dimensions, the user can provide (C, X, Y, Z) to fix which channel C is affected, or (X, Y, Z) to place the same spike in all channels. For 2D cases, the user can provide (C, X, Y) or (X, Y). k_intensity: value for the log-intensity of the `k`-space version of the image. If one location is passed to ``loc`` or the channel is not specified, then this argument should receive a float. If ``loc`` is given a sequence of locations, then this argument should receive a sequence of intensities. This value should be tested as it is data-dependent. The default values are the 2.5 the mean of the log-intensity for each channel. Example: When working with 4D data, ``KSpaceSpikeNoise(loc = ((3,60,64,32), (64,60,32)), k_intensity = (13,14))`` will place a spike at `[3, 60, 64, 32]` with `log-intensity = 13`, and one spike per channel located respectively at `[: , 64, 60, 32]` with `log-intensity = 14`. Nloctuple | Sequence[tuple] k_intensitySequence[float] | float | NonecCst||_||_t|tr$t|dtstdt|t|kr$tdt|jdtr:|durtddSdSdS)NrzZIf a sequence is passed to k_intensity, then a sequence of locations must be passed to loczJThere must be one intensity_factor value for each tuple of indices in loc.)r rrrrrr)rarrrbrbrcr_s  $ zKSpaceSpikeNoise.__init__rdr r\c Cst|td}||t|jdkrtdt|jdtr1t|jdkr1t|jdkr1tdt|jdt rNt|jdkrNt t t|jdkrNtdt|jdd }| ||}t|t jret nt}|||d }||}|j}|d urt|j|tt| dd d }t|jdt rt|jt|D] \}} |||| qn|||j||||d |}t||||d^}} |S)zX Args: img: image with dimensions (C, H, W) or (C, H, W, D) rtrz Image needs a channel direction.rrzCInput images of dimension 4 need location tuple to be length 3 or 4rN绽|=r@y?r9)r(r _check_indicesrrorwrrrrrmaprrrrlogrUanglerrrWrrr _set_spiker r'r) rardrrliblog_absphaseridxvalrprbrbrcrx-s0 ,2  "zKSpaceSpikeNoise.__call__r]cst|j}t|dts|g}tt|D]t|t|jkr-dgt||<qtt|jD]|jtfdd|DkrStdd|jdq5dS)zHelper method to check consistency of self.loc and input image. Raises assertion error if any index in loc is out of bounds.rc3s|]}|VqdSr^rb)rrrrbrcrwcsz2KSpaceSpikeNoise._check_indices..zThe index value at position z of one of the tuples in loc = z$ is out of bounds for current image.N) listrrrrrrorr)rardrrbrrcrVs  zKSpaceSpikeNoise._check_indicesrrrrrcCst|jt|krt|tr||dn|||<dSt|jdkr9t|dkr9||dd|d|d|df<dSt|jdkrUt|dkrW||dd|d|df<dSdSdS)z Helper function to introduce a given intensity at given location. Args: k: intensity array to alter. idx: index of location where to apply change. val: value of intensity to write in. rrrNrr)rrorr)rarrrrbrbrcrhs "$zKSpaceSpikeNoise._set_spiker^)rrrrr)r\r])rr rrrr) r{r|r}r~rrrrr_rxrrrbrbrbrcrHs "   )rHcs^eZdZdZejZ   ddfd d ZddddZd fdd Zd!ddZ d"ddZ Z S)#rIaF Naturalistic data augmentation via spike artifacts. The transform applies localized spikes in `k`-space, and it is the random version of :py:class:`monai.transforms.KSpaceSpikeNoise`. Spike (Herringbone) artifact is a type of data acquisition artifact which may occur during MRI scans. For general information on spike artifacts, please refer to: `AAPM/RSNA physics tutorial for residents: fundamental physics of MR imaging `_. `Body MRI artifacts in clinical practice: A physicist's and radiologist's perspective `_. Args: prob: probability of applying the transform, either on all channels at once, or channel-wise if ``channel_wise = True``. intensity_range: pass a tuple (a, b) to sample the log-intensity from the interval (a, b) uniformly for all channels. Or pass sequence of intervals ((a0, b0), (a1, b1), ...) to sample for each respective channel. In the second case, the number of 2-tuples must match the number of channels. Default ranges is `(0.95x, 1.10x)` where `x` is the mean log-intensity for each channel. channel_wise: treat each channel independently. True by default. Example: To apply `k`-space spikes randomly with probability 0.5, and log-intensity sampled from the interval [11, 12] for each channel independently, one uses ``RandKSpaceSpikeNoise(prob=0.5, intensity_range=(11, 12), channel_wise=True)`` rSNTrUrVintensity_range(Sequence[Sequence[float] | float] | Nonerr[csJ||_||_g|_g|_|durt|dtr|stdt|dS)NrzSWhen channel_wise = False, intensity_range should be a 2-tuple (low, high) or None.) rrsampled_k_intensity sampled_locsrrrrir_)rarUrrrqrbrcr_szRandKSpaceSpikeNoise.__init__rdr rjcCs|jdurt|jdtrt|j|jdkrtdt|td}g|_g|_ |r5| |}| |||j s:|St |j |j|S)z Apply transform to `img`. Assumes data is in channel-first form. Args: img: image with dimensions (C, H, W) or (C, H, W, D) NrziIf intensity_range is a sequence of sequences, then there must be one (low, high) tuple for each channel.rt)rrrrrorwr(r rr_make_sequencerjrkrH)rardrjrrbrbrcrxs   zRandKSpaceSpikeNoise.__call__Sequence[Sequence[float]]r\r]cstdjs dSjr?t|D]*\}}j|ftfdd|jDj j ||d||dqdStfdd|jddDfddt |jdD_t |dtrqfd d|D_ dSj |d|dgt|_ dS) a Helper method to sample both the location and intensity of the spikes. When not working channel wise (channel_wise=False) it use the random variable ``self._do_transform`` to decide whether to sample a location and intensity. When working channel wise, the method randomly samples a location and intensity for each channel depending on ``self._do_transform``. Nc3|] }jd|VqdSrrlrrrrbrcrwz1RandKSpaceSpikeNoise.randomize..rrc3rrrrrrbrcrwrcsg|]}|fqSrbrbr)spatialrbrcrsz2RandKSpaceSpikeNoise.randomize..cs"g|] }j|d|dqS)rr)rlrm)rprrbrcrr)rirjrkrrrrrrorrlrmrrrr)rardrrchanrq)rarrcrjs &( &zRandKSpaceSpikeNoise.randomizercCsD|jdur ||St|jdtst|jf|jdSt|jS)zZ Formats the sequence of intensities ranges to Sequence[Sequence[float]]. Nr)r_set_default_rangerrr ro)rarrbrbrcrs   z#RandKSpaceSpikeNoise._make_sequencecCst|jdd}|||}t|tjrtnt}|||d}| |t t | dd}t|tjr<| d}t dd|DS) zr Sets default intensity ranges to be sampled. Args: img: image to transform. rNrrrcpucss |] }|d|dfVqdS)gffffff?g?Nrbrrbrbrcrw sz:RandKSpaceSpikeNoise._set_default_range..) rrorrrrrrabsoluterWrrru)rardrrmodrZ shifted_meansrbrbrcrs   z'RandKSpaceSpikeNoise._set_default_range)rSNT)rUrVrrrr[rr)rdr rrr\r])rr r\r)rdr r\r) r{r|r}r~rHrr_rxrjrrrrbrbrqrcrIys"   rIcsVeZdZdZejgZ   d d!ddZd"fdd Ze d#ddZ d$d%ddZ Z S)&rJa Randomly select coarse regions in the image, then execute transform operations for the regions. It's the base class of all kinds of region transforms. Refer to papers: https://arxiv.org/abs/1708.04552 Args: holes: number of regions to dropout, if `max_holes` is not None, use this arg as the minimum number to randomly select the expected number of regions. spatial_size: spatial size of the regions to dropout, if `max_spatial_size` is not None, use this arg as the minimum spatial size to randomly select size for every region. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of input img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. max_holes: if not None, define the maximum number to randomly select the expected number of regions. max_spatial_size: if not None, define the maximum spatial size to randomly select size for every region. if some components of the `max_spatial_size` are non-positive values, the transform will use the corresponding components of input img size. For example, `max_spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. prob: probability of applying the transform. NrSholesr spatial_sizerW max_holesrTmax_spatial_sizeSequence[int] | int | NonerUrVr\r]cCs>t|||dkrtd||_||_||_||_g|_dS)Nrz'number of holes must be greater than 0.)rr_rrrrr hole_coords)rarrrrrUrbrbrcr_ s  zRandCoarseTransform.__init__rrcstdjs dStj|g_jdurjn j jjd}t |D]3}j durItj |t fddt t |Dt|}jtdft||jq+dS)Nrc3s,|]}jj||ddVqdS)rrNrrmax_sizerargrbrcrw8 s*z0RandCoarseTransform.randomize..)rirjrkr#rrrrrlrrrrrrrrr)rarZ num_holesrp valid_sizerqrrcrj. s  &   " "zRandCoarseTransform.randomizerd np.ndarraycCstd|jjd)zV Transform the randomly selected `self.hole_coords` in input images. z Subclass z must implement this method.)rrrr{rardrbrbrc_transform_holes< sz$RandCoarseTransform._transform_holesTr rjr[cCs`t|td}|r||jdd|js|St|tj^}}|j|d}t ||d^}}|S)NrtrrrJ) r(r rjrorkr&rrrr')rardrjr rprrrbrbrcrxD s zRandCoarseTransform.__call__)NNrS) rrrrWrrTrrrUrVr\r]r )rdrr\rrr) r{r|r}r~rrrr_rjrrrxrrbrbrqrcrJ s  rJcs8eZdZdZ     ddfdd ZdddZZS)rKa Randomly coarse dropout regions in the image, then fill in the rectangular regions with specified value. Or keep the rectangular regions and fill in the other areas with specified value. Refer to papers: https://arxiv.org/abs/1708.04552, https://arxiv.org/pdf/1604.07379 And other implementation: https://albumentations.ai/docs/api_reference/augmentations/transforms/ #albumentations.augmentations.transforms.CoarseDropout. Args: holes: number of regions to dropout, if `max_holes` is not None, use this arg as the minimum number to randomly select the expected number of regions. spatial_size: spatial size of the regions to dropout, if `max_spatial_size` is not None, use this arg as the minimum spatial size to randomly select size for every region. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of input img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. dropout_holes: if `True`, dropout the regions of holes and fill value, if `False`, keep the holes and dropout the outside and fill value. default to `True`. fill_value: target value to fill the dropout regions, if providing a number, will use it as constant value to fill all the regions. if providing a tuple for the `min` and `max`, will randomly select value for every pixel / voxel from the range `[min, max)`. if None, will compute the `min` and `max` value of input image then randomly select value to fill, default to None. max_holes: if not None, define the maximum number to randomly select the expected number of regions. max_spatial_size: if not None, define the maximum spatial size to randomly select size for every region. if some components of the `max_spatial_size` are non-positive values, the transform will use the corresponding components of input img size. For example, `max_spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. prob: probability of applying the transform. TNrSrrrrW dropout_holesr[ fill_value"tuple[float, float] | float | NonerrTrrrUrVr\r]csHtj|||||d||_t|ttfrt|dkrtd||_dS)N)rrrrrUrzEfill value should contain 2 numbers if providing the `min` and `max`.) rir_rrrrrrr)rarrrrrrrUrqrbrcr_q s   zRandCoarseDropout.__init__rdrcCs|jdur ||fn|j}|jr;|jD] }t|ttfr2|jj |d|d||j d||<q|||<q|}|St|ttfrW|jj |d|d|j dj |j dd}nt ||}|jD]}||||<q`|S)z Fill the randomly selected `self.hole_coords` in input images. Please note that we usually only use `self.R` in `randomize()` method, here is a special case. NrrrfFr)rrrrrrrrrlrmrorrYr full_like)rardrhrrbrbrcr s  & *  z"RandCoarseDropout._transform_holes)TNNNrS)rrrrWrr[rrrrTrrrUrVr\r]rdr)r{r|r}r~r_rrrbrbrqrcrKR s"rKc@seZdZdZdddZdS)rLa Randomly select regions in the image, then shuffle the pixels within every region. It shuffles every channel separately. Refer to paper: Kang, Guoliang, et al. "Patchshuffle regularization." arXiv preprint arXiv:1707.07103 (2017). https://arxiv.org/abs/1707.07103 Args: holes: number of regions to dropout, if `max_holes` is not None, use this arg as the minimum number to randomly select the expected number of regions. spatial_size: spatial size of the regions to dropout, if `max_spatial_size` is not None, use this arg as the minimum spatial size to randomly select size for every region. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of input img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. max_holes: if not None, define the maximum number to randomly select the expected number of regions. max_spatial_size: if not None, define the maximum spatial size to randomly select size for every region. if some components of the `max_spatial_size` are non-positive values, the transform will use the corresponding components of input img size. For example, `max_spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. prob: probability of applying the transform. rdrcCsN|jD]!}t||D]\}}|}|j|||j|||<q q|S)z Shuffle the content of randomly selected `self.hole_coords` in input images. Please note that we usually only use `self.R` in `randomize()` method, here is a special case. )rrflattenrlshufflerro)rardrrrZ patch_channelrbrbrcr s  z"RandCoarseShuffle._transform_holesNr)r{r|r}r~rrbrbrbrcrL srLc@s<eZdZdZejgZddddejfdddZ ddddZ dS)rMa? Apply the histogram normalization to input image. Refer to: https://github.com/facebookresearch/CovidPrognosis/blob/master/covidprognosis/data/transforms.py#L83. Args: num_bins: number of the bins to use in histogram, default to `256`. for more details: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html. min: the min value to normalize input image, default to `0`. max: the max value to normalize input image, default to `255`. mask: if provided, must be ndarray of bools or 0s and 1s, and same shape as `image`. only points at which `mask==True` are used for the equalization. can also provide the mask along with img at runtime. dtype: data type of the output, if None, same as input image. default to `float32`. rNnum_binsrrrr$rHrYr r\r]cCrr^)rrrr$rY)rarrrr$rYrbrbrcr_ rzHistogramNormalize.__init__rdr cCst|td}t|tj^}}|dur|n|j}d}|dur&t|tj^}}t|||j|j|j d}t |||j p:|j d^}}|S)Nrt)rdr$rrrr) r(r r&rrr$rrrrr'rY)rardr$r rpmask_nprrrbrbrcrx szHistogramNormalize.__call__) rrrrrrr$rHrYr r\r]r^rdr r$rHr\r ) r{r|r}r~rrrrrr_rxrbrbrbrcrM s rMcs.eZdZdZddfdd Zdd dZZS)rNa Transform for intensity remapping of images. The intensity at each pixel is replaced by a new values coming from an intensity remappping curve. The remapping curve is created by uniformly sampling values from the possible intensities for the input image and then adding a linear component. The curve is the rescaled to the input image intensity range. Intended to be used as a means to data augmentation via: :py:class:`monai.transforms.RandIntensityRemap`. Implementation is described in the work: `Intensity augmentation for domain transfer of whole breast segmentation in MRI `_. Args: kernel_size: window size for averaging operation for the remapping curve. slope: slope of the linear component. Easiest to leave default value and tune the kernel_size parameter instead. ffffff? kernel_sizersloperVcst||_||_dSr^)rir_rr)rarrrqrbrcr_ s  zIntensityRemap.__init__rd torch.Tensorr\cCst|td}t|dd}t|}t|j|t|d|j }tj j |j dd| d }tt|t|}||j|7}||||||}t|t|}t|||d^}}|S)8 Args: img: image to remap. rtFr)striderr9)r(r runiquer from_numpyrlchoicerrnn AvgPool1drPrQarangerrr bucketizerr')rardimg_Zvals_to_sampler`gridZ index_imgrprbrbrcrx s " ,zIntensityRemap.__call__)rr)rrrrVrdrr\rr{r|r}r~r_rxrrbrbrqrcrN srNcs.eZdZdZddd dZdfdd ZZS)rOa Transform for intensity remapping of images. The intensity at each pixel is replaced by a new values coming from an intensity remappping curve. The remapping curve is created by uniformly sampling values from the possible intensities for the input image and then adding a linear component. The curve is the rescaled to the input image intensity range. Implementation is described in the work: `Intensity augmentation for domain transfer of whole breast segmentation in MRI `_. Args: prob: probability of applying the transform. kernel_size: window size for averaging operation for the remapping curve. slope: slope of the linear component. Easiest to leave default value and tune the kernel_size parameter instead. channel_wise: set to True to treat each channel independently. rSrrTrUrVrrrrr[cCs$tj||d||_||_||_dS)Nr)rr_rrr)rarUrrrrbrbrcr_B s zRandIntensityRemap.__init__rdrr\csrtdttdjr7jr&tfddtt DSt j j j jgS)rNrtcs2g|]}tjjj jg|qSrb)rNrrlrrrrdrarbrcrR s$z/RandIntensityRemap.__call__..)rirjr(r rkrrrrrrNrrlrrrrqrrcrxH s    "zRandIntensityRemap.__call__)rSrrT)rUrVrrrrVrr[rrrbrbrqrcrO+ s rOc@sHeZdZdZejejgZ   ddd dZddZ ddZ dddZ dS)rPa Creates a binary mask that defines the foreground based on thresholds in RGB or HSV color space. This transform receives an RGB (or grayscale) image where by default it is assumed that the foreground has low values (dark) while the background has high values (white). Otherwise, set `invert` argument to `True`. Args: threshold: an int or a float number that defines the threshold that values less than that are foreground. It also can be a callable that receives each dimension of the image and calculate the threshold, or a string that defines such callable from `skimage.filter.threshold_...`. For the list of available threshold functions, please refer to https://scikit-image.org/docs/stable/api/skimage.filters.html Moreover, a dictionary can be passed that defines such thresholds for each channel, like {"R": 100, "G": "otsu", "B": skimage.filter.threshold_mean} hsv_threshold: similar to threshold but HSV color space ("H", "S", and "V"). Unlike RBG, in HSV, value greater than `hsv_threshold` are considered foreground. invert: invert the intensity range of the input image, so that the dtype maximum is now the dtype minimum, and vice-versa. otsuNFr#dict | Callable | str | float | int hsv_threshold*dict | Callable | str | float | int | Noneinvertr[r\r]cCsi|_|dur0t|tr|D] \}}|||qn||d||d||d|dur]t|trK|D] \}}|||q=n||d||d||ddd|jD|_|jtd r{t d |jd ||_ dS) NrlGBHSVcSsi|] \}}|dur||qSr^rb)rrvrbrbrc sz+ForegroundMask.__init__..ZRGBHSVzBThreshold for at least one channel of RGB or HSV needs to be set. z is provided.) thresholdsrdictitems_set_thresholdr-keys isdisjointsetrr)rarrrrMthrbrbrcr_s s.          zForegroundMask.__init__cCsrt|r ||j|<dSt|trttjd||j|<dSt|tt fr/t||j|<dSt dt |d)N threshold_zB`threshold` should be either a callable, string, or float number, z was given.) callabler rrNgetattrr*filtersr,rVrrr)rarrMrbrbrcr  s zForegroundMask._set_thresholdcCs |j|}t|r||S|Sr^)r getr)raimagerMrrbrbrc_get_threshold s zForegroundMask._get_thresholdrr c Cs.t|td}t|tj^}}|jrtj|}g}|j t dsLt |dd}t |dD]\}}|||}|rFt|||k}q2|||j t dstjj|dd} t |dd} t | dD]\}}|||}|rt| ||k} ql|| t|jdd} t| |ddS) NrtRGBrHSVr) channel_axisrrJ)r(r r&rrrr*utilr rrr zeros_likerr logical_orrcolorZrgb2hsvrallr') rarZimg_rgbrpZ foregroundsZrgb_foregroundrdrMrZimg_hsvZhsv_foregroundr$rbrbrcrx s0     zForegroundMask.__call__)rNF)rrrrrr[r\r])rr ) r{r|r}r~rrrrr_r rrxrbrbrbrcrP] s   rPcs.eZdZdZd dfdd Zdd d ZZS)rQaCompute horizontal and vertical maps from an instance mask It generates normalized horizontal and vertical distances to the center of mass of each region. Input data with the size of [1xHxW[xD]], which channel dim will temporarily removed for calculating coordinates. Args: dtype: the data type of output Tensor. Defaults to `"float32"`. Return: A torch.Tensor with the size of [2xHxW[xD]], which is stack horizontal and vertical maps rrYr r\r]cst||_dSr^)rir_rY)rarYrqrbrcr_ s  zComputeHoVerMaps.__init__r$r c Cs(t|tjd}|j|jdd}|j|jdd}|d}tj|D]b}|j dddf|j d}|j dddf|j d}||dkt | <||dkt |<||dkt | <||dkt |<||||j k<||||j k<q#tt||gtd}|S)NrTrrrt)r&rrrrYrQr*measure regionpropsrcentroidaminamaxlabelr( concatenater ) rar$Z instance_maskh_mapZv_mapregionZv_disth_distZhv_mapsrbrbrcrx s zComputeHoVerMaps.__call__)r)rYr r\r])r$r rrbrbrqrcrQ s rQc@s8eZdZdZ        ddddZddddZdS)rRa2Compute confidence map from an ultrasound image. This transform uses the method introduced by Karamalis et al. in https://doi.org/10.1016/j.media.2012.07.005. It generates a confidence map by setting source and sink points in the image and computing the probability for random walks to reach the source for each pixel. The official code is available at: https://campar.in.tum.de/Main/AthanasiosKaramalisCode Args: alpha (float, optional): Alpha parameter. Defaults to 2.0. beta (float, optional): Beta parameter. Defaults to 90.0. gamma (float, optional): Gamma parameter. Defaults to 0.05. mode (str, optional): 'RF' or 'B' mode data. Defaults to 'B'. sink_mode (str, optional): Sink mode. Defaults to 'all'. If 'mask' is selected, a mask must be when calling the transform. Can be one of 'all', 'mid', 'min', 'mask'. use_cg (bool, optional): Use Conjugate Gradient method for solving the linear system. Defaults to False. cg_tol (float, optional): Tolerance for the Conjugate Gradient method. Defaults to 1e-6. Will be used only if `use_cg` is True. cg_maxiter (int, optional): Maximum number of iterations for the Conjugate Gradient method. Defaults to 200. Will be used only if `use_cg` is True. rV@皙?rr Fư>rsrVbetar<cg_tol cg_maxiterrc Cs||_||_||_||_||_||_||_||_|jdvr&td|jd|jdvr4td|jdt |j|j|j|j|j|j|j|j|_ dS)N)rZRFzUnknown mode: z#. Supported modes are 'B' and 'RF'.)r midrr$zUnknown sink mode: z5. Supported modes are 'all', 'mid', 'min' and 'mask'.) rsr/r<rM sink_modeuse_cgr0r1rr_compute_conf_map) rarsr/r<rMr3r4r0r1rbrbrcr_ s"      z)UltrasoundConfidenceMapTransform.__init__Nrdr r$rHr\cCs|jdkr |dur td|jddkrtdt|td}t|tj^}}|d}d}|durFt|tj td}t|tj^}}|d}t |jd krTtj |dd }|durb|j|jkrbtd | ||}t |tjurtt|}|S) a+Compute confidence map from an ultrasound image. Args: img (ndarray or Tensor): Ultrasound image of shape [1, H, W] or [1, D, H, W]. If the image has channels, they will be averaged before computing the confidence map. mask (ndarray or Tensor, optional): Mask of shape [1, H, W]. Defaults to None. Must be provided when sink mode is 'mask'. The non-zero values of the mask are used as sink points. Returns: ndarray or Tensor: Confidence map of shape [1, H, W]. r$Nz1A mask must be provided when sink mode is 'mask'.rrzr@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrbrbrbrcs         ,9YE6=7YBD]p9?Lz6-)#68STL> NK(/72a)