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edd͍eŃeeeedd?d@gd΍eŃeeed.dMeŃeeeed.dNeŃeeedldeŃeeeedldXd@gdύeŃeeŃZeejdke jɡeej<eeed.dʍedd0dЍeeeejd.dˍedd0dЍeeeddҍedd0dЍeeeejddӍedd0dЍeeed*dgd*d@d=dՍeŃeeeed*dgd*d?d@gd=d֍eŃeeed*d7dd؍eŃeeeedd7dd?d@gdڍeŃeeeddd7dݍeŃeeeeddd7dލeŃeeeddd7ddeŃeeeeddd7ddeŃeeeddd7dd?deŃeeeeddd7dd?deŃdSdS)) annotationsN)deepcopy)glob) TYPE_CHECKING)download_and_extract)AffineAffined AsDiscreteComposeEnsureChannelFirstdFlipFlipd LoadImaged MapTransform Orientation Orientationd Rand3DElasticRand3DElasticdRandFlip RandFlipd Randomizable RandRotate RandRotatedRandZoom RandZoomdRotateRotate90 Rotate90dRotatedScaleIntensityScaleIntensityd SpatialPaddZoomZoomd) BorderPadCenterScaleCropCenterSpatialCropCropForeground DivisiblePadRandCropByLabelClassesRandCropByPosNegLabel RandScaleCropRandSpatialCropRandSpatialCropSamplesRandWeightedCropResizeWithPadOrCrop SpatialCrop SpatialPad) BorderPaddCenterScaleCropdCenterSpatialCropdCropForegroundd DivisiblePaddRandCropByLabelClassesdRandCropByPosNegLabeldRandScaleCropdRandSpatialCropdRandSpatialCropSamplesdRandWeightedCropdResizeWithPadOrCropd SpatialCropd)AdjustContrastForegroundMaskGaussianSharpenGaussianSmooth GibbsNoiseHistogramNormalizeKSpaceSpikeNoise MaskIntensity MedianSmoothNormalizeIntensityRandAdjustContrast RandBiasFieldRandCoarseDropoutRandCoarseShuffleRandGaussianNoiseRandGaussianSharpenRandGaussianSmoothRandGibbsNoiseRandHistogramShiftRandKSpaceSpikeNoiseRandRicianNoiseRandScaleIntensityRandShiftIntensityRandStdShiftIntensitySavitzkyGolaySmoothScaleIntensityRangeScaleIntensityRangePercentilesShiftIntensityStdShiftIntensityThresholdIntensity)AdjustContrastdForegroundMaskdGaussianSharpendGaussianSmoothd GibbsNoisedHistogramNormalizedKSpaceSpikeNoisedMaskIntensityd MedianSmoothDNormalizeIntensitydRandAdjustContrastdRandBiasFielddRandCoarseDropoutdRandCoarseShuffledRandGaussianNoisedRandGaussianSharpendRandGaussianSmoothdRandGibbsNoisedRandHistogramShiftdRandKSpaceSpikeNoisedRandRicianNoisedRandScaleIntensitydRandShiftIntensitydRandStdShiftIntensitydSavitzkyGolaySmoothdScaleIntensityRangedScaleIntensityRangePercentilesdShiftIntensitydStdShiftIntensitydThresholdIntensityd)KeepLargestConnectedComponent LabelFilterLabelToContourRemoveSmallObjects) AsDiscretedKeepLargestConnectedComponentd LabelFilterdLabelToContourdRemoveSmallObjectsd)RandSmoothDeformRandSmoothFieldAdjustContrastRandSmoothFieldAdjustIntensity)RandSmoothDeformdRandSmoothFieldAdjustContrastdRandSmoothFieldAdjustIntensityd)GridDistortion Rand2DElastic RandAffine RandAxisFlipRandGridDistortion RandRotate90ResizeSpacing)GridDistortiondRand2DElasticd RandAffined RandAxisFlipdRandGridDistortiond RandRotate90dResizedSpacingd) CommonKeys) MONAIEnvVars)optional_importTzmatplotlib.pyplotc Cstpt}d}d|d}tj|d}tj||}t|||tt tj|d\}}t t |t |t tjt|ddg}|tj|tj|i} t| |dj} t|| | | f} | | S) zGet the example data to be used. Use MarsAtlas as it only contains 1 image for quick download and that image is parcellated. zMarsAtlas-MNI-Colin27.zipz*https://www.dropbox.com/s/ndz8qtqblkciole/z?dl=1zMarsAtlas-MNI-Colin27z*.nii)r spatial_axesr)rdata_dirtempfilemkdtempospathjoinrsortedrr rr r rIMAGErLABELmaxshaper!) keys cache_dirfnameurlout_pathzip_pathimagelabel transformsdatamax_sizepadderrm/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/utils_create_transform_ims.pyget_datas$   rc Cs t| }|}Wdn1swYd}t|D]\}}d|d|vr.|}nq|dur7td|d}d||vrCdSt|}||d|d||dd |d t|t|dkritt|d }||WddS1swYdS) z Find the documentation for a given transform and if it's missing, add a pointer to the transform's example image. N`z%Couldn't find transform documentationrz.. imagezJ.. image:: https://github.com/Project-MONAI/DocImages/raw/main/transforms/z.png z :alt: example of  w) open readlines enumerate RuntimeErrorrinsertlenAssertionError writelines) Z code_pathtransform_namefcontentsZ doc_startilineZ image_lineZ contents_origrrrupdate_docstrings2      "rcCs:|dkr dd|D}|r|S|r|tjS|tjS)z`If transform requires 2D data, then convert to 2D by selecting the middle of the last dimension.rcSs(i|]\}}||d|jddfqS).r)r).0kvrrr s(z$pre_process_data..)itemsrrr)rndimis_mapis_postrrrpre_process_datas rviewintcCsl|jdkr|}n#|j}dd|D}||d}t||d||<t|t||}|r4tj||dk<|S)zsIf image is 3d, get the central slice. If is already 2d, return as-is. If image is label, set 0 to np.nan. rcSsg|]}td|qSr)slice)rsrrr z get_2d_slice..rr)rrrnpsqueezetuplenan)rris_labeloutrslices_slicerrr get_2d_slices  rcsfddtdDS)zGet the 3 orthogonal views and stack them into 1 image. Requires that all images be same size, but this is taken care of by the `SpatialPadd` earlier. csg|]}t|qSrrrrimrrrr.sz&get_stacked_2d_ims..)rangerrrrget_stacked_2d_ims)srFcsfdd||fDS)zrStack before and after images into 1 image if 3d. Requires that before and after images be the same size. csg|]}t|qSr)rrdrrrr5rz,get_stacked_before_after..r)beforeafterrrrrget_stacked_before_after1srcCstjdditjdt|}t|d}dd|D} tjdd} | j||dd| d } t|D]} t d d || D} t d d || D}t|D]}| | | |f}|j || |d | |d}| d|r{||dkr{tj||d|dkr| rdnd}||d|dkrd|| nd7}||||dks|r|gn|jt|jD] \}}|dkr|dq|g|d|dur|j || |ddddqOq3|d}|D]<\}}||d7}t|tr|d|d7}nt|tjtjfr|d 7}nt|r|d!7}n|t|7}|d"7}qt|dkr3|dd#}|d$7}t j!|d%dd&t|dd'}| j"|d(d)d*| #|t$| dS)+zCSave image to file, ensuring there's no whitespace around the edge.z font.family monospaceZdark_backgroundrcSsg|] }t|djdqSr)floatr)rrrrrr?szsave_image..T) tight_layout)hspacewspace height_ratioscs|]}|VqdSN)minrrrr Czsave_image..csrr)rrrrrrDrgray)cmapvminvmaxequalr)axZAfterZBeforerrFNhsv?nearest)ralpha interpolation(='z[array]z [callable]z, )2 )break_long_wordssubsequent_indent皙?left)xhorizontalalignment)%pltrcParamsupdatestyleuserfigure add_gridspecrrr add_subplotimshow set_aspectcolorbar set_ylabel set_yticksyaxis tick_rightrget_ticklabels set_visible set_xticks set_frame_onr isinstancestrrndarraytorchTensorcallabletextwrapfillsuptitlesavefigclose)imageslabelsfilenamertransform_argsshapesr"nrowncolhsfigspecrowrrcolrr Zy_labelnrtitlerrrrr save_image8sf       $               rDc spttsgr tjntjtdtfddDddDt}djdkr5dnd}|dkr@|dndtdj }t |D]fd dt |D<qMg}|dkrmd}||fSt t |d }t |D]9t fd dD}|j \}} } ||} ||| krt||| | | dd | || | }||qz||fS) zGet image. If is dictionary, extract key. If is list, stack. If both dictionary and list, do both. Also return the image size as string to be used im the imshow. If it's a list, return `N x (H,W,D)`. rcsg|] }r |n|qSrrr)rkeyrrr}zget_images..cSsg|]}|dqSrrrrrrr~rrz x rcsg|] }t|qSrr)rr)rrrrrrrF?csg|]}|qSrrr)rrrrrGr)r+listrrrdictrrr,rrrrfloorasarrayNotImplementedErrorreshapeswapaxesappend) rr num_samplesZnum_orthog_views shape_strrnrowsresultZnindexheightwidthncolsr)rrrrrErr get_imagesrs2 $     ( rXrcCsP|d i|}ts tt|tr t|tr|dn|}||t}|dur,tdtj |d}|j j } | d} tj || } t|t} t t||| |} |t| }t| \}}t|\}}||f}||f}d}| rt| dd^}}t|dd^}}||f}t||| | ||||rttjjj}tj |dd d }t|| dSdS) zCreate an image with the before and after of the transform. Also update the transform's documentation to point to this image.rNztPlease git clone https://github.com/Project-MONAI/DocImages and then set the environment variable `MONAI_DOC_IMAGES`rz.pngTrdocssourceztransforms.rstr)has_matplotlibrr+rrset_random_stater doc_imagesrrr __class____name__rrrXrDpathlibPath__file__parentr) transformr9rrr"Z update_docseedrZout_dirrZ out_fnameout_filerdata_inZdata_trZ images_before before_shapeZ images_after after_shaper6r:r7Z labels_before_Z labels_afterbase_dirZrst_pathrrrcreate_transform_imsB      rl__main__r)prob spatial_axisr)rrnro)ro)rroZRPI)axcodes)rrpg?)rr)rHrH)rrr)rn sigma_rangemagnitude_range shear_range)rrHrzeros) shear_params image_only padding_modebilinearr)rrumoderw)rnrsrw)rrnrsryrw))r)rqrrrnrw)r})rnspacingrrrw)rrnr~rrrwry)rrqrrrnrwryr)rr)rn)rrnr)angle)rrryg?)rnrange_x)rrnrry333333?)zoomg?area)rrry皙?)rnmin_zoommax_zoom?)rrnrrry )minvmaxv)r")rrr)rzr)rnfactors)rrnr@)r)rr) allow_smaller)r source_keyr)rnmeanstd)rrnrr)drr )loc k_intensity)rrr)rr)rnintensity_range)r)rrnrrHrz) window_lengthorder)rrr)r )rr )rr)rnr )rrnr )offset)rr)rr})rnoffsets)rrnr)factor)rr)皙?333333?)rn coeff_range)rrnr) subtrahenddivisor)rrrr) thresholdabovecval)rrrr)a_mina_maxb_minb_max)rrrrr_)lowerupperrr)rrrrr)gamma)rr)rr)rnr)rrnrcC|dkSNrrrrrrNr) mask_data select_fncCrrrrrrrrPr)rmask_keyr)invert)rr)sigma)rr)radius)rr)rnsigma_x)rrnr)r)rnnum_control_points)rrnrr})rnholes spatial_size fill_value)rrnrrr)rnrr)rrnrr)num_bins)rr),rr)r)rr)spatial_border)rr)Krr) roi_centerroi_size)rrr)r)rr)r random_size)rrr)rQrr)rrQrr)rrQ weight_map)rrrQw_key)rrnegrQ)rr label_keyrrQ)rr num_classesratiosrQ)rrrrrrQ) roi_scale)rr) to_onehotr)rr")rrr)r)rrrrrz)applied_labels)rr)rzrzrz)pixdim)rrry)rrry)rrr)min_size)rr)rrrr) num_cells distort_stepsryrw)rrrryrw)gr)rrn distort_limit)gɿr)rrrnrry)rr)rrr)r rand_sizern)rrrrn)rHg@)rrrnr)rrrrnrg?)rrrn def_range grid_mode)rrrrnrr)rr)F)rFTrF) __future__rrr`rr1copyrrtypingrnumpyrr. monai.appsrmonai.transformsrrr r r r r rrrrrrrrrrrrrrrrrrr r!r"r#monai.transforms.croppad.arrayr$r%r&r'r(r)r*r+r,r-r.r/r0r1Z#monai.transforms.croppad.dictionaryr2r3r4r5r6r7r8r9r:r;r<r=r> monai.transforms.intensity.arrayr?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrSrTrUrVrWrXrYrZr[r\Z%monai.transforms.intensity.dictionaryr]r^r_r`rarbrcrdrerfrgrhrirjrkrlrmrnrorprqrrrsrtrurvrwrxryrzmonai.transforms.post.arrayr{r|r}r~Z monai.transforms.post.dictionaryrrrrrZ#monai.transforms.smooth_field.arrayrrrZ(monai.transforms.smooth_field.dictionaryrrrmonai.transforms.spatial.arrayrrrrrrrrZ#monai.transforms.spatial.dictionaryrrrrrrrrmonai.utils.enumsrmonai.utils.miscrmonai.utils.modulermatplotlib.pyplotpyplotrr[rrrrrrrDrXrlr_rrrrrJZ data_binaryastypefloat32rrrrs     |@<  ((    &    :, 5