U Ph@sddlmZddlZddlmZmZmZmZddlm Z ddl Z ddl Z ddl mZmZmZddlmZddlmZmZddlmZmZmZdd lmZmZdd lmZmZm Z m!Z!m"Z"dd l#m$Z$e"d d e!\Z%Z&e"ddd\Z'Z&e$(Z)GdddeZ*GdddeeZ+GdddeZ,GdddeZ-GdddeeZ.GdddeZ/GdddeZ0Gdd d eZ1Gd!d"d"eZ2Gd#d$d$eZ3Gd%d&d&eZ4dS)') annotationsN)CallableHashableIterableSequence)Any)IndexSelectionKeysCollectionNdarrayOrTensor)GaussianFilter)Resize SpatialCrop) MapTransform Randomizable Transform)generate_spatial_bounding_box is_positive)InterpolateMode ensure_tupleensure_tuple_rep min_versionoptional_import)PostFixzskimage.measurez0.14.2zscipy.ndimage.morphologydistance_transform_cdt)namec@s:eZdZdZddddddZdd Zd d d d dZdS)FindAllValidSlicesdz Find/List all valid slices in the label. Label is assumed to be a 4D Volume with shape CDHW, where C=1. Args: label: key to the label source. sids: key to store slices indices having valid label map. labelsidsstrrrcCs||_||_dSNr)selfrrr"S/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/apps/deepgrow/transforms.py__init__.szFindAllValidSlicesd.__init__cCsBg}t|jdD]$}t|d|dkr||qt|S)Nr)rangeshapenpsumappendasarray)r!rrsidr"r"r#_apply2s  zFindAllValidSlicesd._applyrdictdatareturncCst|}t||jtjr(||jn||j}|jddkrRtd|jdt|jdkrrtd|jd| |}|dk rt|r|||j <|S)Nrr%z5Only supports single channel labels, got label shape !z5Only supports label with shape CDHW, got label shape ) r. isinstancertorchTensornumpyr' ValueErrorlenr-r)r!r0drrr"r"r#__call__9s*  zFindAllValidSlicesd.__call__N)rr)__name__ __module__ __qualname____doc__r$r-r;r"r"r"r#r$s rc@s@eZdZdZddddddd d d Zd d ZddZddZdS)AddInitialSeedPointda Add random guidance as initial seed point for a given label. Note that the label is of size (C, D, H, W) or (C, H, W) The guidance is of size (2, N, # of dims) where N is number of guidance added. # of dims = 4 when C, D, H, W; # of dims = 3 when (C, H, W) Args: label: label source. guidance: key to store guidance. sids: key that represents list of valid slice indices for the given label. sid: key that represents the slice to add initial seed point. If not present, random sid will be chosen. connected_regions: maximum connected regions to use for adding initial points. rguidancerr,rint)rrArr,connected_regionscCs(||_||_||_d|_||_||_dSr )rsids_keysid_keyr,rArD)r!rrArr,rDr"r"r#r$Ys zAddInitialSeedPointd.__init__cCsT||jd}||jd}|dk rF|dks4||krJ|jj|dd}nd}||_dS)NF)replace)getrFrERchoicer,)r!r0r,rr"r"r# randomizehszAddInitialSeedPointd.randomizec Cst|jdkrdnd}dg|d}|}|dk rN|dkrNd}|d|tj}|dktj}|dkrztj|tddn|}t |dkrt dg}t d|dkrdn|j dD]}|dkr||ktj}t |dkr||qt|} t| d } t|dkd} |jj| d| | t | | d } | | } tt| |jd}| d|d<|dks|dkr||q||d||d |dgqt||gt|gS) Nr%r?) backgroundzNot a valid Label?sizep)r9r'r(newaxisastypefloat32measurerrCmaxAssertionErrorr&rDr)r*rflattenexpwhererIrJr+ unravel_index transposetolist)r!rr, dimensionsdefault_guidancedims blobs_labels pos_guidanceridxdistance probabilityidxseeddstgr"r"r#r-rs8    $    zAddInitialSeedPointd._applycCsDt|}||t|||j|jjtdd ||j <|S)NFcopy) r.rKjsondumpsr-rr,rWrCrarA)r!r0r:r"r"r#r;s .zAddInitialSeedPointd.__call__N)rrArr,rB)r<r=r>r?r$rKr-r;r"r"r"r#r@Hs &r@c@s>eZdZdZddddddd d Zd d Zd dZddZdS)AddGuidanceSignaldaW Add Guidance signal for input image. Based on the "guidance" points, apply gaussian to them and add them as new channel for input image. Args: image: key to the image source. guidance: key to store guidance. sigma: standard deviation for Gaussian kernel. number_intensity_ch: channel index. imagerArMr%rrCrsrAsigmanumber_intensity_chcCs||_||_||_||_dSr rt)r!rsrArurvr"r"r#r$szAddGuidanceSignald.__init__cCsNt|jdkrdnd}t|tjr*|n|}t|trBt|n|}|dkr~tj t||jd|jd|jdftj d}n&tj t||jd|jdftj d}|j}t |D]\}}|D]}t t |dkrq|dkrVtdtt|d|dd} tdtt|d|dd} tdtt|d|dd} d ||| | | f<qtdtt|d|dd} tdtt|d|dd} d ||| | f<qt||dkrt||} tt| j|jd } | | dd} | dd} | ||<||t||t||t||||<q|S) NrLrMrUrNdtyperr%rQ)ru)r9r'r4r(ndarrayrarrploadszerosrX enumerateanyr+rZminrCr5tensorr ru unsqueezesqueezedetachcpur7)r!rsrArbsignalsshapeig_ipointp1p2p3 signal_tensor pt_gaussianr"r"r# _get_signals60&      8zAddGuidanceSignald._get_signalcCsP|||}t|tjr(|}|dd|jdf}tj ||gddS)Nr.axis) rr4r5r6rrr7rvr( concatenate)r!rsrArr"r"r#r-s   zAddGuidanceSignald._applycCs2t|}||j}||j}|||||j<|Sr )r.rsrAr-)r!r0r:rsrAr"r"r#r;s   zAddGuidanceSignald.__call__N)rsrArMr%)r<r=r>r?r$rr-r;r"r"r"r#rrs  " rrc@s@eZdZdZdddddddZed d Zd d Zd dZdS)FindDiscrepancyRegionsda Find discrepancy between prediction and actual during click interactions during training. Args: label: key to label source. pred: key to prediction source. discrepancy: key to store discrepancies found between label and prediction. rpred discrepancyrrrrcCs||_||_||_dSr r)r!rrrr"r"r#r$sz FindDiscrepancyRegionsd.__init__cCsP|dktj}|dktj}||}|dktj}|dktj}||gS)NrOr)rWr(rX)rr disparity pos_disparity neg_disparityr"r"r#rs z!FindDiscrepancyRegionsd.disparitycCs |||Sr )r)r!rrr"r"r#r-szFindDiscrepancyRegionsd._applycCs2t|}||j}||j}|||||j<|Sr )r.rrr-r)r!r0r:rrr"r"r#r;s   z FindDiscrepancyRegionsd.__call__N)rrr) r<r=r>r?r$ staticmethodrr-r;r"r"r"r#rs   rc@sNeZdZdZdddddddZdd d Zd d ZddZddZddZ d S)AddRandomGuidanceda Add random guidance based on discrepancies that were found between label and prediction. input shape is as below: Guidance is of shape (2, N, # of dim) Discrepancy is of shape (2, C, D, H, W) or (2, C, H, W) Probability is of shape (1) Args: guidance: key to guidance source. discrepancy: key that represents discrepancies found between label and prediction. probability: key that represents click/interaction probability. rArrir)rArricCs||_||_||_d|_dSr )rArri_will_interact)r!rArrir"r"r#r$szAddRandomGuidanced.__init__NcCs,||j}|jjddg|d|gd|_dS)NTFrQ)rT)rirIrJr)r!r0rir"r"r#rK"s zAddRandomGuidanced.randomizecCst|}t|d}t|dkd}t|dkdkr|jj|d||t||d}||}tt ||j  d}|d|d<|SdS)NrQrr%rR) rr\r(r]r^r)rIrJr+r_r'r`ra)r!rrhrirjrkrlrmr"r"r# find_guidance&s $  z AddRandomGuidanced.find_guidancecCsx|sdS|d}|d}t|dk}t|dk}t|t|k}|r^|r^||dfS|st|rtd||fSdS)N)NNrr%)r(r)r)r!rZ will_interact pos_discrZ neg_discrZcan_be_positiveZcan_be_negativeZ correct_posr"r"r# add_guidance4szAddRandomGuidanced.add_guidancecCst|tjr|n|}t|tr,t|n|}|||j\}}|rl|d ||d dgt ||r|d dgt ||d |t tj |t dS)Nrr%rNrx)r4r(rzrarrpr{rrr*r9rqr+rC)r!rArposnegr"r"r#r-FszAddRandomGuidanced._applycCs<t|}||j}||j}|||||||j<|Sr )r.rArrKr-)r!r0r:rArr"r"r#r;Ss    zAddRandomGuidanced.__call__)rArri)N) r<r=r>r?r$rKrrr-r;r"r"r"r#r s  rcsbeZdZdZeddddeddddd f d d d d ddddd d d d d dddfdd ZddZZS)SpatialCropForegroundda Crop only the foreground object of the expected images. Difference VS :py:class:`monai.transforms.CropForegroundd`: 1. If the bounding box is smaller than spatial size in all dimensions then this transform will crop the object using box's center and spatial_size. 2. This transform will set "start_coord_key", "end_coord_key", "original_shape_key" and "cropped_shape_key" in data[{key}_{meta_key_postfix}] 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. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.MapTransform` source_key: data source to generate the bounding box of foreground, can be image or label, etc. spatial_size: minimal spatial size of the image patch e.g. [128, 128, 128] to fit in. 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 allow the image size to be smaller than box size, default to `True`. if the margined size is bigger than image size, will pad with specified `mode`. meta_keys: explicitly indicate the key of the corresponding metadata dictionary. for example, for data with key `image`, the metadata by default is in `image_meta_dict`. the metadata is a dictionary object which contains: filename, original_shape, etc. it can be a sequence of string, map to the `keys`. if None, will try to construct meta_keys by `key_{meta_key_postfix}`. meta_key_postfix: if meta_keys is None, use `{key}_{meta_key_postfix}` to fetch/store the metadata according to the key data, default is `meta_dict`, the metadata is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. 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. original_shape_key: key to record original shape for foreground. cropped_shape_key: key to record cropped shape for foreground. allow_missing_keys: don't raise exception if key is missing. NrTforeground_start_coordforeground_end_coordforeground_original_shapeforeground_cropped_shapeFr rzSequence[int] | np.ndarrayrzIndexSelection | NonerCboolKeysCollection | NoneNone)keys source_key spatial_size select_fnchannel_indicesmargin allow_smaller meta_keysmeta_key_postfixstart_coord_key end_coord_keyoriginal_shape_keycropped_shape_keyallow_missing_keysr1cst||||_t||_||_||_||_||_|dkrNt dt |j nt ||_ t |j t |j krttdt | t |j |_| |_| |_| |_| |_dSNz.meta_keys should have the same length as keys.)superr$rlistrrrrrrr9rrrr8rrrrr)r!rrrrrrrrrrrrrr __class__r"r#r$s "zSpatialCropForegroundd.__init__c CsHt|}t||j|j|j|j|j\}}ttj ||gddj t dd}tt ||j t dd}t t||jrt||jd}tdd|jD}tdd|jD}n t||d }|||j|jD]p\}} } | p|d | } ||| |j<||| |j<||j|| |j<|||} | j|| |j<| ||<q|S) NrrFrn roi_centerroi_sizecSsg|] }|jqSr"start.0sr"r"r# sz3SpatialCropForegroundd.__call__..cSsg|] }|jqSr"stoprr"r"r#rs roi_startroi_end_)r.rrrrrrrr(meanrWrCsubtractalllessrr arrayslices key_iteratorrrrrr'rr) r!r0r: box_startbox_endcenter current_sizecropperkeymeta_keyrrsr"r"r#r;s0    zSpatialCropForegroundd.__call__) r<r=r>r?rDEFAULT_POST_FIXr$r; __classcell__r"r"rr#r]s60"rc @sTeZdZdZdddddddd ef d d d d d d d d d d d ddZddZddZd S)AddGuidanceFromPointsda Add guidance based on user clicks. We assume the input is loaded by LoadImaged and has the shape of (H, W, D) originally. Clicks always specify the coordinates in (H, W, D) If depth_first is True: Input is now of shape (D, H, W), will return guidance that specifies the coordinates in (D, H, W) else: Input is now of shape (H, W, D), will return guidance that specifies the coordinates in (H, W, D) Args: ref_image: key to reference image to fetch current and original image details. guidance: output key to store guidance. foreground: key that represents user foreground (+ve) clicks. background: key that represents user background (-ve) clicks. axis: axis that represents slices in 3D volume. (axis to Depth) depth_first: if depth (slices) is positioned at first dimension. spatial_dims: dimensions based on model used for deepgrow (2D vs 3D). slice_key: key that represents applicable slice to add guidance. meta_keys: explicitly indicate the key of the metadata dictionary of `ref_image`. for example, for data with key `image`, the metadata by default is in `image_meta_dict`. the metadata is a dictionary object which contains: filename, original_shape, etc. if None, will try to construct meta_keys by `{ref_image}_{meta_key_postfix}`. meta_key_postfix: if meta_key is None, use `{ref_image}_{meta_key_postfix}` to fetch the metadata according to the key data, default is `meta_dict`, the metadata is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. rA foregroundrPrTrMsliceNrrCr str | None) ref_imagerArrPr depth_first spatial_dims slice_keyrrc Cs@||_||_||_||_||_||_||_||_| |_| |_ dSr ) rrArrPrrrbrrr) r!rrArrPrrrrrrr"r"r#r$s zAddGuidanceFromPointsd.__init__c spg}}|jdkrt|}||ttt|dd|jf}dkrX|dntfdd|D} t|rt|}|t |dd|jf| k|ddddf t  }t|rt|}|t |dd|jf| k|ddddf t  }||| g} nPt|r@t ||j t dd }t|rdt ||j t dd }||g} | S)NrMrc3s|]}|kr|VqdSr r")rx slice_numr"r# sz0AddGuidanceFromPointsd._apply..r%Frn)rbrextendr(uniquerrnextr9r^rWrCramultiply) r! pos_clicks neg_clicksfactorrrrpointsr slice_idxrAr"rr#r- s&  "& >  >   zAddGuidanceFromPointsd._applyc Cs.t|}|jp|jd|j}||kr8td|dd||krLtd||d}t||jj}|jr|jdkrtdt |d}t ||}g}|j |j fD]X}||} tt j | td } |jrtt| D]} tt | | d| | <q|| q||d|d|||j||j<|S) NrzMissing meta_dict z in data! spatial_shapez%Missing "spatial_shape" in meta_dict!rz-Depth first means the depth axis should be 0.r%rx)r.rrr RuntimeErrorrr'rrr(rollrrrPrCr&r9r*r-rHrrA) r!r0r: meta_dict_keyoriginal_shape current_shaperZ fg_bg_clicksrclicksrr"r"r#r;#s.     &zAddGuidanceFromPointsd.__call__)r<r=r>r?rr$r-r;r"r"r"r#rs%"rcsfeZdZdZddedddddfd d d d d d d d d d ddd fdd ZddZdddddZZS)SpatialCropGuidanceda Crop image based on guidance with minimal spatial size. - If the bounding box is smaller than spatial size in all dimensions then this transform will crop the object using box's center and spatial_size. - This transform will set "start_coord_key", "end_coord_key", "original_shape_key" and "cropped_shape_key" in data[{key}_{meta_key_postfix}] Input data is of shape (C, spatial_1, [spatial_2, ...]) Args: keys: keys of the corresponding items to be transformed. guidance: key to the guidance. It is used to generate the bounding box of foreground spatial_size: minimal spatial size of the image patch e.g. [128, 128, 128] to fit in. margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims. meta_keys: explicitly indicate the key of the corresponding metadata dictionary. for example, for data with key `image`, the metadata by default is in `image_meta_dict`. the metadata is a dictionary object which contains: filename, original_shape, etc. it can be a sequence of string, map to the `keys`. if None, will try to construct meta_keys by `key_{meta_key_postfix}`. meta_key_postfix: if meta_keys is None, use `key_{postfix}` to fetch the metadata according to the key data, default is `meta_dict`, the metadata is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. 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. original_shape_key: key to record original shape for foreground. cropped_shape_key: key to record cropped shape for foreground. allow_missing_keys: don't raise exception if key is missing. NrrrrFr rz Iterable[int]rCrrr) rrArrrrrrrrrr1c st|| ||_t||_||_|dkr.cSsg|] }|jqSr"rrr"r"r#rsz>All the image specified in keys should have same spatial shaper)r. first_keyrAr'rr(rrrrWrCrrr9rrr rrrr array_equalrrrrrra)r!r0r:rrAoriginal_spatial_shaperrrrbox_sizediffrrrrrsrrrrr"r"r#r;sH  "    zSpatialCropGuidanced.__call__) r<r=r>r?rr$rr;rr"r"rr#rAs%*rc@s@eZdZdZdedfddddddddd Zd d d d dZdS)ResizeGuidanceda Resize the guidance based on cropped vs resized image. This transform assumes that the images have been cropped and resized. And the shape after cropped is store inside the meta dict of ref image. Args: guidance: key to guidance ref_image: key to reference image to fetch current and original image details meta_keys: explicitly indicate the key of the metadata dictionary of `ref_image`. for example, for data with key `image`, the metadata by default is in `image_meta_dict`. the metadata is a dictionary object which contains: filename, original_shape, etc. if None, will try to construct meta_keys by `{ref_image}_{meta_key_postfix}`. meta_key_postfix: if meta_key is None, use `{ref_image}_{meta_key_postfix}` to fetch the metadata according to the key data, default is `meta_dict`, the metadata is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. cropped_shape_key: key that records cropped shape for foreground. Nrrrr)rArrrrr1cCs"||_||_||_||_||_dSr )rArrrr)r!rArrrrr"r"r#r$s zResizeGuidanced.__init__rr.r/c Cst|}||j}||jp*|jd|j}||jjdd}||jdd}t||}|d|d}} t |rt ||j t dd ng} t | rt | |j t dd ng} | | g||j<|S)Nrr%rFrn)r.rArrrr'rr(divider9rrWrCra) r!r0r:rA meta_dictr cropped_shaperrrrrr"r"r#r;s  &&zResizeGuidanced.__call__)r<r=r>r?rr$r;r"r"r"r#rs rcsfeZdZdZdejddedddddf dd d d d d d d d d d d dd fdd ZdddddZZ S) RestoreLabelda Restores label based on the ref image. The ref_image is assumed that it went through the following transforms: 1. Fetch2DSliced (If 2D) 2. Spacingd 3. SpatialCropGuidanced 4. Resized And its shape is assumed to be (C, D, H, W) This transform tries to undo these operation so that the result label can be overlapped with original volume. It does the following operation: 1. Undo Resized 2. Undo SpatialCropGuidanced 3. Undo Spacingd 4. Undo Fetch2DSliced The resulting label is of shape (D, H, W) Args: keys: keys of the corresponding items to be transformed. ref_image: reference image to fetch current and original image details slice_only: apply only to an applicable slice, in case of 2D model/prediction mode: {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} One of the listed string values or a user supplied function for padding. Defaults to ``"constant"``. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html It also can be a sequence of bool, each element corresponds to a key in ``keys``. meta_keys: explicitly indicate the key of the corresponding metadata dictionary. for example, for data with key `image`, the metadata by default is in `image_meta_dict`. the metadata is a dictionary object which contains: filename, original_shape, etc. it can be a sequence of string, map to the `keys`. if None, will try to construct meta_keys by `key_{meta_key_postfix}`. meta_key_postfix: if meta_key is None, use `key_{meta_key_postfix} to fetch the metadata according to the key data, default is `meta_dict`, the metadata is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. start_coord_key: key that records the start coordinate of spatial bounding box for foreground. end_coord_key: key that records the end coordinate of spatial bounding box for foreground. original_shape_key: key that records original shape for foreground. cropped_shape_key: key that records cropped shape for foreground. allow_missing_keys: don't raise exception if key is missing. FNrrrrr rrz7Sequence[InterpolateMode | str] | InterpolateMode | strz#Sequence[bool | None] | bool | Nonerr) rr slice_onlymode align_cornersrrrrrrrr1c st|| ||_||_t|t|j|_t|t|j|_|dkrVtdt|jnt ||_ t|jt|j kr|t d||_ ||_ | |_| |_| |_dSr)rr$rr rr9rr rrrr8rrrrr) r!rrr r rrrrrrrrrr"r#r$(s"zRestoreLabeld.__init__rr.r/c Cs*t|}||jd|j}|||j|j|jD]\}}}}||}|j} ||j} t t | | rt | dd|d} | |||d}||j } t j| t jd} ||j}||j}tt|t|jdd}ttdgddt|d||d|D}|| |<| jdd}tt |dd}|t| d}t t ||rtt ||d} | | ||d} |d }|dks|jrt| jd kr| n| d }n"|d d }t t|}| ||<|||<|p|d|j}||}|dkrt}|||<||d <|d |d <q4|S)Nrr%)rr )r rrxcSsg|]\}}t||qSr")r)rrer"r"r#r[sz*RestoreLabeld.__call__..rrrLroriginal_affineaffine)r.rrrr rrr'rr(r~ not_equalr rr|rXrrrr9tuplerziprrrHr )r!r0r:r rr rrrsrr resizerrresultrrrrrrrr final_resultmetar"r"r#r;EsN$    ,     zRestoreLabeld.__call__) r<r=r>r?rNEARESTrr$r;rr"r"rr#r s5,r csLeZdZdZdddedfdddd dd d fd d ZddZddZZS) Fetch2DSlicedaT Fetch one slice in case of a 3D volume. The volume only contains spatial coordinates. Args: keys: keys of the corresponding items to be transformed. guidance: key that represents guidance. axis: axis that represents slice in 3D volume. meta_keys: explicitly indicate the key of the corresponding metadata dictionary. for example, for data with key `image`, the metadata by default is in `image_meta_dict`. the metadata is a dictionary object which contains: filename, original_shape, etc. it can be a sequence of string, map to the `keys`. if None, will try to construct meta_keys by `key_{meta_key_postfix}`. meta_key_postfix: use `key_{meta_key_postfix}` to fetch the metadata according to the key data, default is `meta_dict`, the metadata is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. allow_missing_keys: don't raise exception if key is missing. rArNFr rrCrr)rrArrrrcsnt||||_||_|dkr2tdt|jnt||_t|jt|jkrXt dt|t|j|_ dSr) rr$rArrr9rrrr8r)r!rrArrrrrr"r#r$s "zFetch2DSliced.__init__cCsX|d}g}t|jD],\}}||jkr2||n|td|q|t|t|fS)NrMr)r}r'rr*rr)r!rsrArrjrsize_ir"r"r#r-s &zFetch2DSliced._applyc Cs~t|}||j}t|dkr&td|||j|jD]@\}}}||||\}}|||<|||pr|d|d<q8|S)NrLz&Guidance does not container slice_idx!rr)r.rAr9rrrrr-) r!r0r:rArrrZ img_slicerjr"r"r#r;s  zFetch2DSliced.__call__) r<r=r>r?rr$r-r;rr"r"rr#r~sr)5 __future__rrpcollections.abcrrrrtypingrr7r(r5 monai.configrr r monai.networks.layersr monai.transformsr r monai.transforms.transformrrrmonai.transforms.utilsrr monai.utilsrrrrrmonai.utils.enumsrrYrrrrrr@rrrrrrrrr rr"r"r"r# s8    $WH&Pqs3