o  i]@sdZddlmZddlZddlmZmZddlmZddl m Z ddl m Z m Z mZmZddlZddlZddlmZmZdd lmZdd lmZmZdd lmZmZdd lmZdd l m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&ddl'm(Z(m)Z)m*Z*ddl+m,Z,ddl-m.Z.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>ddl?m@Z@mAZAmBZBmCZCddlDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMddlNmOZOmPZPmQZQmRZRddlSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbddlcmdZdddlemfZfmgZgmhZhmiZiddljmkZlddlmmnZnddlompZpmqZqmrZrebd\ZsZtebd\ZuZvebd\ZwZvebd \ZxZvgd!Zye eeeeze{e{fe{fe{fZ|Gd"d#d#e1e@Z}Gd$d%d%e}Z~Gd&d'd'e1e@ZGd(d)d)e1e@ZGd*d+d+e1e@ZGd,d-d-e1e@ZGd.d/d/e1e@ZGd0d1d1e1e@ZGd2d3d3e1e@ZGd4d5d5eBe1e@ZGd6d7d7eBe1e@ZGd8d9d9eBe1e@ZGd:d;d;eBe1e@ZGdd?d?e@ZGd@dAdAeAe@ZGdBdCdCeAeCZGdDdEdEeCZGdFdGdGe1e@ZGdHdIdIeBe1e@ZGdJdKdKeBZGdLdMdMeBZGdNdOdOeCZGdPdQdQeBZGdRdSdSeCe>ZGdTdUdUeCe>ZGdVdWdWeeBe>ZGdXdYdYeBZGdZd[d[eCZGd\d]d]eCZdS)^z> A collection of "vanilla" transforms for spatial operations. ) annotationsN)CallableSequence)deepcopy) zip_longest)AnyOptionalUnioncast) USE_COMPILED DtypeLike)NdarrayOrTensor)BoxMode StandardMode)get_track_metaset_track_meta) MetaTensor) AFFINE_TOLaffine_to_spacingcompute_shape_offset iter_patch to_affine_nd zoom_affine)AffineTransformGaussianFilter grid_pull) meshgrid_ij)CenterSpatialCropResizeWithPadOrCrop)InvertibleTransform) affine_funcconvert_box_to_pointsconvert_points_to_boxflip orientationresizerotaterotate90spatial_resamplezoom)MultiSampleTrait) LazyTransform RandomizableRandomizableTransform Transform) create_control_grid create_grid create_rotate create_scale create_shearcreate_translatemap_spatial_axesresolves_modes scale_affine)argsortargwhere linalg_invmoveaxis)GridSampleModeGridSamplePadModeInterpolateMode NumpyPadMode SpaceKeysconvert_to_cupyconvert_to_dst_typeconvert_to_numpyconvert_to_tensor ensure_tupleensure_tuple_repensure_tuple_sizefall_back_tupleissequenceiterableoptional_import)deprecated_arg_default) GridPatchSort PatchKeys TraceKeysTransformBackends) ImageMetaKey)look_up_option)convert_data_typeget_equivalent_dtypeget_torch_dtype_from_stringnibabelcupyzcupyx.scipy.ndimagez scipy.ndimage)SpatialResampleResampleToMatchSpacing OrientationFlipGridDistortion GridSplit GridPatch RandGridPatchResizeRotateZoomRotate90 RandRotate90 RandRotateRandFlipRandGridDistortion RandAxisFlipRandZoom AffineGridRandAffineGridRandDeformGridResampleAffine RandAffine Rand2DElastic Rand3DElasticRandSimulateLowResolutionc@s`eZdZdZejejejgZe j e j de jdfdd d Z       dd ddZd!ddZdS)"rWa Resample input image from the orientation/spacing defined by ``src_affine`` affine matrix into the ones specified by ``dst_affine`` affine matrix. Internally this transform computes the affine transform matrix from ``src_affine`` to ``dst_affine``, by ``xform = linalg.solve(src_affine, dst_affine)``, and call ``monai.transforms.Affine`` with ``xform``. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Fmode str | int padding_modestr align_cornersbooldtyper lazycCs*tj||d||_||_||_||_dS)a% Args: mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"border"``. 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 dtype: data type for resampling computation. Defaults to ``float64`` for best precision. 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 to indicate whether this transform should execute lazily or not. Defaults to False rzN)r+__init__rsrurwry)selfrsrurwryrzr~`/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/spatial/array.pyr|s  zSpatialResample.__init__Nimg torch.Tensor dst_affinetorch.Tensor | None spatial_size)Sequence[int] | torch.Tensor | int | Nonestr | int | None str | None bool | Nonereturnc Cs~t|p|jp|jtj} |dur|n|j}|dur|n|j}|dur$|n|j}|dur.|jn|} t||||||| | | d S)a Args: img: input image to be resampled. It currently supports channel-first arrays with at most three spatial dimensions. dst_affine: destination affine matrix. Defaults to ``None``, which means the same as `img.affine`. the shape should be `(r+1, r+1)` where `r` is the spatial rank of ``img``. when `dst_affine` and `spatial_size` are None, the input will be returned without resampling, but the data type will be `float32`. spatial_size: output image spatial size. if `spatial_size` and `self.spatial_size` are not defined, the transform will compute a spatial size automatically containing the previous field of view. if `spatial_size` is ``-1`` are the transform will use the corresponding input img size. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. 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 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 Defaults to ``None``, effectively using the value of `self.align_corners`. dtype: data type for resampling computation. Defaults to ``self.dtype`` or ``np.float64`` (for best precision). 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 to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. The spatial rank is determined by the smallest among ``img.ndim -1``, ``len(src_affine) - 1``, and ``3``. When both ``monai.config.USE_COMPILED`` and ``align_corners`` are set to ``True``, MONAI's resampling implementation will be used. Set `dst_affine` and `spatial_size` to `None` to turn off the resampling step. Nrztransform_info) rSrytorchTensorrwrsrurzr(get_transform_info) r}rrrrsrurwryrzZdtype_ptlazy_r~r~r__call__s 3zSpatialResample.__call__datacCs||}|tj}t|d|d<|d|d<|tj|d<|dtjkr,d|d<|dt j ||fi|}Wdn1sFwY|d|d<|S)NryZ src_affinerrrwF) pop_transformrN EXTRA_INFOrTpop ORIG_SIZEgetNONEtrace_transformrWr)r}r transformkw_argsoutr~r~rinverses   zSpatialResample.inverse) rsrtrurvrwrxryr rzrxNNNNNNN)rrrrrrrsrrurrwrryr rzrrrrrrr)__name__ __module__ __qualname____doc__rOTORCHNUMPYCUPYbackendr<BILINEARr=BORDERnpfloat64r|rrr~r~r~rrW|s$  % DrWcs.eZdZdZ     ddfdd ZZS)rXa  Resample an image to match given metadata. The affine matrix will be aligned, and the size of the output image will match. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Nrrimg_dstrsrrurrwrryr rzrc s |durtdt|tr|ntd}|dur|jn|} tj||t|tr-| n|j dd||||| d}| s`t|tr^||_ t|tr^|j tjd} t|j |_ | |j tj<|St|trt|tr|j tjd} t|j } dD]} | | dqy|j | | |j tj<|S)a> Args: img: input image to be resampled to match ``img_dst``. It currently supports channel-first arrays with at most three spatial dimensions. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"border"``. 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 align_corners: Geometrically, we consider the pixels of the input as squares rather than points. Defaults to ``None``, effectively using the value of `self.align_corners`. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. Defaults to ``self.dtype`` or ``np.float64`` (for best precision). 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 to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Raises: ValueError: When the affine matrix of the source image is not invertible. Returns: Resampled input tensor or MetaTensor. Nz`img_dst` is missing.)rrrrsrurwryrzZresample_to_match_source)affine spatial_shape) RuntimeError isinstancerpeek_pending_affinereyerzsuperrpeek_pending_shapeshapermetarKeyFILENAME_OR_OBJrrupdate) r}rrrsrurwryrzrrZoriginal_fname meta_dictk __class__r~rr s<)        zResampleToMatch.__call__NNNNN)rrrrrsrrurrwrryr rzrrr)rrrrr __classcell__r~r~rrrXs rXc @sreZdZdZejZdejej de j dddddf d(ddZ e jjd)ddZ       d*d+d#d$Zd,d&d'ZdS)-rYz Resample input image into the specified `pixdim`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. FNpixdim$Sequence[float] | float | np.ndarraydiagonalrxrsrtrurvrwryr scale_extentrecompute_affine min_pixdim+Sequence[float] | float | np.ndarray | None max_pixdimrzrNonec Cstj|| dtjt|tjd|_tjt| tjd|_tjt| tjd|_||_ ||_ ||_ t |j|jD]#\} } t | s[t | s[| | ksN| dkr[td|jd|jdq8t||||| d|_dS) a Args: pixdim: output voxel spacing. if providing a single number, will use it for the first dimension. items of the pixdim sequence map to the spatial dimensions of input image, if length of pixdim sequence is longer than image spatial dimensions, will ignore the longer part, if shorter, will pad with the last value. For example, for 3D image if pixdim is [1.0, 2.0] it will be padded to [1.0, 2.0, 2.0] if the components of the `pixdim` are non-positive values, the transform will use the corresponding components of the original pixdim, which is computed from the `affine` matrix of input image. diagonal: whether to resample the input to have a diagonal affine matrix. If True, the input data is resampled to the following affine:: np.diag((pixdim_0, pixdim_1, ..., pixdim_n, 1)) This effectively resets the volume to the world coordinate system (RAS+ in nibabel). The original orientation, rotation, shearing are not preserved. If False, this transform preserves the axes orientation, orthogonal rotation and translation components from the original affine. This option will not flip/swap axes of the original data. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"border"``. 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 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 dtype: data type for resampling computation. Defaults to ``float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. scale_extent: whether the scale is computed based on the spacing or the full extent of voxels, default False. The option is ignored if output spatial size is specified when calling this transform. See also: :py:func:`monai.data.utils.compute_shape_offset`. When this is True, `align_corners` should be `True` because `compute_shape_offset` already provides the corner alignment shift/scaling. recompute_affine: whether to recompute affine based on the output shape. The affine computed analytically does not reflect the potential quantization errors in terms of the output shape. Set this flag to True to recompute the output affine based on the actual pixdim. Default to ``False``. min_pixdim: minimal input spacing to be resampled. If provided, input image with a larger spacing than this value will be kept in its original spacing (not be resampled to `pixdim`). Set it to `None` to use the value of `pixdim`. Default to `None`. max_pixdim: maximal input spacing to be resampled. If provided, input image with a smaller spacing than this value will be kept in its original spacing (not be resampled to `pixdim`). Set it to `None` to use the value of `pixdim`. Default to `None`. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r{ryrz min_pixdim z$ must be positive, smaller than max .)rsrurwryrzN)r+r|rarrayrErrrrrrrzipisnan ValueErrorrW sp_resample)r}rrrsrurwryrrrrrzmnmxr~r~rr|^sD$  zSpacing.__init__valcC||_||j_dSN)_lazyrrzr}rr~r~rrz z Spacing.lazy data_arrayrrrroutput_spatial_shape'Sequence[int] | np.ndarray | int | Nonec  Cst|tr |n|jdd} t| } | dkr td| dt|tr)|nd} | dur>tdt j | dt j d} t | t | t jd} |jd| } | j| kret | | dg| | j} t| | | j}tt||jd| |jd| t jd D]N\}\}}}| |}t |r|nt||}t |r|nt||}||krtd |d |d |d |d |t|kr|tkrnn|n|| |<q|s|rtdt| | |jd}|dur|j n|}t!| | ||\}}|d| |d| df<|durt"|n|}|dur|j#n|}|j$|t%&|||||||d}|j'rBt|trB|r5t(dt)| |}t*|| d|_+|S)a Args: data_array: in shape (num_channels, H[, W, ...]). mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"self.mode"``. 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. Defaults to ``"self.padding_mode"``. 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 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 Defaults to ``None``, effectively using the value of `self.align_corners`. dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. scale_extent: whether the scale is computed based on the spacing or the full extent of voxels, The option is ignored if output spatial size is specified when calling this transform. See also: :py:func:`monai.data.utils.compute_shape_offset`. When this is True, `align_corners` should be `True` because `compute_shape_offset` already provides the corner alignment shift/scaling. output_spatial_shape: specify the shape of the output data_array. This is typically useful for the inverse of `Spacingd` where sometimes we could not compute the exact shape due to the quantization error with the affine. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Raises: ValueError: When ``data_array`` has no spatial dimensions. ValueError: When ``pixdim`` is nonpositive. Returns: data tensor or MetaTensor (resampled into `self.pixdim`). rNr9data_array must have at least one spatial dimension, got rzG`data_array` is not of type MetaTensor, assuming affine to be identity.r) fillvaluez,min_pixdim is larger than max_pixdim at dim z: min z max z out z=align_corners=False is not compatible with scale_extent=True.)r)rrrsrurwryrzz7recompute_affine is not supported with lazy evaluation.),rrrrlenrrwarningswarnrrrrrRndarrayrcopysizeappendrry enumeraterrrnanrminmaxrrrrrlistrzrr as_tensorrNotImplementedErrorr7rBr)r}rrsrurwryrrrzZoriginal_spatial_shapesrZ input_affineaffine_Zout_dZorig_didx_drrtarget new_affine output_shapeoffset actual_shaperar~r~rrs^4  $".   zSpacing.__call__rcCs |j|Sr)rrr}rr~r~rr#s zSpacing.inverse)rrrrxrsrtrurvrwrxryr rrxrrxrrrrrzrxrrrrxrrr)rrrsrrurrwrryr rrrrrzrrrr)rrrrrWrr<rr=rrrr|r+rzsetterrrr~r~r~rrYTs2 T  lrYc@sVeZdZdZejejgZeddddd    ddddZ ddddZ dddZ dS)rZz Change the input image's orientation into the specified based on `axcodes`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. labels))LR)PAISNzDefault value changed to None meaning that the transform now uses the 'space' of a meta-tensor, if applicable, to determine appropriate axis labels.)name old_default new_default msg_suffixFaxcodesras_closest_canonicalrx Sequence[tuple[str, str]] | NonerzrrcCsNtj||d|dur|std|dur|rtd||_||_||_dS)a Args: axcodes: N elements sequence for spatial ND input's orientation. e.g. axcodes='RAS' represents 3D orientation: (Left, Right), (Posterior, Anterior), (Inferior, Superior). default orientation labels options are: 'L' and 'R' for the first dimension, 'P' and 'A' for the second, 'I' and 'S' for the third. as_closest_canonical: if True, load the image as closest to canonical axis format. labels: optional, None or sequence of (2,) sequences (2,) sequences are labels for (beginning, end) of output axis. If ``None``, an appropriate value is chosen depending on the value of the ``"space"`` metadata item of a metatensor: if ``"space"`` is ``"LPS"``, the value used is ``(('R', 'L'), ('A', 'P'), ('I', 'S'))``, if ``"space"`` is ``"RPS"`` or the input is not a meta-tensor or has no ``"space"`` item, the value ``(('L', 'R'), ('P', 'A'), ('I', 'S'))`` is used. If not ``None``, the provided value is always used and the ``"space"`` metadata item (if any) of the input is ignored. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False Raises: ValueError: When ``axcodes=None`` and ``as_closest_canonical=True``. Incompatible values. See Also: `nibabel.orientations.ornt2axcodes`. r{N@Incompatible values: axcodes=None and as_closest_canonical=True.z1using as_closest_canonical=True, axcodes ignored.)r+r|rrrrrr)r}rrrrzr~r~rr|1s+    zOrientation.__init__rrrc Cst|tr |n|jdd}t|}|dkr td|d|j}t|trNt|t j ^}}t ||}|jdurMd|j vrMt |j dt jkrMd}ntdt j|dt jd }t j|dt jd }t|} |jrr| } nS|jdur{td |t|jkrtd |jd |d |jjd|d|jdd tjj|jd||d} t| |krtdt|jd|dtj| | } |dur|jn|} t||| | |dS)a If input type is `MetaTensor`, original affine is extracted with `data_array.affine`. If input type is `torch.Tensor`, original affine is assumed to be identity. Args: data_array: in shape (num_channels, H[, W, ...]). lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Raises: ValueError: When ``data_array`` has no spatial dimensions. ValueError: When ``axcodes`` spatiality differs from ``data_array``. Returns: data_array [reoriented in `self.axcodes`]. Output type will be `MetaTensor` unless `get_track_meta() == False`, in which case it will be `torch.Tensor`. rNrrrspace)rr)rrrzH`data_array` is not of type `MetaTensor, assuming affine to be identity.rr z axcodes ('z?') length is smaller than number of input spatial dimensions D=z. z: spatial shape = z , channels = z;,please make sure the input is in the channel-first format.rz5axcodes must match data_array spatially, got axcodes=z D data_array=Dr)rrrrrrrrRrrrrrr@LPSrrrrnibio_orientationrrrr orientationsZ axcodes2orntornt_transformrzr$r) r}rrzrrr affine_np_rsrcZ spatial_orntdstrr~r~rresN         zOrientation.__call__rcCs||}|tjd}|j}t|tr*|jdur*d|jvr*t|jdtjkr*d}t j j ||d}t |d|d}| d ||}Wd|S1sNwY|S)Noriginal_affiner r r F)rrr)rrNrrrrrr@rrrZ aff2axcodesrZr)r}rr orig_affinerZ orig_axcodesinverse_transformr~r~rrs"      zOrientation.inverse)NFNF) rrrrxrrrzrxrrr)rrrzrrrr) rrrrrOrrrrKr|rrr~r~r~rrZ's    +CrZc@s:eZdZdZejgZddd d ZddddZdddZ dS)r[a7 Reverses the order of elements along the given spatial axis. Preserves shape. See `torch.flip` documentation for additional details: https://pytorch.org/docs/stable/generated/torch.flip.html This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_axis: spatial axes along which to flip over. Default is None. The default `axis=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 to indicate whether this transform should execute lazily or not. Defaults to False NF spatial_axisSequence[int] | int | NonerzrxrrcCstj||d||_dSNr{)r+r|r)r}rrzr~r~rr|s z Flip.__init__rrrcCs6t|td}|dur|jn|}t||j||dS)al Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]) lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None.  track_metaNr)rDrrzr#rr)r}rrzrr~r~rrsz Flip.__call__rcCsL||t|jd}|d ||WdS1swYdS)NrF)rr[rr)r}rflipperr~r~rrs   $z Flip.inverse)NF)rrrzrxrrrrrrzrrrr) rrrrrOrrr|rrr~r~r~rr[s    r[c@sbeZdZdZejgZdejddde j dfd!ddZ      d"d#ddZ d$ddZ d$dd ZdS)%r`a Resize the input image to given spatial size (with scaling, not cropping/padding). Implemented using :py:class:`torch.nn.functional.interpolate`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: spatial_size: expected shape of spatial dimensions after resize operation. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. size_mode: should be "all" or "longest", if "all", will use `spatial_size` for all the spatial dims, if "longest", rescale the image so that only the longest side is equal to specified `spatial_size`, which must be an int number in this case, keeping the aspect ratio of the initial image, refer to: https://albumentations.ai/docs/api_reference/augmentations/geometric/resize/ #albumentations.augmentations.geometric.resize.LongestMaxSize. mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``"area"``. 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'. Default: None. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html anti_aliasing: bool 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. By default, this value is chosen as (s - 1) / 2 where s is the downsampling factor, where s > 1. For the up-size case, s < 1, no anti-aliasing is performed prior to rescaling. dtype: data type for resampling computation. Defaults to ``float32``. If None, use the data type of input data. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False allNFrSequence[int] | int size_modervrsrwr anti_aliasingrxanti_aliasing_sigmaSequence[float] | float | NoneryDtypeLike | torch.dtyperzrrc CsFtj||dt|ddg|_||_||_||_||_||_||_ dS)Nr{r"longest) r+r|rQr$rrsrwr%r&ry) r}rr$rsrwr%r&ryrzr~r~rr|s  zResize.__init__rrrc s|dur|jn|}|dur|jn|}|jd}|jdkr\tt|j} | |kr6t|j| dd} | | }n| |krEt d| d|dt |t rN| n|jdd} t|j| } n,t |t re| n|jdd} t |jtsvt d|jt| tfdd | D} |dur|jn|}|dur|jn|}t|p|jp|jtj}|dur|jn|}t|td d | D|||||||| S) aP Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]). mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``self.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'. Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html anti_aliasing: bool, optional 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. By default, this value is chosen as (s - 1) / 2 where s is the downsampling factor, where s > 1. For the up-size case, s < 1, no anti-aliasing is performed prior to rescaling. dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Raises: ValueError: When ``self.spatial_size`` length is less than ``img`` spatial dimensions. Nrr"zWlen(spatial_size) must be greater or equal to img spatial dimensions, got spatial_size=z img=rz=spatial_size must be an int number if size_mode is 'longest'.c3s |] }tt|VqdSr)intround).0sscaler~r ez"Resize.__call__..css|]}t|VqdSr)r*)r,_sr~r~rr0ms)r%r&ndimr$rrErrGrreshaperrrrrHr*rtuplersrwrSryrrrzr%r)r}rrsrwr%r&ryrz input_ndimZ output_ndim input_shapeZ_spsp_sizeimg_size_mode_align_corners_dtyperr~r.rr*sN&      zResize.__call__rcC||}|||Srrrr}rrr~r~rrx  zResize.inversec Cs|tj}|tjd}|tjd}|tjd}t|||tjkr$dn||d}|d ||}Wdn1s=wYt|tjdD]}|d}qK|S)Nrsrwry)rrsrwryFnew_dimr)rNrrr`rrrangesqueeze) r}rr orig_sizersrwryxformrr~r~rr|s    zResize.inverse_transform)rr#r$rvrsrvrwrr%rxr&r'ryr(rzrxrr)NNNNNN)rrrsrrwrr%rr&r'ryr(rzrrrr)rrrrrOrrr>AREArfloat32r|rrrr~r~r~rr`s(&  Nr`c@s`eZdZdZejgZdeje j de j dfdddZ     d d!ddZd"ddZd"ddZdS)#raa Rotates an input image by given angle using :py:class:`monai.networks.layers.AffineTransform`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: angle: Rotation angle(s) in radians. should a float for 2D, three floats for 3D. keep_size: If it is True, the output shape is kept the same as the input. If it is False, the output shape is adapted so that the input array is contained completely in the output. Default is True. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. Defaults to ``float32``. 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 to indicate whether this transform should execute lazily or not. Defaults to False TFangleSequence[float] | float keep_sizerxrsrvrurwryr(rzrrcCs6tj||d||_||_||_||_||_||_dSr)r+r|rHrJrsrurwry)r}rHrJrsrurwryrzr~r~rr|s  zRotate.__init__Nrrrrc Cst|td}t|p|jp|jtj}|p|j}|p|j} |dur$|jn|} t |t r/| n|j dd} |j r;| nd} |durD|jn|} t||j| || | || |d S)a  Args: img: channel first array, must have shape: [chns, H, W] or [chns, H, W, D]. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. Defaults to ``self.dtype``. 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 to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Raises: ValueError: When ``img`` spatially is not one of [2D, 3D]. rNrr)rDrrSryrrrsrurwrrrrrJrzr&rHr)r}rrsrurwryrzr<r: _padding_moder;im_shaperrr~r~rrs&!   zRotate.__call__rcCr=rr>r?r~r~rrr@zRotate.inversecCs(|tjd}|tjd}|tjd}|tjd}|tjd}tt|}t||\} } } } td| | |tjkr=dn|dd} t|t|d d } t || ^}} |tj }| | d ||d  d }t |||jd d }t|trt|dd }tt|d|}|jt ||d _|S)NZrot_matrsrurwryFT) normalizedrsrurwreverse_indexingrrrrryrr)rNrr:rCr6rrrRrrBr unsqueezefloatrCryrrDrrrr)r}rrZ fwd_rot_matrsrurwryZ inv_rot_matr_m_prEimg_tZ transform_tr8rrmatr~r~rrs0   zRotate.inverse_transform)rHrIrJrxrsrvrurvrwrxryr(rzrxrrrrrrsrrurrwrryr(rzrrrr)rrrrrOrrr<rr=rrrGr|rrrr~r~r~rras$  5rac@s`eZdZdZejgZeje j de j ddfdddZ     d d!ddZd"ddZd"ddZdS)#rba: Zooms an ND image using :py:class:`torch.nn.functional.interpolate`. For details, please see https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html. Different from :py:class:`monai.transforms.resize`, this transform takes scaling factors as input, and provides an option of preserving the input spatial size. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: zoom: 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. mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``"area"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"edge"``. The mode to pad data after zooming. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html dtype: data type for resampling computation. Defaults to ``float32``. If None, use the data type of input data. keep_size: Should keep original size (padding/slicing if needed), default is True. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. NTFr)rIrsrvrurwrryr(rJrxrzrrc Ks<tj||d||_||_||_||_||_||_||_dSr) r+r|r)rsrurwryrJkwargs) r}r)rsrurwryrJrzrXr~r~rr|9s  z Zoom.__init__rrrc Cst|td}t|j|jd}|dur|jn|}|p|j} |dur%|jn|} t|p/|j p/|j t j } |dur:|j n|} t|||j || | | f| |d|jS)a Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]). mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"edge"``. The mode to pad data after zooming. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. rrNr)rDrrFr)r3rsrurwrSryrrrzrJrrX) r}rrsrurwryrz_zoomr:rKr;r<rr~r~rrMs*   z Zoom.__call__rcCr=rr>r?r~r~rrr@z Zoom.inversec Cs|tjdr5|tj}t|dd}|tjd}tj|tjdtj<tj|tjdtj<|||}|tjd}|tjd}|tjd }t|tjd } | d | |||tjkrbdn||d } Wd| S1srwY| S) NZ do_padcropedge)rrsZpadcroppad_info crop_inforsrwryrOF)rsrwry) rNrrrrIDrr`r) r}rrrDZ pad_or_cropZ padcrop_xformrsrwryrrr~r~rrs&     zZoom.inverse_transform)r)rIrsrvrurvrwrryr(rJrxrzrxrrrrWr)rrrrrOrrr>rFr?EDGErrGr|rrrr~r~r~rrbs$$  4rbc@sDeZdZdZejgZddd dZddddZdddZ dddZ dS)rcaE Rotate an array by 90 degrees in the plane specified by `axes`. See `torch.rot90` for additional details: https://pytorch.org/docs/stable/generated/torch.rot90.html#torch-rot90. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. rrrFrr* spatial_axestuple[int, int]rzrxrrcCsNtj||dd|dd|_t|}t|dkr"td|d||_dS)a Args: k: number of times to rotate by 90 degrees. spatial_axes: 2 int numbers, defines the plane to rotate with 2 spatial axes. Default: (0, 1), this is the first two axis in spatial dimensions. If axis is negative it counts from the last to the first axis. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r{rzBspatial_axes must be 2 numbers to define the plane to rotate, got rN)r+r|rrErrr`)r}rr`rz spatial_axes_r~r~rr|s    zRotate90.__init__NrrrcCsFt|td}t|j|j}|dur|jn|}t|||j||dS)am Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]), lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. rNr) rDrr5r3r`rzr'rr)r}rrzaxesrr~r~rrszRotate90.__call__rcCr=rr>r?r~r~rrr@zRotate90.inversecCsj|tjd}|tjd}d|d}t||d}|d ||WdS1s.wYdS)Nrdrr)rr`F)rNrrcr)r}rrrdrZinv_krEr~r~rrs   $zRotate90.inverse_transform)rr_F)rr*r`rarzrxrrrr!r) rrrrrOrrr|rrrr~r~r~rrcs   rccsNeZdZdZejZ d d!ddZd"d#fdd Zd$d%ddZd&ddZ Z S)'rdz With probability `prob`, input arrays are rotated by 90 degrees in the plane specified by `spatial_axes`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. 皙?r_FprobrRmax_kr*r`rarzrxrrcCs0t||tj||d||_||_d|_dS)a# Args: prob: probability of rotating. (Default 0.1, with 10% probability it returns a rotated array) max_k: number of rotations will be sampled from `np.random.randint(max_k) + 1`, (Default 3). spatial_axes: 2 int numbers, defines the plane to rotate with 2 spatial axes. Default: (0, 1), this is the first two axis in spatial dimensions. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r{rN)r-r|r+rhr`_rand_k)r}rgrhr`rzr~r~rr|s  zRandRotate90.__init__Nr Any | Nonecs.td|js dS|j|jd|_dSNr)r randomize _do_transformrrandintrhrirrr~rrl zRandRotate90.randomizeTrrrlrcCsb|r||dur |jn|}|jr t|j|j|d}||}nt|td}|j|d|d|Sa Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]), randomize: whether to execute `randomize()` function first, default to True. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Nr{rTreplacerz) rlrzrmrcrir`rDrpush_transform)r}rrlrzrrErr~r~rrs  zRandRotate90.__call__cCs0||}|tjs |S|tj}t||Sr)rrN DO_TRANSFORMrrcr)r}r xform_infoZ rotate_xformr~r~rrs   zRandRotate90.inverse)rerfr_F) rgrRrhr*r`rarzrxrrrrrjrrTNrrrlrxrzrrrr) rrrrrcrr|rlrrrr~r~rrrds  rdc sreZdZdZejZdddddejej de j df d'ddZ d(d)fdd Z      d*d+d#d$Zd,d%d&ZZS)-rea Randomly rotate the input arrays. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: range_x: Range of rotation angle in radians in the plane defined by the first and second axes. If single number, angle is uniformly sampled from (-range_x, range_x). range_y: Range of rotation angle in radians in the plane defined by the first and third axes. If single number, angle is uniformly sampled from (-range_y, range_y). only work for 3D data. range_z: Range of rotation angle in radians in the plane defined by the second and third axes. If single number, angle is uniformly sampled from (-range_z, range_z). only work for 3D data. prob: Probability of rotation. keep_size: If it is False, the output shape is adapted so that the input array is contained completely in the output. If it is True, the output shape is the same as the input. Default is True. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. Defaults to ``float32``. 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 to indicate whether this transform should execute lazily or not. Defaults to False reTFrange_xtuple[float, float] | floatrange_yrange_zrgrRrJrxrsrvrurwryr(rzrrc Cst||tj|| dt||_t|jdkr)tt|jd |jdg|_t||_t|jdkrEtt|jd |jdg|_t||_ t|j dkratt|j d |j dg|_ ||_ ||_ ||_ ||_ | |_d|_d|_d|_dS)Nr{rrry)r-r|r+rErzrr5sortedr|r}rJrsrurwryxyz) r}rzr|r}rgrJrsrurwryrzr~r~rr|9s&        zRandRotate.__init__Nrrjcsttd|js dS|jj|jd|jdd|_|jj|jd|jdd|_|jj|j d|j dd|_ dS)Nrrlowhigh) rrlrmruniformrzrr|rr}rrrr~rrl\s "zRandRotate.randomizerrrrrlc Cs|r||dur |jn|}|jrUtt|tr|n|jdd} t| dkr,|j n|j |j |j f|j |p9|j |p=|j|durD|jn||pL|jpL|j|d} | |} n t|ttjd} |j| d|d| S)aq Args: img: channel first array, must have shape 2D: (nchannels, H, W), or 3D: (nchannels, H, W, D). mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. randomize: whether to execute `randomize()` function first, default to True. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Nrrb)rHrJrsrurwryrzrryTrq)rlrzrmrrrrrrarrrrJrsrurwryrDrrrGrs) r}rrsrurwryrlrzrr3Zrotatorrr~r~rrds$$ zRandRotate.__call__cCs.||}|tjs |Std||tjS)Nr)rrNrtrarrr}rrur~r~rrs  zRandRotate.inverse)rzr{r|r{r}r{rgrRrJrxrsrvrurvrwrxryr(rzrxrrrrvNNNNTN)rrrsrrurrwrryr(rlrxrzrr)rrrrrarr<rr=rrrGr|rlrrrr~r~rrres.  #  2rec@sJeZdZdZejZddd dZejj dddZdd ddZ d!ddZ dS)"rfa) Randomly flips the image along axes. Preserves shape. See numpy.flip for additional details. https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: prob: Probability of flipping. spatial_axis: Spatial axes along which to flip over. Default is None. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False reNFrgrRrrrzrxrrcCs,t||tj||dt||d|_dS)Nr{)rrz)r-r|r+r[r )r}rgrrzr~r~rr|s zRandFlip.__init__rcC||j_||_dSrr rzrrr~r~rrz z RandFlip.lazyTrrrlrcCsZ|r|d|dur|jn|}|jr|j||dn|}t|td}|j|d|d|Srp)rlrzrmr rDrrsr}rrlrzrrr~r~rrs zRandFlip.__call__rcCs6||}|tjs |S|j|tj|j|Sr)rrNrtapplied_operationsrrr rr?r~r~rrs   zRandFlip.inverse)reNF)rgrRrrrzrxrrrrxrwrxr) rrrrr[rr|r+rzrrrr~r~r~rrfs   rfcs\eZdZdZejZddd d Zejj dd dZd fdd Z d!d"ddZ d#ddZ Z S)$rha Randomly select a spatial axis and flip along it. See numpy.flip for additional details. https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: prob: Probability of flipping. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False reFrgrRrzrxrrcCs2t||tj||dd|_t|jd|_dS)Nr{r)r-r|r+_axisr[r )r}rgrzr~r~rr|s zRandAxisFlip.__init__rcCrrrrr~r~rrzrzRandAxisFlip.lazyrr cs.td|js dS|j|jd|_dSrk)rrlrmrrnr3rrrr~rrlrozRandAxisFlip.randomizeTNrrrlrcCsd|r|j|d|dur|jn|}|jr!|j|j_|j||d}nt|td}|j|d|d|S)a Args: img: channel first array, must have shape: (num_channels, H[, W, ..., ]) randomize: whether to execute `randomize()` function first, default to True. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. )rNr{rTrq) rlrzrmrr rrDrrsrr~r~rrs  zRandAxisFlip.__call__cCsh||}|tjs |St|tjtjdd}|d ||WdS1s-wYdS)NrdrF)rrNrtr[rr)r}rrr r~r~rr s   $zRandAxisFlip.inverse)reF)rgrRrzrxrrr)rr rrrwrxr)rrrrr[rr|r+rzrrlrrrr~r~rrrhs   rhc sneZdZdZejZdddejej de j ddf d'ddZ d(fdd Z      d)d*d"d#Zd+d%d&ZZS),ria Randomly zooms input arrays with given probability within given zoom range. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: prob: Probability of zooming. min_zoom: Min zoom factor. Can be float or sequence same size as image. If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims to keep the original spatial shape ratio. If a sequence, min_zoom should contain one value for each spatial axis. If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio. max_zoom: Max zoom factor. Can be float or sequence same size as image. If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims to keep the original spatial shape ratio. If a sequence, max_zoom should contain one value for each spatial axis. If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio. mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``"area"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. The mode to pad data after zooming. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html dtype: data type for resampling computation. Defaults to ``float32``. If None, use the data type of input data. keep_size: Should keep original size (pad if needed), default is True. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. reg?g?NTFrgrRmin_zoomrImax_zoomrsrvrurwrryr(rJrxrzrrc Kst||tj|| dt||_t||_t|jt|jkr2tdt|jdt|jd||_||_ ||_ ||_ ||_ | |_ dg|_dS)Nr{z1min_zoom and max_zoom must have same length, got z and r?)r-r|r+rErrrrrsrurwryrJrXrY) r}rgrrrsrurwryrJrzrXr~r~rr|>s    zRandZoom.__init__rr cstdjs dSfddtjjD_tjdkr/tjd|j d_dStjdkrP|j dkrRtjd|j dt jd_dSdSdS)Ncsg|] \}}j||qSr~)rr)r,lhr}r~r `z&RandZoom.randomize..rrrbrfr) rrlrmrrrrYrrFr3rE)r}rrrrrl\s *zRandZoom.randomizerrrlc Cs|r|j|d|dur|jn|}|jst|ttjd} n&t|jf|j |p(|j |p,|j |dur3|j n||p8|j |d|j} | |} |j| d|d| S)aQ Args: img: channel first array, must have shape 2D: (nchannels, H, W), or 3D: (nchannels, H, W, D). mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}, the interpolation mode. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"constant"``. The mode to pad data after zooming. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. randomize: whether to execute `randomize()` function first, default to True. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. )rNr)rJrsrurwryrzTrq)rlrzrmrDrrrGrbrYrJrsrurwryrXrs) r}rrsrurwryrlrzrrrEr~r~rrhs("  zRandZoom.__call__rcCs0||}|tjs |St|j||tjSr)rrNrtrbrYrrrr~r~rrs  zRandZoom.inverse)rgrRrrIrrIrsrvrurvrwrryr(rJrxrzrxrr)rr rrr)rrrsrrurrwrryr(rlrxrzrrrr)rrrrrbrr>rFr?r^rrGr|rlrrrr~r~rrris,)  7ric @sFeZdZdZejgZdddddejdddf dddZ dd ddZ dS)!rja Affine transforms on the coordinates. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: rotate_params: a rotation angle in radians, a scalar for 2D image, a tuple of 3 floats for 3D. Defaults to no rotation. shear_params: shearing factors for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] a tuple of 2 floats for 2D, a tuple of 6 floats for 3D. Defaults to no shearing. translate_params: a tuple of 2 floats for 2D, a tuple of 3 floats for 3D. Translation is in pixel/voxel relative to the center of the input image. Defaults to no translation. scale_params: scale factor for every spatial dims. a tuple of 2 floats for 2D, a tuple of 3 floats for 3D. Defaults to `1.0`. dtype: data type for the grid computation. Defaults to ``float32``. If ``None``, use the data type of input data (if `grid` is provided). device: device on which the tensor will be allocated, if a new grid is generated. align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html affine: If applied, ignore the params (`rotate_params`, etc.) and use the supplied matrix. Should be square with each side = num of image spatial dimensions + 1. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False NF rotate_paramsr' shear_paramstranslate_params scale_paramsdevicetorch.device | Noneryr rwrxrNdarrayOrTensor | Nonerzrrc Csftj|| d||_||_||_||_||_t|tj } | tj tj dfvr'| ntj |_ ||_||_dSr)r+r|rrrrrrSrrfloat16rrGryrwr) r}rrrrrryrwrrzr<r~r~rr|s   zAffineGrid.__init__rSequence[int] | Nonegridrr(tuple[torch.Tensor | None, torch.Tensor]c Cs|dur|jn|}|s@|dur"|durtdt||jd|jd}n|}|jp)|j}t||td}t|j}t|j d}n|j}t|}t j } |j durtj |d|d} |jrf| t||j|| d} |jrt| t||j|| d} |jr| t||j|| d} |jr| t||j|| d} n|j } t|| } |rd| fSt| |j|jd d } |jrt|d d |j ddD|| d} t| | d } | | ||j d dfdgt|j dd}|| fS| ||j d dfdgt|j dd}|| fS)a  The grid can be initialized with a `spatial_size` parameter, or provided directly as `grid`. Therefore, either `spatial_size` or `grid` must be provided. When initialising from `spatial_size`, the backend "torch" will be used. Args: spatial_size: output grid size. grid: grid to be transformed. Shape must be (3, H, W) for 2D or (4, H, W, D) for 3D. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Raises: ValueError: When ``grid=None`` and ``spatial_size=None``. Incompatible values. Nz5Incompatible values: grid=None and spatial_size=None.r)rrry)ryrrrrrF)rryrcSs$g|]}t|dt|ddqS)rbr)rr,dr~r~rrs$z'AffineGrid.__call__..rr)rzrr0rryrDrrrrrOrrrrr1rr3rr4rr2rrwrBviewr) r}rrrzrgrid_r<_device spatial_dims_brscr~r~rrsN    62zAffineGrid.__call__)rr'rr'rr'rr'rrryr rwrxrrrzrxrrNNN)rrrrrzrrr) rrrrrOrrrrGr|rr~r~r~rrjs# rjc@sheZdZdZejZdddddejdfd)ddZd*d+ddZ d,d-ddZ    d.d/d$d%Z d0d'd(Z dS)1rkz Generate randomised affine grid. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NF rotate_range RandRange shear_rangetranslate_range scale_rangerrryr rzrxrrcCsptj||dt||_t||_t||_t||_d|_d|_d|_ d|_ ||_ ||_ t jdt jd|_dS)a Args: rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then `uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used. This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]` for dim0 and nothing for the remaining dimensions. shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select shearing factors(a tuple of 2 floats for 2D, a tuple of 6 floats for 3D) for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] translate_range: translate range with format matching `rotate_range`, it defines the range to randomly select voxels to translate for every spatial dims. scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select the scale factor to translate for every spatial dims. A value of 1.0 is added to the result. This allows 0 to correspond to no change (i.e., a scaling of 1.0). device: device to store the output grid data. dtype: data type for the grid computation. Defaults to ``np.float32``. If ``None``, use the data type of input data (if `grid` is provided). lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False See also: - :py:meth:`monai.transforms.utils.create_rotate` - :py:meth:`monai.transforms.utils.create_shear` - :py:meth:`monai.transforms.utils.create_translate` - :py:meth:`monai.transforms.utils.create_scale` r{Nrr)r+r|rErrrrrrrrrryrrrr)r}rrrrrryrzr~r~rr|.s/    zRandAffineGrid.__init__ry add_scalarrRcCszg}|D]6}t|r)t|dkrtd|d||j|d|d|q|dur:||j| ||q|S)NrbzBIf giving range as [min,max], should have 2 elements per dim, got rrr)rIrrrrr)r}Z param_ranger out_paramfr~r~r_get_rand_paramls "zRandAffineGrid._get_rand_paramrrjcCs>||j|_||j|_||j|_||jd|_dS)Nr) rrrrrrrrrrr~r~rrlwszRandAffineGrid.randomizeTrrrrrlrrc Csl|r||dur |jn|}t|j|j|j|j|j|j|d}|r,|||d|_ dS|||\}|_ |S)aO Args: spatial_size: output grid size. grid: grid to be transformed. Shape must be (3, H, W) for 2D or (4, H, W, D) for 3D. randomize: boolean as to whether the grid parameters governing the grid should be randomized. lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Returns: a 2D (3xHxW) or 3D (4xHxWxD) grid. N)rrrrrryrzr) rlrzrjrrrrrryr)r}rrrlrzr affine_gridZ_gridr~r~rr}s" zRandAffineGrid.__call__rcCs|jS)z3Get the most recently applied transformation matrixrrr~r~rget_transformation_matrixsz(RandAffineGrid.get_transformation_matrix)rrrrrrrrrrryr rzrxrr)ry)rrRrrv)NNTN) rrrrrlrxrzrrr)rr) rrrrrjrrrGr|rrlrrr~r~r~rrk$s& >  &rkc@s:eZdZdZejgZ ddd d ZdddZdddZ dS)rlz+ Generate random deformation grid. NspacingrImagnitude_rangetuple[float, float]rrrrcCs ||_||_d|_|||_dS)a Args: spacing: spacing of the grid in 2D or 3D. e.g., spacing=(1, 1) indicates pixel-wise deformation in 2D, spacing=(1, 1, 1) indicates voxel-wise deformation in 3D, spacing=(2, 2) indicates deformation field defined on every other pixel in 2D. magnitude_range: the random offsets will be generated from `uniform[magnitude[0], magnitude[1])`. device: device to store the output grid data. rN)r magnituderand_magr)r}rrrr~r~rr|s   zRandDeformGrid.__init__ grid_size Sequence[int]cCsJ|jjt|gt|djtjdd|_|j|j d|j d|_ dS)N)rFrrr) rnormalrrastyperrG random_offsetrrrr}rr~r~rrls* zRandDeformGrid.randomizerrcCspt|jdt||_t||j|jdd}||jddt|j|j |^}}|dt||7<|S)zK Args: spatial_size: spatial size of the grid. rrrrN) rHrrr/rrlrrBrr)r}rZ control_grid_offsetrr~r~rrs zRandDeformGrid.__call__r)rrIrrrrrrrrrr)rrrr) rrrrrOrrr|rlrr~r~r~rrls rlc@sLeZdZejejgZeje j ddde j fdddZ     ddddZdS)rmTNFrsrtrurv norm_coordsrxrrrwryr rrcCs(||_||_||_||_||_||_dS)a) computes output image using values from `img`, locations from `grid` using pytorch. supports spatially 2D or 3D (num_channels, H, W[, D]). Args: mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `USE_COMPILED` is `True`, this argument uses ``"nearest"``, ``"bilinear"``, ``"bicubic"`` to indicate 0, 1, 3 order interpolations. See also: https://docs.monai.io/en/stable/networks.html#grid-pull (experimental). 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. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `USE_COMPILED` is `True`, this argument uses an integer to represent the padding mode. See also: https://docs.monai.io/en/stable/networks.html#grid-pull (experimental). 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 norm_coords: whether to normalize the coordinates from `[-(size-1)/2, (size-1)/2]` to `[0, size - 1]` (for ``monai/csrc`` implementation) or `[-1, 1]` (for torch ``grid_sample`` implementation) to be compatible with the underlying resampling API. device: device on which the tensor will be allocated. align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html dtype: data type for resampling computation. Defaults to ``float64`` for best precision. If ``None``, use the data type of input data. To be compatible with other modules, the output data type is always `float32`. N)rsrurrrwry)r}rsrurrrwryr~r~rr|s + zResample.__init__rrrrrrrcspt|td}|dur |St|tjr|jn|j}|p |jp |j}|dur(|jn|} t|tj||d^} } t t t| t r@| n| j ddd} t|durR|jn||durZ|jn|dtd\} } tsl| tjkr:t|d| | |jdd^}} t|tjr||kr|jtjd }t| j dd| D]9\}}td |}|dd }|jr| r|d||||n|||||<q| r|d|||d ||<qtr| tjkrt|d d}t| d |d | ddd }n| tjkr9| j }|rt!nt"| dd}t|||jdd^} |rt#nt$j%|r#t&nt'(fdd|D}t|| d }nrt|t)t*| dddd d}t|| ddd d }t|tjrm||krm|jtjd }|jrt| j | dd dD]\}}|d d|fd td |9<q}tj+j,j-| d || t.j/krdn| dd }t||t'j0d^}} |S)a Args: img: shape must be (num_channels, H, W[, D]). grid: shape must be (3, H, W) for 2D or (4, H, W, D) for 3D. if ``norm_coords`` is True, the grid values must be in `[-(size-1)/2, (size-1)/2]`. if ``USE_COMPILED=True`` and ``norm_coords=False``, grid values must be in `[0, size-1]`. if ``USE_COMPILED=False`` and ``norm_coords=False``, grid values must be in `[-1, 1]`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `USE_COMPILED` is `True`, this argument uses ``"nearest"``, ``"bilinear"``, ``"bicubic"`` to indicate 0, 1, 3 order interpolations. See also: https://docs.monai.io/en/stable/networks.html#grid-pull (experimental). 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. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `USE_COMPILED` is `True`, this argument uses an integer to represent the padding mode. See also: https://docs.monai.io/en/stable/networks.html#grid-pull (experimental). 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 dtype: data type for resampling computation. Defaults to ``self.dtype``. To be compatible with other modules, the output data type is always `float32`. align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html See also: :py:const:`monai.config.USE_COMPILED` rN)ryrrrf)r use_compiledT)ry wrap_sequence) memory_formatrb@?rr)bound extrapolate interpolation)rcsg|] }|dqS))orderrsr~)r,c _interp_modeZ _map_coordrKZgrid_npr~rr\z%Resample.__call__...)rsrurwrP)1rDrrrrrryrwrRrrrrrr6rsrur rOrrBdata_ptrclonecontiguous_formatrrrrr;rrQtois_cudarArCcupy_ndinp_ndimap_coordinatesrVrstackrrBnn functional grid_samplerNrrG)r}rrrsruryrwrr<r;rUrrrZgrid_tidim_dimtrrimg_npZout_valr~rrr s)*  .     $zResample.__call__)rsrtrurvrrxrrrwrxryr rrr)rrrrrsrrurryr rwrrr)rrrrOrrrr<rr=rrrr|rr~r~r~rrms  5rmc@seZdZdZeeejeej@Zdddddde j e j dde jdddfd.ddZejjd/dd Z    d0d1d'd(Zed)d*Zd2d,d-ZdS)3rna/ Transform ``img`` given the affine parameters. A tutorial is available: https://github.com/Project-MONAI/tutorials/blob/0.6.0/modules/transforms_demo_2d.ipynb. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NFrr'rrrrrrrrsrtrurvrMrxrrryr rw image_onlyrzrrc Csbtj||dt|||||| | | |d |_| |_| |_t|j| | | d|_||_||_ ||_ dS)a" The affine transformations are applied in rotate, shear, translate, scale order. Args: rotate_params: a rotation angle in radians, a scalar for 2D image, a tuple of 3 floats for 3D. Defaults to no rotation. shear_params: shearing factors for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] a tuple of 2 floats for 2D, a tuple of 6 floats for 3D. Defaults to no shearing. translate_params: a tuple of 2 floats for 2D, a tuple of 3 floats for 3D. Translation is in pixel/voxel relative to the center of the input image. Defaults to no translation. scale_params: scale factor for every spatial dims. a tuple of 2 floats for 2D, a tuple of 3 floats for 3D. Defaults to `1.0`. affine: If applied, ignore the params (`rotate_params`, etc.) and use the supplied matrix. Should be square with each side = num of image spatial dimensions + 1. spatial_size: output image spatial size. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"reflection"``. 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 normalized: indicating whether the provided `affine` is defined to include a normalization transform converting the coordinates from `[-(size-1)/2, (size-1)/2]` (defined in ``create_grid``) to `[0, size - 1]` or `[-1, 1]` in order to be compatible with the underlying resampling API. If `normalized=False`, additional coordinate normalization will be applied before resampling. See also: :py:func:`monai.networks.utils.normalize_transform`. device: device on which the tensor will be allocated. dtype: data type for resampling computation. Defaults to ``float32``. If ``None``, use the data type of input data. To be compatible with other modules, the output data type is always `float32`. align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html image_only: if True return only the image volume, otherwise return (image, affine). lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r{) rrrrrryrwrrz)rrryrwN) r+r|rjrrZ norm_coordrm resamplerrrsru)r}rrrrrrrsrurMrryrwrrzr~r~rr|}s$I  zAffine.__init__rcCrr)rrzrrr~r~rrzrz Affine.lazyrrrrr3torch.Tensor | tuple[torch.Tensor, NdarrayOrTensor]c Cst|td}t|tr|n|jdd}t|dur|jn||}|dur*|jn|}|dur2|n|j } |dur;|n|j } |j ||d\} } t || | |j || | d|j||d S)a Args: img: shape must be (num_channels, H, W[, D]), spatial_size: output image spatial size. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if `img` has two spatial dimensions, `spatial_size` should have 2 elements [h, w]. if `img` has three spatial dimensions, `spatial_size` should have 3 elements [h, w, d]. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. 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 lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. rrN)rrzTr)rDrrrrrrHrrzrsrurr rrr) r}rrrsrurzr9r8rr:rKrrr~r~rrs( zAffine.__call__cCsft|}t||}t|dd|d|D}t|dd|d|D}|t|tjd|}|S)NcSsg|] }t|ddqSrrbrRrr~r~rr rz+Affine.compute_w_affine..cSsg|] }t|d dqSrrrr~r~rr rr)r*rr4rRrr)cls spatial_rankrVr9r8rZshift_1Zshift_2r~r~rcompute_w_affine s  zAffine.compute_w_affinercCs||}|tj}|tjd}|tjd}|tjd}|tjd}tt|}t|||jdd}t||d} | |\} } |j || |||d} t | t sUt | } |j | _ t | tjd} ttt| d ||jd d|| ^}} | j|_| S) Nrrsrurwrr)rrw)rwr)rrNrrr:rCrBryrjrrrrrRrrrrnrrrr)r}rrrD fwd_affinersrurw inv_affinerrrrrrEr~r~rr s(      "zAffine.inverse)rr'rr'rr'rr'rrrrrsrtrurvrMrxrrryr rwrxrrxrzrxrrr)NNNN) rrrrrsrrurrzrrrr)rrrrrsetrjrrmr<rr= REFLECTIONrrGr|r+rzrr classmethodrrr~r~r~rrnrs8 \  6 rnc seZdZdZejZddddddejej dddf d8ddZ e j j d9ddZ d:ddZd;d!d"Zdd?fd+d, Z    -  d@dAd4d5ZdBd6d7ZZS)Croa Random affine transform. A tutorial is available: https://github.com/Project-MONAI/tutorials/blob/0.6.0/modules/transforms_demo_2d.ipynb. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. reNFrgrRrrrrrrrrsrtrurv cache_gridrxrrrzrrc Csdt||tj|| dt||||| | d|_t| d|_||_| |_| | |_ ||_ ||_ dS)a Args: prob: probability of returning a randomized affine grid. defaults to 0.1, with 10% chance returns a randomized grid. rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then `uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used. This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]` for dim0 and nothing for the remaining dimensions. shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select shearing factors(a tuple of 2 floats for 2D, a tuple of 6 floats for 3D) for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] translate_range: translate range with format matching `rotate_range`, it defines the range to randomly select pixel/voxel to translate for every spatial dims. scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select the scale factor to translate for every spatial dims. A value of 1.0 is added to the result. This allows 0 to correspond to no change (i.e., a scaling of 1.0). spatial_size: output image spatial size. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``bilinear``. 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. Defaults to ``reflection``. 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 cache_grid: whether to cache the identity sampling grid. If the spatial size is not dynamically defined by input image, enabling this option could accelerate the transform. device: device on which the tensor will be allocated. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False See also: - :py:class:`RandAffineGrid` for the random affine parameters configurations. - :py:class:`Affine` for the affine transformation parameters configurations. r{rrrrrrzrN) r-r|r+rkrand_affine_gridrmrrr_init_identity_cache _cached_gridrsru) r}rgrrrrrrsrurrrzr~r~rr|B s F   zRandAffine.__init__rcCrr)rrrzrr~r~rrz rzRandAffine.lazycCs|rdS|jdur|jrtddSt|j}t|}|t|dg|ks0|t|dg|kr?|jr=td|jddSt||jj ddS) za Create cache of the identity grid if cache_grid=True and spatial_size is known. Nz_cache_grid=True is not compatible with the dynamic spatial_size, please specify 'spatial_size'.rrbzNcache_grid=True is not compatible with the dynamic spatial_size 'spatial_size=z!', please specify 'spatial_size'.rrrr) rrrrrErrHr0rr)r}rzZ_sp_size_ndimr~r~rr s&  (zRandAffine._init_identity_cachercCsj|rdSt|}|t|dg|ks|t|dg|kr$td|d|jdur2t||jjddS|jS)z Return a cached or new identity grid depends on the availability. Args: spatial_size: non-dynamic spatial size Nrrbz(spatial_size should not be dynamic, got rrr)rrHrrr0rr)r}rrzr3r~r~rget_identity_grid s  zRandAffine.get_identity_gridseed int | Nonestatenp.random.RandomState | Nonec |j||t|||Srrset_random_staterr}rrrr~rr zRandAffine.set_random_staterrjcs$td|js dS|jdSr)rrlrmrrrr~rrl s zRandAffine.randomizeTrrrrrlrc CsF|r|t|tr|n|jdd}t|dur|jn||} |jp*| t|k} |dur1|n|j } |dur:|n|j } |durD|j n|} t |t d}| rw|jrd|dur^|j| |dd|j}n-ttt| d||jjdd}n|dur|| | }|jr|j||| d}|j}t||||j| | | | d| |d S) a4 Args: img: shape must be (num_channels, H, W[, D]), spatial_size: output image spatial size. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if `img` has two spatial dimensions, `spatial_size` should have 2 elements [h, w]. if `img` has three spatial dimensions, `spatial_size` should have 3 elements [h, w, d]. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. 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 randomize: whether to execute `randomize()` function first, default to True. grid: precomputed grid to be used (mainly to accelerate `RandAffined`). lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. rNrT)rlrzrr)rrlrzr)rlrrrrrHrrmrErsrurzrDrrrrBrrrryrr rr)r}rrrsrurlrrzZori_sizer8 do_resamplingr:rKrrr~r~rr sB$  &  zRandAffine.__call__cCs||}|tjds|S|tj}t||jdd}|tjd}|tjd}|tjd}tt|}t|||j dd}t |d}||\} } | || ||} t | t s^t | } |j| _t| tjd} ttt| d||jdd|| ^} } | j| _| S) Nrrrrsrurrr)rrNrrrHrr:rCrBryrjrrrrrRrrrrnrrr)r}rrrDrrsrurrrrrrrEr~r~rr s,      "zRandAffine.inverse)rgrRrrrrrrrrrrrsrtrurvrrxrrrzrxrrr)rzrx)rrrzrxNN)rrrrrrorrv)NNNTNN)rrrrrsrrurrlrxrzrrrr)rrrrrnrr<rr=rr|r+rzrrrrrlrrrr~r~rrro7 s: X     Jroc sveZdZdZejZddddddejej df d/ddZ d0d1fdd Z d!d"Z d2fd$d% Z    &d3d4d-d.ZZS)5rpz Random elastic deformation and affine in 2D. A tutorial is available: https://github.com/Project-MONAI/tutorials/blob/0.6.0/modules/transforms_demo_2d.ipynb. reNrr{rrrgrRrrrrrrtuple[int, int] | int | Nonersrtrurvrrrrc CsZt||t||| d|_t||||| dd|_t| d|_| |_||_ | |_ | |_ dS)al Args: spacing : distance in between the control points. magnitude_range: the random offsets will be generated from ``uniform[magnitude[0], magnitude[1])``. prob: probability of returning a randomized elastic transform. defaults to 0.1, with 10% chance returns a randomized elastic transform, otherwise returns a ``spatial_size`` centered area extracted from the input image. rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then `uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used. This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]` for dim0 and nothing for the remaining dimensions. shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select shearing factors(a tuple of 2 floats for 2D) for affine matrix, take a 2D affine as example:: [ [1.0, params[0], 0.0], [params[1], 1.0, 0.0], [0.0, 0.0, 1.0], ] translate_range: translate range with format matching `rotate_range`, it defines the range to randomly select pixel to translate for every spatial dims. scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select the scale factor to translate for every spatial dims. A value of 1.0 is added to the result. This allows 0 to correspond to no change (i.e., a scaling of 1.0). spatial_size: specifying output image spatial size [h, w]. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"reflection"``. 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 device: device on which the tensor will be allocated. See also: - :py:class:`RandAffineGrid` for the random affine parameters configurations. - :py:class:`Affine` for the affine transformation parameters configurations. )rrrFrrN) r-r|rl deform_gridrkrrmrrrrsru) r}rrrgrrrrrrsrurr~r~rr|F s B  zRand2DElastic.__init__rrrrcs.|j|||j||t|||Sr)r rrrrrr~rr szRand2DElastic.set_random_statecCs"||j_||j_||j_||_dSr)r rrrr}rr~r~r set_device s zRand2DElastic.set_devicercs0td|js dS|j||jdSr)rrlrmr r)r}rrr~rrl s  zRand2DElastic.randomizeTrrrrrlrxc Cst|dur|jn||jdd}|r|j|d|jrI|j|d}|j|d}tjj j d| dt t |jjtjjdd}t|d |d}nt|tjrR|jn|j}ttjt||d d }|j|||durj|n|j|durr|n|jd } | S) a" Args: img: shape must be (num_channels, H, W), spatial_size: specifying output image spatial size [h, w]. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. 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 randomize: whether to execute `randomize()` function first, default to True. NrrOrTrF)recompute_scale_factorinput scale_factorrsrw)roi_sizerrrsru)rHrrrlrmr rrrr interpolaterQrrErr>BICUBICvaluerrrrr r0rrsru) r}rrrsrurlr8rrrr~r~rr s."   zRand2DElastic.__call__)rr{rrrgrRrrrrrrrrrr rsrtrurvrrrrr)rrrrrrp)rrrrNNNT) rrrr rsrrurrlrxrrrrrrrmrr<rr=rr|rr rlrrr~r~rrrp= s* S rpc sveZdZdZejZddddddejej df d/ddZ d0d1fdd Z d d!Z d2fd$d% Z    &d3d4d-d.ZZS)5rqz Random elastic deformation and affine in 3D. A tutorial is available: https://github.com/Project-MONAI/tutorials/blob/0.6.0/modules/transforms_demo_2d.ipynb. reN sigma_rangerrrgrRrrrrrr!tuple[int, int, int] | int | Nonersrtrurvrrrrc Csft||t||||| dd|_t| d|_||_||_||_| |_ | |_ | |_ |d|_ d|_ dS)ad Args: sigma_range: a Gaussian kernel with standard deviation sampled from ``uniform[sigma_range[0], sigma_range[1])`` will be used to smooth the random offset grid. magnitude_range: the random offsets on the grid will be generated from ``uniform[magnitude[0], magnitude[1])``. prob: probability of returning a randomized elastic transform. defaults to 0.1, with 10% chance returns a randomized elastic transform, otherwise returns a ``spatial_size`` centered area extracted from the input image. rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then `uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used. This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]` for dim0 and nothing for the remaining dimensions. shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select shearing factors(a tuple of 6 floats for 3D) for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] translate_range: translate range with format matching `rotate_range`, it defines the range to randomly select voxel to translate for every spatial dims. scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select the scale factor to translate for every spatial dims. A value of 1.0 is added to the result. This allows 0 to correspond to no change (i.e., a scaling of 1.0). spatial_size: specifying output image spatial size [h, w, d]. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, 32, -1)` will be adapted to `(32, 32, 64)` if the third spatial dimension size of img is `64`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"reflection"``. 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 device: device on which the tensor will be allocated. See also: - :py:class:`RandAffineGrid` for the random affine parameters configurations. - :py:class:`Affine` for the affine transformation parameters configurations. FrrrN)r-r|rkrrmrrrrrsrurrsigma) r}rrrgrrrrrrsrurr~r~rr| s& E  zRand3DElastic.__init__rrrrcrrrrrr~rrG rzRand3DElastic.set_random_statecCs||j_||j_||_dSr)rrrr r~r~rr L s zRand3DElastic.set_devicerrcstd|js dS|jdddgt|jtjdd|_ |j|j d|j d|_ |j|j d|j d|_ |jdS)NgrrfFrrr)rrlrmrrrrrrG rand_offsetrrrrrrrr~rrlQ s (zRand3DElastic.randomizeTrrrrrlrxc Cst|dur|jn||jdd}|r|j|dt|tjr"|jn|j}t||dd}|j re|j dur8t dt d|j dj|d } tj|j |d d } |dd| | d |j7<|j|d }|j|||duro|n|j|durw|n|jd } | S) a3 Args: img: shape must be (num_channels, H, W, D), spatial_size: specifying spatial 3D output image spatial size [h, w, d]. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. 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 randomize: whether to execute `randomize()` function first, default to True. Nr)rrrzrand_offset is not initialized.rfg@rrr r)rHrrrlrrrrr0rmrrrrrrrQrrrrsru) r}rrrsrurlr8rrgaussianrrr~r~rrZ s&"  " zRand3DElastic.__call__)rrrrrgrRrrrrrrrrrrrsrtrurvrrrrr)rrrrrrqrr) rrrrrsrrurrlrxrrrr~r~rrrq s* [ rqc@s<eZdZejgZejej dfdddZ   ddddZ dS)r\N num_cellstuple[int] | int distort_stepsSequence[Sequence[float]]rsrtrurvrrrrcCs&t|||d|_||_||_||_dS)a Grid distortion transform. Refer to: https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/transforms.py Args: num_cells: number of grid cells on each dimension. distort_steps: This argument is a list of tuples, where each tuple contains the distort steps of the corresponding dimensions (in the order of H, W[, D]). The length of each tuple equals to `num_cells + 1`. Each value in the tuple represents the distort step of the related cell. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"border"``. 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 device: device on which the tensor will be allocated. )rsrurN)rmrrrr)r}rrrsrurr~r~rr| s  zGridDistortion.__init__rrSequence[Sequence] | NonercCsb|dur|jn|}t|jt|dkrtdg}t|jt|jd}t|tr2|jr2t dt |jddD]Z\}}||} t j |t jd} |||} d} t||dD],} t| | }|| }||krp|}|}n| | | | }t | |||| ||<|} q[| |dd} || q;t|}t g|t |d}|j||||d S) a, Args: img: shape must be (num_channels, H, W[, D]). distort_steps: This argument is a list of tuples, where each tuple contains the distort steps of the corresponding dimensions (in the order of H, W[, D]). The length of each tuple equals to `num_cells + 1`. Each value in the tuple represents the distort step of the related cell. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. 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 NrzKthe spatial size of `img` does not match with the length of `distort_steps`NMetaTensor img has pending operations, transform may return incorrect results.rrrr)rrsru)rrrrrFrrrpending_operationsrrrrzerosrGrBr*linspacerrr ones_liker)r}rrrsru all_rangesrdim_idxdim_sizeZdim_distort_stepsranges cell_sizeprevrstartendcurcoordsrr~r~rr s4    zGridDistortion.__call__) rrrr rsrtrurvrrrrr) rrrr!rsrrurrr) rrrrOrrr<rr=rr|rr~r~r~rr\ s (r\csPeZdZejgZdddejej dfd!ddZ d"fdd Z d#d$dd Z Z S)%rgre)gQgQ?NrrrgrR distort_limitr{rsrtrurvrrrrcCsnt||||_t|ttfrt| |t| |f|_n t|t|f|_d|_ t ||j |||d|_ dS)a Random grid distortion transform. Refer to: https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/transforms.py Args: num_cells: number of grid cells on each dimension. prob: probability of returning a randomized grid distortion transform. Defaults to 0.1. distort_limit: range to randomly distort. If single number, distort_limit is picked from (-distort_limit, distort_limit). Defaults to (-0.03, 0.03). mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. 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. Defaults to ``"border"``. 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 device: device on which the tensor will be allocated. )r)rrrsrurN) r-r|rrr*rRrrr2rr\grid_distortion)r}rrgr2rsrurr~r~rr| s "  zRandGridDistortion.__init__rrcs>tdjs dStfddtjt|D_dS)Nc3s:|]}tdjjjdjd|ddVqdS)rrr)rrrN)r5rrr2)r,Zn_cellsrr~rr0# s ( z/RandGridDistortion.randomize..)rrlrmr5rFrrr)r}rrrrrl s  zRandGridDistortion.randomizeTrrrrlrxcCsZ|rt|tr|jrtd||jdd|js#t|t dS|j ||j ||dS)aJ Args: img: shape must be (num_channels, H, W[, D]). mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``self.mode``. 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. Defaults to ``self.padding_mode``. 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 randomize: whether to shuffle the random factors using `randomize()`, default to True. r"rNr)rrsru) rrr#rrrlrrmrDrr3r)r}rrsrurlr~r~rr( s zRandGridDistortion.__call__)rrrgrRr2r{rsrtrurvrrrr)rrrr)NNT) rrrsrrurrlrxrr)rrrrOrrr<rr=rr|rlrrr~r~rrrg s - rgc@sBeZdZdZejejgZdddd Z ddddZ ddddZ dS)r]a Split the image into patches based on the provided grid in 2D. Args: grid: a tuple define the shape of the grid upon which the image is split. Defaults to (2, 2) size: a tuple or an integer that defines the output patch sizes. If it's an integer, the value will be repeated for each dimension. The default is None, where the patch size will be inferred from the grid shape. Example: Given an image (torch.Tensor or numpy.ndarray) with size of (3, 10, 10) and a grid of (2, 2), it will return a Tensor or array with the size of (4, 3, 5, 5). Here, if the `size` is provided, the returned shape will be (4, 3, size, size) Note: This transform currently support only image with two spatial dimensions. rbrbNrrarint | tuple[int, int] | NonecCs.||_|dur d|_dSt|t|j|_dSr)rrFrr)r}rrr~r~rr|Y s(zGridSplit.__init__imager )int | tuple[int, int] | np.ndarray | Nonerlist[NdarrayOrTensor]cCsh|dur|jnt|t|j}|jdkr|dur|gSt|tr(|jr(td| |j dd|\}}t|t j rFt j }|\}}} nt|tjrXtjjj }|j\}}} n tdt|d|\} } |j d} ||g|j| |d|dR|| | | ||| f} | jdg| j ddR} t|t j rd d | D}|St|tjrd d | D}|S) N)rrr"rz Input type [z] is not supported.rrrbcSsg|]}|qSr~) contiguousr,pr~r~rr sz&GridSplit.__call__..cSsg|]}t|qSr~)rascontiguousarrayr:r~r~rr s)rrFrrrrr#rr _get_paramsrrr as_stridedstriderrlib stride_tricksstridesrtyper4)r}r6r input_size split_sizestepsZas_strided_funcZc_stridex_strideZy_strideZx_stepy_step n_channelsZ strided_imagepatchesr~r~rr` s6       zGridSplit.__call__ image_sizeSequence[int] | np.ndarray!Sequence[int] | np.ndarray | NonecsdurtfddttjDtfddttjDr1tdddtfddttjD}|fS) z Calculate the size and step required for splitting the image Args: The size of the input image Nc3s"|] }|j|VqdSrr r,r)rKr}r~rr0 s z(GridSplit._get_params..c3s |] }||kVqdSrr~rN)rKrr~rr0 r1zThe image size (z+)is smaller than the requested split size ()c3sD|]}j|dkr||j|dn|VqdS)rNr rNrKr}rr~rr0 s 2 )r5rBrranyr)r}rKrrFr~rPrr= s"" zGridSplit._get_params)r4N)rrarr5r)r6r rr7rr8)rKrLrrM) rrrrrOrrrr|rr=r~r~r~rr]E s   &r]c@sReZdZdZejejgZ      d!d"ddZd#ddZ d#ddZ d$dd Z dS)%r^a Extract all the patches sweeping the entire image in a row-major sliding-window manner with possible overlaps. It can sort the patches and return all or a subset of them. Args: patch_size: size of patches to generate slices for, 0 or None selects whole dimension offset: offset of starting position in the array, default is 0 for each dimension. num_patches: number of patches (or maximum number of patches) to return. If the requested number of patches is greater than the number of available patches, padding will be applied to provide exactly `num_patches` patches unless `threshold` is set. When `threshold` is set, this value is treated as the maximum number of patches. Defaults to None, which does not limit number of the patches. overlap: the amount of overlap of neighboring patches in each dimension (a value between 0.0 and 1.0). If only one float number is given, it will be applied to all dimensions. Defaults to 0.0. sort_fn: when `num_patches` is provided, it determines if keep patches with highest values (`"max"`), lowest values (`"min"`), or in their default order (`None`). Default to None. threshold: a value to keep only the patches whose sum of intensities are less than the threshold. Defaults to no filtering. pad_mode: the mode for padding the input image by `patch_size` to include patches that cross boundaries. 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 `None`, which means no padding will be applied. See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html requires pytorch >= 1.10 for best compatibility. pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Returns: MetaTensor: the extracted patches as a single tensor (with patch dimension as the first dimension), with following metadata: - `PatchKeys.LOCATION`: the starting location of the patch in the image, - `PatchKeys.COUNT`: total number of patches in the image, - "spatial_shape": spatial size of the extracted patch, and - "offset": the amount of offset for the patches in the image (starting position of the first patch) Nry patch_sizerrr num_patchesroverlaprIsort_fnr threshold float | Nonepad_modec KsZt||_|r t|ndt|j|_||_||_||_||_|r%|nd|_ ||_ dS)Nr) rErRrrrX pad_kwargsrTrSlowerrUrV) r}rRrrSrTrUrVrXrZr~r~rr| s  zGridPatch.__init__image_npr locations np.ndarrayr"tuple[NdarrayOrTensor, np.ndarray]cCsNt|j}t|ttd||jkd}t|t j d}||||fS)a Filter the patches and their locations according to a threshold. Args: image_np: a numpy.ndarray or torch.Tensor representing a stack of patches. locations: a numpy.ndarray representing the stack of location of each patch. Returns: tuple[NdarrayOrTensor, numpy.ndarray]: tuple of filtered patches and locations. rrr) rrr9sumr5rBrVr4rRrrr}r\r]n_dimsridx_npr~r~rfilter_threshold s $zGridPatch.filter_thresholdcCs|jdur|d|j}|d|j}||fS|jdurht|j}|jtjkr4t|tt d|}n|jtj krHt|tt d| }n t d|jd|d|j}t |t jd}||}||}||fS)a0 Sort the patches based on the sum of their intensity, and just keep `self.num_patches` of them. Args: image_np: a numpy.ndarray or torch.Tensor representing a stack of patches. locations: a numpy.ndarray representing the stack of location of each patch. Nrz2`sort_fn` should be either "min", "max", or None! provided!r)rUrSrrrLMINr8r`r5rBMAXrrRrrrar~r~r filter_count s    zGridPatch.filter_countrrc Cst|fd|jd|j|jd|jd|j}tt|}t|t j r*t |dnt |d}t |ddddddf}|j durN|||\}}|jr|||\}}|j dur|jt|}|dkr|jdd}|gt|jddR}t|t j rt j|||jd } t j|| gdd }nt j|||j|j|jd } t j|| gdd }t j|d|gddggdd }t|tr|jnt} |j| tj <t|| tj!<t "t #|jt|dfj| d<|j| d<t|| d} d| _$| S)a Extract the patches (sweeping the entire image in a row-major sliding-window manner with possible overlaps). Args: array: a input image as `numpy.ndarray` or `torch.Tensor` Return: MetaTensor: the extracted patches as a single tensor (with patch dimension as the first dimension), with defined `PatchKeys.LOCATION` and `PatchKeys.COUNT` metadata. rrYF)rR start_posrT copy_backrsrrNconstant_valuesr)axis)rylayoutr)r)rkrr)rrT)%rrRrrTrXrZrrrrrrrrVrdrSrhrrrfullry concatenatermrcatpadrrget_default_metaTrMLOCATIONCOUNTtileris_batch) r}rZpatch_iteratorrJZ patched_imager]paddingrkZ padding_shapeZconstant_paddingmetadataoutputr~r~rr sV  (     "  zGridPatch.__call__)NNryNNN)rRrrrrSrrTrIrUrrVrWrXrr\r r]r^rr_)rr rr) rrrrrOrrrr|rdrhrr~r~r~rr^ s (  r^csdeZdZdZejejgZ       d$d%fdd ZddZ d&fdd Z d'd(fd"d# Z Z S))r_a Extract all the patches sweeping the entire image in a row-major sliding-window manner with possible overlaps, and with random offset for the minimal corner of the image, (0,0) for 2D and (0,0,0) for 3D. It can sort the patches and return all or a subset of them. Args: patch_size: size of patches to generate slices for, 0 or None selects whole dimension min_offset: the minimum range of offset to be selected randomly. Defaults to 0. max_offset: the maximum range of offset to be selected randomly. Defaults to image size modulo patch size. num_patches: number of patches (or maximum number of patches) to return. If the requested number of patches is greater than the number of available patches, padding will be applied to provide exactly `num_patches` patches unless `threshold` is set. When `threshold` is set, this value is treated as the maximum number of patches. Defaults to None, which does not limit number of the patches. overlap: the amount of overlap of neighboring patches in each dimension (a value between 0.0 and 1.0). If only one float number is given, it will be applied to all dimensions. Defaults to 0.0. sort_fn: when `num_patches` is provided, it determines if keep patches with highest values (`"max"`), lowest values (`"min"`), in random ("random"), or in their default order (`None`). Default to None. threshold: a value to keep only the patches whose sum of intensities are less than the threshold. Defaults to no filtering. pad_mode: the mode for padding the input image by `patch_size` to include patches that cross boundaries. 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 `None`, which means no padding will be applied. See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html requires pytorch >= 1.10 for best compatibility. pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Returns: MetaTensor: the extracted patches as a single tensor (with patch dimension as the first dimension), with following metadata: - `PatchKeys.LOCATION`: the starting location of the patch in the image, - `PatchKeys.COUNT`: total number of patches in the image, - "spatial_shape": spatial size of the extracted patch, and - "offset": the amount of offset for the patches in the image (starting position of the first patch) NryrRr min_offsetr max_offsetrSrrTrIrUrrVrWrXc s>tjd|d|||||d| ||_||_||_||_dS)Nr~)rRrrSrTrUrVrX)rr|r|r}rSrU) r}rRr|r}rSrTrUrVrXrZrr~rr|v s   zRandGridPatch.__init__csjdur dtj}n tjtj}jdur.tddt|jddjD}n tjtj}tfddt||D_dS)NrYcss|] \}}||VqdSrr~)r,r-r;r~r~rr0 sz*RandGridPatch.randomize..rc3s(|]\}}jj||ddVqdS)rrN)rrn)r,rrrr~rr0 s&) r|rrRrFr}r5rrr)r}rr|r}r~rrrl s  &"zRandGridPatch.randomizer\r r]r^rr_cs|jtjkr*|j|jd}|d|j}t|tj d}||}||}||fS|jdtj tj fvr=t d|jdt ||S)Nrz;`sort_fn` should be either "min", "max", "random" or None! re)rUrLRANDOMr permutationrrSrRrrrfrgrrrh)r}r\r]rrcrr~rrh s zRandGridPatch.filter_countTrrlrxcs|r||t|Sr)rlrr)r}rrlrr~rr s  zRandGridPatch.__call__)NNNryNNN)rRrr|rr}rrSrrTrIrUrrVrWrXrr{T)rr rlrx) rrrrrOrrrr|rlrhrrr~r~rrr_G s ,  r_csReZdZdZejZdejejdddfdddZ dd fdd Z d!d"ddZ Z S)#rra Random simulation of low resolution corresponding to nnU-Net's SimulateLowResolutionTransform (https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/resample_transforms.py#L23) First, the array/tensor is resampled at lower resolution as determined by the zoom_factor which is uniformly sampled from the `zoom_range`. Then, the array/tensor is resampled at the original resolution. re)rrFNrgrRdownsample_modeInterpolateMode | str upsample_mode zoom_rangeSequence[float]rrrrcCs4t||||_||_||_||_||_d|_dS)a Args: prob: probability of performing this augmentation downsample_mode: interpolation mode for downsampling operation upsample_mode: interpolation mode for upsampling operation zoom_range: range from which the random zoom factor for the downsampling and upsampling operation is sampled. It determines the shape of the downsampled tensor. align_corners: This only has an effect when downsample_mode or upsample_mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: False See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html device: device on which the tensor will be allocated. rN)r-r|rrrrwr zoom_factor)r}rgrrrrwrr~r~rr| s  z"RandSimulateLowResolution.__init__rrjcs6td|j|jd|jd|_|jsdSdS)Nrr)rrlrrrrrmrrr~rrl s z#RandSimulateLowResolution.randomizeTrrrlrxc Cs|r||jrU|jdd}ttt||jtj  }t |d|j dd}t |d|j d|jd}t}td||}||} t|t| } | || S|S)z Args: img: shape must be (num_channels, H, W[, D]), randomize: whether to execute `randomize()` function first, defaults to True. rNr"F)rr$rsr%)rr$rsr%rw)rlrmrr5rr+rrrint_tolistr`rrrwrrrcopy_meta_from) r}rrlr7 target_shapeZresize_tfm_downsampleZresize_tfm_upsampleZoriginal_tack_meta_valueZimg_downsampledZ img_upsampledr~r~rr s0&   z"RandSimulateLowResolution.__call__) rgrRrrrrrrrrrrrrvr)rrrlrxrr) rrrrrnrr>NEAREST TRILINEARr|rlrrr~r~rrrr s rrcs:eZdZdZejejgZd dfdd Zdd d Z Z S)ConvertBoxToPointsaG Converts an axis-aligned bounding box to points. It can automatically convert the boxes to the points based on the box mode. Bounding boxes of the shape (N, C) for N boxes. C is [x1, y1, x2, y2] for 2D or [x1, y1, z1, x2, y2, z2] for 3D for each box. Return shape will be (N, 4, 2) for 2D or (N, 8, 3) for 3D. Nrs$str | BoxMode | type[BoxMode] | Nonerrcs&t|durt|_dS||_dS)z Args: mode: the mode of the box, can be a string, a BoxMode instance or a BoxMode class. Defaults to StandardMode. N)rr|rrs)r}rsrr~rr|s zConvertBoxToPoints.__init__rrcCs*t|td}t||jd}t||dS)Nr)rsr)rDrr!rsrB)r}rpointsr~r~rrszConvertBoxToPoints.__call__r)rsrrrrr rrrrrOrrrr|rrr~r~rrr s  rcs8eZdZdZejejgZd fdd Zd dd Z Z S) ConvertPointsToBoxesz Converts points to an axis-aligned bounding box. Points representing the corners of the bounding box. Shape (N, 8, 3) for the 8 corners of a 3D cuboid or (N, 4, 2) for the 4 corners of a 2D rectangle. rrcstdSr)rr|rrr~rr|+szConvertPointsToBoxes.__init__rrcCs$t|td}t|}t||dS)Nrr)rDrr"rB)r}rboxr~r~rr.szConvertPointsToBoxes.__call__)rrrrr~r~rrr"s  r)r __future__rrcollections.abcrrrr itertoolsrtypingrrr r numpyrr monai.configr r monai.config.type_definitionsr Zmonai.data.box_utilsrrmonai.data.meta_objrrmonai.data.meta_tensorrmonai.data.utilsrrrrrrmonai.networks.layersrrrmonai.networks.utilsrZmonai.transforms.croppad.arrayrrmonai.transforms.inverserZ#monai.transforms.spatial.functionalr r!r"r#r$r%r&r'r(r)monai.transforms.traitsr*monai.transforms.transformr+r,r-r.monai.transforms.utilsr/r0r1r2r3r4r5r6r70monai.transforms.utils_pytorch_numpy_unificationr8r9r:r; monai.utilsr<r=r>r?r@rArBrCrDrErFrGrHrIrJmonai.utils.deprecate_utilsrKmonai.utils.enumsrLrMrNrOmonai.utils.miscrPrmonai.utils.modulerQmonai.utils.type_conversionrRrSrTrZhas_nibrVrrr__all__r5rRrrWrXrYrZr[r`rarbrcrdrerfrhrirjrkrlrmrnrorprqr\rgr]r^r_rrrrr~r~r~rs        0 , D       $RT-" 7D5@~,F'*cVV-h\