U Phz@sdZddlmZddlZddlZddlmZddlZddl Z ddl Z ddl m Z ddl mZddlmZddlmZdd lmZmZmZdd lmZdd lmZdd lmZdd lmZddlm Z m!Z!m"Z"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/e/d\Z0Z1e/d\Z2Z3e/d\Z4Z3e/d\Z5Z3ddddddddgZ6d)ddZ7dd d!dZ8dd d"dZ9d#dZ:d$dZ;d%dZd(dZ?dS)*zA A collection of "functional" transforms for spatial operations. ) annotationsN)Enum) USE_COMPILED)NdarrayOrTensor)get_track_meta) MetaTensor) AFFINE_TOLcompute_shape_offset to_affine_nd)AffineTransform)ResizeWithPadOrCrop)GaussianSmooth)TraceableTransform) create_rotatecreate_translateresolves_modes scale_affine)allclose) LazyAttr TraceKeysconvert_to_dst_typeconvert_to_numpyconvert_to_tensor ensure_tupleensure_tuple_repfall_back_tupleoptional_importnibabelcupyzcupyx.scipy.ndimagez scipy.ndimagespatial_resample orientationflipresizerotatezoomrotate90 affine_funccCs&tt|tr|n|||tddS)zgcreate a metatensor with fresh metadata if track_meta is True otherwise convert img into a torch tensorT)dtypedevice track_meta wrap_sequence)r isinstancer as_tensorr)imgr'r(r.X/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/spatial/functional.py_maybe_new_metatensor8sr0z torch.Tensor)returnc Csxt|tr|n |jdd} t|tr2|ntd} t|td}t t |jd| jddd} t|t r||dkr|dk rt t t |d} t | | tj} |dk rt | |n| }t|| d}t|tjstdt|t| d| } t|t r|dkr| }n$|dkr<| dkrtz"spatial_resample..)r'mode padding_mode align_corners src_affinezsrc affine is not invertible z, .)r(r')atolsp_sizeaffine extra_info orig_sizetransform_infolazyr'cSsg|]}t|ddqSr2r?float.0dr.r.r/ sz$spatial_resample..T)rD spatial_size normalized image_onlyr'r=F)r;r<rRr;r<r=reverse_indexing)thetarQ)7r+rpeek_pending_shapeshapepeek_pending_affinetorcheyerrminlenintrr tofloat64rTensor ValueErrortypetensorr rstrrvaluerNONErnplinalgsolve LinAlgError RuntimeErrorr(rrrtrack_transform_metar0copy_meta_fromfloat32r,listreshaperrmonai transformsAffinetrace_transformrr unsqueezesqueeze) r- dst_affinerQr;r<r=dtype_ptrHrGoriginal_spatial_shaper> spatial_rankZin_spatial_size_rE_s_dxformeZaffine_unchanged meta_infooutim_sizechnsZ in_sp_sizeZadditional_dimsZ xform_shape dst_xformZ affine_xform_m_p full_shaper.r.r/rCs   **"  ,       c Cs~t|tr|n |jdd}tj||}t|td}|dddfd7<t t ddgg|g}ddt |dddfD}t t|d}t |dddf|dt|<d|i} t|dd } | d d|D} tj|| || |||d } t|} |r&t| tr"| | S| S|r:tj| |d } t |t t| jksd| |} t| trz| | S| S) a Functional implementation of changing the input image's orientation into the specified based on `spatial_ornt`. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be changed, assuming `img` is channel-first. original_affine: original affine of the input image. spatial_ornt: orientations of the spatial axes, see also https://nipy.org/nibabel/reference/nibabel.orientations.html lazy: a flag that indicates whether the operation should be performed lazily or not transform_info: a dictionary with the relevant information pertaining to an applied transform. r2Nr)rcSsg|]\}}|dkr|qS)r6r.)rNaxr!r.r.r/rPszorientation..original_affineTr*cSsg|]}|dkr|dqS)rr2r.rNir.r.r/rPsrB)dims)r+rrWrXnib orientations inv_ornt_affrrrh concatenatearray enumeratearanger]argsortrrrmr0rnrZr!allpermutetolist) r-r spatial_orntrHrG spatial_shaperaxesfull_transposerEZshape_nprrr.r.r/r s8 "  c Cs&t|tr|n |jdd}t|dd}d|i}tjj |j |}t|tr\| nt j dt jd}t jt|dt jd}|D]:} | d} || | fd|| d|| | f<|| df<qtj||||||d } t|} |rt| tr| | S| St | |} t| tr"| | S| S) a Functional implementation of flip. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be changed, assuming `img` is channel-first. sp_axes: spatial axes along which to flip over. If None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple. lazy: a flag that indicates whether the operation should be performed lazily or not transform_info: a dictionary with the relevant information pertaining to an applied transform. r2NTrr@rIr6)rCrDrErGrH)r+rrWrXrrrrrsutilsmap_spatial_axesndimpeek_pending_rankrZrddoubler[r^rrmr0rnr!) r-Zsp_axesrHrGrCrErrankraxissprrr.r.r/r!s, "0 c  CsDt|td}t|tr |n |jdd} ||dk r<|ntjt|ddt | |d} t j ||t | || | | |d} |r|r|rt dt|} t| tr| | S| Stt| |krt|tjd} t| tr| | S| St|} t| |d d }|rtd d t||jddDrttt|jddt|}|dkrztt|j|dd }nBtt|t |}tt |D]"}||t||dk||<qt |d}t||d d}t!|t |jdd\}}}}tj"j#j$|%d|||d}t&|'d| tjd^} }t| tr@| | S| S)a Functional implementation of resize. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be changed, assuming `img` is channel-first. out_size: expected shape of spatial dimensions after resize operation. mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. dtype: data type for resampling computation. If None, use the data type of input data. input_ndim: number of spatial dimensions. anti_aliasing: whether to apply a Gaussian filter to smooth the image prior to downsampling. It is crucial to filter when downsampling the image to avoid aliasing artifacts. See also ``skimage.transform.resize`` anti_aliasing_sigma: {float, tuple of floats}, optional Standard deviation for Gaussian filtering used when anti-aliasing. lazy: a flag that indicates whether the operation should be performed lazily or not transform_info: a dictionary with the relevant information pertaining to an applied transform. rr2Nr:)r;r=r'new_dimrBz5anti-aliasing is not compatible with lazy evaluation.rIF)r'r)css|]\}}||kVqdSNr.)rNr7yr.r.r/ Bszresize..r?)sigmatorch_interpolate_spatial_ndr)inputsizer;r=)(rrr+rrWrXrrgrer]rrmrwarningswarnr0rntuplerrZroanyzipdivrarpmaximumzerosrrranger^r rnn functional interpolatervrrw)r-out_sizer;r=r' input_ndim anti_aliasinganti_aliasing_sigmarHrGrFrErrimg_factorsrZanti_aliasing_filterr|rresizedr.r.r/r" sX    *& "  c  Cs(t|tr|n |jdd} t| } | dkr@td| dt|| dkrPdnd} t| | } |dkrt tj dd | Dd d i t| d f} | dd dd f| } tj | j dd dt d}ntj |t d}t| t| dd}t| tj |t dd d}|| |} | |||dk r6|ntjt|ddd}tj||| || ||d}t|}|rt|tr||S|St||\}}}}td|||dd}||}t| |^}}||d|tdd|Dd}|d}t||t j!d^}}t|tr$||S|S)a  Functional implementation of rotate. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be changed, assuming `img` is channel-first. angle: Rotation angle(s) in radians. should a float for 2D, three floats for 3D. output_shape: output shape of the rotated data. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. lazy: a flag that indicates whether the operation should be performed lazily or not transform_info: a dictionary with the relevant information pertaining to an applied transform. r2N)r?r5zUnsupported image dimension: z, available options are [2, 3].r?r5cSsg|] }d|fqS)rr.)rNdimr.r.r/rPvszrotate..indexingijr6)rg?rIr:)rot_matr;r<r=r'rBFTrTrcss|]}t|VqdSrr^rr.r.r/rszrotate..)rQdstr')"r+rrWrXr]rbrrrhasarraymeshgridrqptpr^rrrrrgrerrmr0rnrr r_rrvrrLrwrZro)r-angle output_shaper;r<r=r'rHrGim_shaper_angle transformcornersshiftshift_1rErrr|rrrimg_t transform_toutputr.r.r/r#Vs\  ."   "c  Cs>t|tr|n |jdd} ddt| |D} t| | } ||dk rL|ntjt|dddid} |rt | |  } | r|rt | |d}d |_ tgt t| dd }|tjt| tj| i||}t|tr|} |jd | d <| | d <dd| D} tj|| | | | ||d}t|}|rHt|trD||S|S||}t|t|jdd\}}}}t jjjd | dt|||d!d}t"||t j#d^}}t|tr||}t | |jdd } | rt |jdd|d}||}t$r:| r:|j%&}d |j%d dd <||j%d dd <|S)a Functional implementation of zoom. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be changed, assuming `img` is channel-first. scale_factor: The zoom factor along the spatial axes. If a float, zoom is the same for each spatial axis. If a sequence, zoom should contain one value for each spatial axis. keep_size: Whether keep original size (padding/slicing if needed). mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. lazy: a flag that indicates whether the operation should be performed lazily or not transform_info: a dictionary with the relevant information pertaining to an applied transform. r2NcSs&g|]\}}ttt||qSr.)r^mathfloorrL)rNrzr.r.r/rPszzoom..r:F)r;r=r' do_padcroppadcrop)rQr;T)rDr6rrcSsg|] }t|qSr.rrr.r.r/rPsrBrr)recompute_scale_factorr scale_factorr;r=rrE)'r+rrWrXrrrrgrerhrr rHrZr[r]push_pending_operationrSHAPErpAFFINErYpending_operationsrrmr0rnr_rrrrrvrwrrorapplied_operationspop)r-r keep_sizer;r<r=r'rHrGr output_sizerrEZ do_pad_cropZ _pad_cropZ_tmp_imgZ lazy_croppedrrrr|rZzoomed padcrop_xformr.r.r/r$sr         c Csdd|D|d}t|tr&|n |jdd}t|}|dkrx|dd|dd}} || ||||<|| <t|tr|ntjdtjd } t | t |} } t | t | d d|D} t |dt |dd krd nd }| dkrt | t | |tjdg}nFdddht|}dddg}|tjd||d<t | t | |}t|D]}|| } q`t | t | dd|D| } tj||| ||||d}t|}|rt|tr||S|St|||}t|tr||S|S)ai Functional implementation of rotate90. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be changed, assuming `img` is channel-first. axes: 2 int numbers, defines the plane to rotate with 2 spatial axes. If axis is negative it counts from the last to the first axis. k: number of times to rotate by 90 degrees. lazy: a flag that indicates whether the operation should be performed lazily or not transform_info: a dictionary with the relevant information pertaining to an applied transform. cSsg|] }|dqS)r2r.rMr.r.r/rPszrotate90..)rkr2N)r2r5rrrIcSsg|]}t|d dqSrJrKrMr.r.r/rPs)r6r?gg?r?r5cSsg|]}t|ddqSrJrKrMr.r.r/rPsrB)r+rrWrXrprrZrdrr^r]r rrrhpisetrrrrmr0rnrot90)r-rrrHrGrEZ ori_shapeZsp_shapeZa_0a_1rrZsp_rrsridxrr|rrr.r.r/r%sB "$     c  Cst|tr|n |jdd} t|tr2|ntjdtjd} |||||jd} t j j | || |}t j|||| | | | d}| rt|}t|tr||n|}|r|S||fS|r|||||d}t|}nt|tj|jd}t|tr||n|}|r|S||fS) ai Functional implementation of affine. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be changed, assuming `img` is channel-first. affine: the affine transformation to be applied, it can be a 3x3 or 4x4 matrix. This should be defined for the voxel space spatial centers (``float(size - 1)/2``). grid: used in non-lazy mode to pre-compute the grid to do the resampling. resampler: the resampler function, see also: :py:class:`monai.transforms.Resample`. sp_size: output image spatial size. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html do_resampling: whether to do the resampling, this is a flag for the use case of updating metadata but skipping the actual (potentially heavy) resampling operation. image_only: if True return only the image volume, otherwise return (image, affine). lazy: a flag that indicates whether the operation should be performed lazily or not transform_info: a dictionary with the relevant information pertaining to an applied transform. r2NrrI)rDr;r< do_resamplingr=rB)r-gridr;r<)r'r()r+rrWrXrrZrdrr=rrrsrtcompute_w_affinerrmr0rnror()r-rDr resamplerrCr;r<rrSrHrGimg_sizerrErrr.r.r/r&#s8$ "  )NN)@__doc__ __future__rrrenumrnumpyrhrZrr monai.configrmonai.config.type_definitionsrmonai.data.meta_objrmonai.data.meta_tensorrmonai.data.utilsrr r monai.networks.layersr monai.transforms.croppad.arrayr Z monai.transforms.intensity.arrayr monai.transforms.inversermonai.transforms.utilsrrrr0monai.transforms.utils_pytorch_numpy_unificationr monai.utilsrrrrrrrrrrhas_nibrr|cupy_ndinp_ndi__all__r0rr r!r"r#r$r%r&r.r.r.r/ sB           ,     w.$JGT2