U PhT1@s>dZddlmZddlZddlZddlZddlmZ ddl m Z ddl m Z ddlmZddlmZdd lmZdd lmZmZdd lmZmZmZmZmZd d ddgZddZdddddddZdddddddZ ej!fddddddd Z"ddddddZ#ej!d fdd!d"dd#dd$d%d Z$dd&d#d"dd'd(dZ%dS))zA A collection of "functional" transforms for spatial operations. ) annotationsN)pad) NdarrayTensor)get_track_meta) MetaTensor) to_affine_nd)TraceableTransform)convert_pad_modecreate_translate)PytorchPadModeconvert_to_dst_typeconvert_to_numpyconvert_to_tensor ensure_tuplepad_ndpad_func crop_funccrop_or_pad_ndcCs8|dks|dkrtjS|dkr$tjS|dkr2tjStjS)zSget the most similar mode of `pad` from ``padding_mode`` of the spatial resampling.N)zerosconstantz grid-constant) reflectionreflectmirrorz grid-mirror)wrapz grid-wrap)r CONSTANTREFLECTCIRCULAR REPLICATE) padding_moderX/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/croppad/functional.py_convert_pt_pad_mode"sr!rzlist[tuple[int, int]]str)img pad_widthmodereturnc Kst|tjrF|jr4td|jd|jd|d| }n|}t ||dj }|dkrvd|krv| d|d<tj||fd |i|}t||d d S) NzPadding: moving img z from cuda to cpu for dtype=z mode=.dstr%rvalueconstant_valuesr%r)r) isinstancetorchTensoris_cudawarningswarnshapedtypedetachcpunumpyr r*popnprr )r#r$r%kwargsZimg_nprrr _np_pad-s "r;cKst|}t||dj}|dkr@d|kr@|}|d|d<n|}dd|ddDddd}t|d |fd |i|d }t ||d d S) Nr(rr+r*cSs$g|]}|dddD]}|qqS)Nr).0sublistvalrrr Csz_pt_pad..r<rr%r,) r. as_tensorr r*copyr8pad_pt unsqueezesqueezer )r#r$r%r:Zimg_pt_kwargsZ pt_pad_widthrrr _pt_pad;s  "rH)r#to_padr%r&c s|dkrt|f||d|SzBt}|dkrJ|jtjtjtjtjhkrJt}||f||d|WStt t fk r zt t st fdddDrt|f||d|WYHSt|jd|d|d|d|jdt |tjr|jnd W5dXYnXdS) a Pad `img` for a given an amount of padding in each dimension. `torch.nn.functional.pad` is used unless the mode or kwargs are not available in torch, in which case `np.pad` will be used. Args: img: data to be transformed, assuming `img` is channel-first and padding doesn't apply to the channel dim. to_pad: the amount to be padded in each dimension [(low_H, high_H), (low_W, high_W), ...]. default to `self.to_pad`. mode: available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. >median symmetric linear_rampminimummaximummeanempty)r$r%>r replicaterredgecircularc3s|]}|tkVqdS)N)r")r=kerrrr lszpad_nd..) supportedzunexpected keyword implementedr* N)r;r4r.int16int64booluint8rH ValueError TypeError RuntimeErrorr-NotImplementedErroranyr3r/device)r#rIr%r:_padrrUr rIs, :z torch.Tensorztuple[int, ...])r# spatial_sizer%c Kst|jd}tt|t|dd}tt||}ttjdd|Dddi}| t|df}t |t |t |d df}|j dd |jdd } } d gtd gd d f\} } } }t| | |jdd D]\}}}| p|d kp||dk|p|d kp||dk} }| |d kr,d nt| ||dkrFd nt||dfg7} | ttt|d t|d| dd g7} q| rt|}t|| fd|i|}|r|| }|S)a Crop or pad using the translation matrix and spatial size. The translation coefficients are rounded to the nearest integers. For a more generic implementation, please see :py:class:`monai.transforms.SpatialResample`. Args: img: data to be transformed, assuming `img` is channel-first and padding doesn't apply to the channel dim. translation_mat: the translation matrix to be applied to the image. A translation matrix generated by, for example, :py:func:`monai.transforms.utils.create_translate`. The translation coefficients are rounded to the nearest integers. spatial_size: the spatial size of the output image. mode: the padding mode. kwargs: other arguments for the `np.pad` or `torch.pad` function. rAT) wrap_sequencecSsg|]}d|dgqS)g?r)r=xrrr r@sz"crop_or_pad_nd..indexingijr<N)axisrrFrr%)lenr3r9roundrr rCasarraymeshgridreshapefloor concatenate ones_likeminmaxslicezipintr!r)r#Ztranslation_matrfr%r:ndim matrix_npccZsrc_ccZ src_startZsrc_endrIZto_cropdo_padZdo_cropsesp_moderrr rus$ & 6@0Fztuple[tuple[int, int]]dictr])r#rItransform_infor%lazyr&c Ks||d}t|tr|n |jdd}t|tr>|nd}t|} | rdd|D} t| t|jkr| dgt|jt| 7} dd| ddD} t || } d dt || ddD} n$|} t j t |dt d t jd } tj|| | ||||d }tt|tr |n|td }|rLt|trH||S|S| rbt|| |f|n|}t|td }t|tr||S|S)a7 Functional implementation of padding a MetaTensor. This function operates eagerly or lazily according to ``lazy`` (default ``False``). `torch.nn.functional.pad` is used unless the mode or kwargs are not available in torch, in which case `np.pad` will be used. Args: img: data to be transformed, assuming `img` is channel-first and padding doesn't apply to the channel dim. to_pad: the amount to be padded in each dimension [(low_H, high_H), (low_W, high_W), ...]. note that it including channel dimension. transform_info: a dictionary with the relevant information pertaining to an applied transform. mode: available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html lazy: a flag indicating whether the operation should be performed in a lazy fashion or not. transform_info: a dictionary with the relevant information pertaining to an applied transform. kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. )paddedr%rANcSs$g|]}t|dt|dfqSrrA)ry)r=prrr r@szpad_func..rlcSsg|]}|d qS)rr)r=r~rrr r@scSs g|]\}\}}|||qSrr)r=dr~rrrr r@s r6)rdr4sp_sizeaffine extra_info orig_sizerr track_meta)r-rpeek_pending_shaper3peek_pending_rankr9rorcrmr rxr.eyeryrdfloat64rtrack_transform_metarrBrcopy_meta_fromr)r#rIrr%rr:rimg_size spatial_rankr}Z to_pad_listto_shiftxformr3 meta_infooutrrr rs8     "ztuple[slice, ...])r#slicesrrr&c Csbt|tr|n |jdd}t|tr2|nd}tddt|dd|D}d| i}g}t t |ddD]B\} } | j dk r| | j dkr|| | j n| j q| dqddt|dd|D} tj|| t||||||d } tt|tr|n|td } |r@t| tr<| | S| S| |} t| tr^| | S| S) aI Functional implementation of cropping a MetaTensor. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be transformed, assuming `img` is channel-first and cropping doesn't apply to the channel dim. slices: the crop slices computed based on specified `center & size` or `start & end` or `slices`. lazy: a flag indicating whether the operation should be performed in a lazy fashion or not. transform_info: a dictionary with the relevant information pertaining to an applied transform. rANrcSs0g|](\}}||d|||dgqSrindicesr=r~orrr r@szcrop_func..croppedrcSs,g|]$\}}||d||dqS)rArrrrrr r@srr)r-rrr3rr9rorxflattentolist enumeraterstartappendrrr rrBrr)r#rrrrrrrrir~r3rrrrr rs0 " &  ")&__doc__ __future__rr1r7r9r.torch.nn.functionalrrDmonai.config.type_definitionsrmonai.data.meta_objrmonai.data.meta_tensorrmonai.data.utilsrmonai.transforms.inversermonai.transforms.utilsr r monai.utilsr r r rr__all__r!r;rHrrrrrrrrr  s.         ,&>