U Ph@sdZddlmZddlZddlmZddlmZddlm Z ddl m Z m Z m Z mZmZmZddlZddlZddlmZmZdd lmZdd lmZmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$dd l%m&Z&m'Z'm(Z(ddl)m*Z*ddl+m,Z,m-Z-ddl.m/Z/ddl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8ddl9m:Z:ddl;mZ>m?Z?ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZIddlJmKZKmLZLmMZMmNZNddlOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]ddl^m_Z_m`Z`maZambZbddlcmdZeddlfmgZgddlhmiZimjZjmkZke]d\ZlZme]d\ZnZoe]d\ZpZoe]d\ZqZodd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:gZre ee eeesesfesfesfZtGd;dde/e<ZuGdd"d"e/e<ZxGd?d#d#e/e<ZyGd@d(d(e/e<ZzGdAd)d)e/e<Z{GdBd*d*e/e<Z|GdCd+d+e/e<Z}GdDd,d,e>e/e<Z~GdEd-d-e>e/e<ZGdFd.d.e>e/e<ZGdGd0d0e>e/e<ZGdHd1d1e>e/e<ZGdId2d2e<ZGdJd3d3e=e<ZGdKd4d4e=e?ZGdLd5d5e?ZGdMd6d6e/e<ZGdNd7d7e>e/e<ZGdOd8d8e>ZGdPd9d9e>ZGdQd$d$e?ZGdRd/d/e>ZGdSd%d%e?e:ZGdTd&d&e?e:ZGdUd'd'ee>e:ZGdVd:d:e>ZdS)Wz> A collection of "vanilla" transforms for spatial operations. ) annotationsN)Callable)deepcopy) zip_longest)AnyOptionalSequenceTupleUnioncast) USE_COMPILED DtypeLike)NdarrayOrTensor)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_funcflip 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 NumpyPadModeconvert_to_cupyconvert_to_dst_typeconvert_to_numpyconvert_to_tensor ensure_tupleensure_tuple_repensure_tuple_sizefall_back_tupleissequenceiterableoptional_import) GridPatchSort PatchKeys TraceKeysTransformBackends) ImageMetaKey)look_up_option)convert_data_typeget_equivalent_dtypeget_torch_dtype_from_stringnibabelcupyzcupyx.scipy.ndimagez scipy.ndimageSpatialResampleResampleToMatchSpacing OrientationFlipGridDistortion GridSplit GridPatch RandGridPatchResizeRotateZoomRotate90 RandRotate90 RandRotateRandFlipRandGridDistortion RandAxisFlipRandZoom AffineGridRandAffineGridRandDeformGridResampleAffine RandAffine Rand2DElastic Rand3DElasticRandSimulateLowResolutionc @sxeZdZdZejejejgZe j e j de jdfdddddddd Zdd d d dddddd d ddZd d dddZd S)rRa 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. F str | intstrboolr mode padding_mode align_cornersdtypelazycCs*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 rvN)r(__init__rrrsrtru)selfrrrsrtrurvrzS/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/spatial/array.pyrxs zSpatialResample.__init__N torch.Tensortorch.Tensor | Nonez)Sequence[int] | torch.Tensor | int | Nonestr | int | None str | None bool | None) img dst_affine spatial_sizerrrsrtrurvreturnc Cs~t|p|jp|jtj} |dk r$|n|j}|dk r6|n|j}|dk rH|n|j}|dkr\|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. Nrvtransform_info) rNrutorchTensorrtrrrsrvr%get_transform_info) ryrrrrrrsrtrurvZdtype_ptlazy_rzrzr{__call__s 3zSpatialResample.__call__datarc Cs||}|tj}t|d|d<|d|d<|tj|d<|dtjkrXd|d<|dt j ||f|}W5QRX|d|d<|S)NruZ src_affinerrrtF) pop_transformrI EXTRA_INFOrOpop ORIG_SIZEgetNONEtrace_transformrRr)ryr transformkw_argsoutrzrzr{inverses   zSpatialResample.inverse)NNNNNNN)__name__ __module__ __qualname____doc__rJTORCHNUMPYCUPYbackendr9BILINEARr:BORDERnpfloat64rxrrrzrzrzr{rRws" % Dc s6eZdZdZd dddddddddfd d ZZS) rSa  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. Nr|r~rrr )rimg_dstrrrsrtrurvrc s"|dkrtdt|tr"|ntd}|dkr:|jn|} tj||t|trZ| n |j dd||||| d}| st|tr||_ t|tr|j tjd} t|j |_ | |j tj<n`t|trt|tr|j tjd} t|j } dD]} | | dq|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.)rrrrrrsrtrurvZresample_to_match_source)affine spatial_shape) RuntimeError isinstancerpeek_pending_affinereyervsuperrpeek_pending_shapeshapermetarKeyFILENAME_OR_OBJrrupdate) ryrrrrrsrtrurvrrZoriginal_fname meta_dictk __class__rzr{rs:)       zResampleToMatch.__call__)NNNNN)rrrrr __classcell__rzrzrr{rSs c@seZdZdZejZdejej de j dddddf ddddddddd d dd d d d Z e jjdd dddZddddddddddd ddZdddddZdS)rTz Resample input image into the specified `pixdim`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. FNz$Sequence[float] | float | np.ndarrayrprnror z+Sequence[float] | float | np.ndarray | NoneNone) pixdimdiagonalrrrsrtru scale_extentrecompute_affine min_pixdim max_pixdimrvrc Cstj|| dtjt|tjd|_tjt| tjd|_tjt| tjd|_||_ ||_ ||_ t |j|jD]F\} } t | spt | sp| | ks| dkrptd|jd|jdqpt||||| 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 rwrurz min_pixdim z$ must be positive, smaller than max .rqN)r(rxrarrayrArrrrrrrzipisnan ValueErrorrR sp_resample)ryrrrrrsrtrurrrrrvmnmxrzrzr{rxYs"D$zSpacing.__init__valrcCs||_||j_dSN)_lazyrrvryrrzrzr{rvsz Spacing.lazyr|r~rrz'Sequence[int] | np.ndarray | int | None) data_arrayrrrsrtruroutput_spatial_shapervrc  Cst|tr|n |jdd} t| } | dkr@td| dt|trR|nd} | dkr|tdt j | dt j d} t | t | t jd} |jd| } | j| krt | | dg| | j} t| | | j}tt||jd| |jd| t jd D]\}\}}}| |}t |r(|nt||}t |rB|nt||}||krxtd |d |d |d |d |t|kr|tkrnn|n|| |<q|s|rtdt| | |jd}|dkr|j n|}t!| | ||\}}|d| |d| df<|dkr"t"|n|}|dkr6|j#n|}|j$|t%&|||||||d}|j'rt|tr|r|t(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)rrrrrsrtrurvz7recompute_affine is not supported with lazy evaluation.),rrrrlenrrwarningswarnrrrrrMndarrayrcopysizeappendrru enumeraterrrnanrminmaxrrrrrlistrvrr as_tensorrNotImplementedErrorr4r>r)ryrrrrsrtrurrrvZoriginal_spatial_shapesrZ input_affineaffine_out_dZorig_didx_drrtarget new_affine output_shapeoffset actual_shaperarzrzr{rs^4  $ "4    zSpacing.__call__rcCs |j|Sr)rrryrrzrzr{rszSpacing.inverse)NNNNNNN)rrrrrRrr9rr:rrrrxr(rvsetterrrrzrzrzr{rTOs0&T lc@sXeZdZdZejejgZddddddd d d Zdd d d dddZ d d dddZ dS)rUz 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. NF)LR)PA)ISrrpz Sequence[tuple[str, str]] | Noner)axcodesas_closest_canonicallabelsrvrcCsNtj||d|dkr"|s"td|dk r8|r8td||_||_||_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. Defaults to ``(('L', 'R'), ('P', 'A'), ('I', 'S'))``. 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`. rwN@Incompatible values: axcodes=None and as_closest_canonical=True.z1using as_closest_canonical=True, axcodes ignored.)r(rxrrrrrr)ryrrrrvrzrzr{rx,s   zOrientation.__init__r|r)rrvrc Cst|tr|n |jdd}t|}|dkr@td|dt|trjt|tj ^}}t ||}n2t dtj |dtjd}tj |dtjd}t|}|jr|} n|jdkrtd|t|jkr t d |jd |d |jjd |d |jdd tjj|jd||jd} t| |krPtdt|jd|dtj|| } |dkrn|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`. rNrrrzH`data_array` is not of type `MetaTensor, assuming affine to be identity.rrz 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)rrrrrrrMrrrrrrrrnibio_orientationrrrr orientations axcodes2orntrornt_transformrvr!r) ryrrvrr affine_np_rsrcZ spatial_orntdstrrzrzr{rPs6      .zOrientation.__call__rc CsV||}|tjd}tj|}t|d|jd}|d||}W5QRX|S)Noriginal_affineF)rrr) rrIrrr aff2axcodesrUrr)ryrr orig_affineZ orig_axcodesinverse_transformrzrzr{rs   zOrientation.inverse)NFrF)N) rrrrrJrrrrxrrrzrzrzr{rU"s $9c@sPeZdZdZejgZddddddd Zdd d d d d dZd d dddZ dS)rVa7 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 NFSequence[int] | int | Nonerpr) spatial_axisrvrcCstj||d||_dSNrw)r(rxr )ryr rvrzrzr{rxsz Flip.__init__r|rrrvrcCs6t|td}|dkr|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)r@rrvr r r)ryrrvrrzrzr{rsz Flip.__call__rc Cs@||t|jd}|d||W5QRSQRXdS)Nr F)rrVr r)ryrflipperrzrzr{rs   z Flip.inverse)NF)N) rrrrrJrrrxrrrzrzrzr{rVs  c @seZdZdZejgZdejddde j dfdddddd d dd d d dZ dddddd d dddddZ dddddZ dddddZdS)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 allNFzSequence[int] | introrrpSequence[float] | float | NoneDtypeLike | torch.dtyper) r size_moderrrt anti_aliasinganti_aliasing_sigmarurvrc CsFtj||dt|ddg|_||_||_||_||_||_||_ dS)Nrwrlongest) r(rxrLrrrrrtrrru) ryrrrrrtrrrurvrzrzr{rxs zResize.__init__r|r)rrrrtrrrurvrc s|dkr|jn|}|dkr |jn|}|jd}|jdkrtt|j} | |krlt|j| dd} | | }n| |krt d| d|dt |t r| n |jdd} t|j| } nXt |t r| n |jdd} t |jtst d|jt| tfdd | D} |dkr |jn|}|dkr4|jn|}t|pL|jpL|jtj}|dkrd|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. NrrzWlen(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).0sscalerzr{ ;sz"Resize.__call__..css|]}t|VqdSr)r)r_srzrzr{rCs)rrndimrrrArrCrreshaperrrrrDrrtuplerrrtrNrurrrvr"r)ryrrrrtrrrurv input_ndimZ output_ndim input_shapeZ_spsp_sizeimg_size_mode_align_corners_dtyperrzrr{rsF&      zResize.__call__rcCs||}|||Srrrryrrrzrzr{rNs zResize.inversec Cs|tj}|tjd}|tjd}|tjd}t|||tjkrHdn||d}|d||}W5QRXt|tjdD]}|d}q|S)Nrrrtru)rrrrtruFnew_dimr)rIrrr[rrrangesqueeze) ryrr orig_sizerrrtruxformrrzrzr{rRs   zResize.inverse_transform)NNNNNN)rrrrrJrrr;AREArfloat32rxrrrrzrzrzr{r[s&& Nc @seZdZdZejgZdeje j de j dfddddddddd d d Z dd dddddd dddZd d dddZd d dddZd S)r\a 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 TFSequence[float] | floatrprorr)angle keep_sizerrrsrtrurvrcCs6tj||d||_||_||_||_||_||_dSr )r(rxr3r4rrrsrtru)ryr3r4rrrsrtrurvrzrzr{rxs zRotate.__init__Nr|rrrrrrsrtrurvrc Cst|td}t|p|jp|jtj}|p.|j}|p8|j} |dkrH|jn|} t |t r^| n |j dd} |j rv| nd} |dkr|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]. r Nrr)r@rrNrurrrrrsrtrrrrr4rvr#r3r)ryrrrrsrtrurvr(r& _padding_moder'im_shaperrrzrzr{rs&!   zRotate.__call__rcCs||}|||Srr)r*rzrzr{rs zRotate.inversecCs*|tjd}|tjd}|tjd}|tjd}|tjd}tt|}t||\} } } } td| | |tjkrzdn|dd} t|t|d d } t || ^}} |tj }| | d ||d  d }t |||jd d }t|tr&t|dd }tt|d|}|jt ||d _|S)Nrot_matrrrsrtruFT) normalizedrrrsrtreverse_indexingrrrrrur r)rIrr7r?r3rrrMrr>r unsqueezefloatr-rurr@rrrr)ryrrZ fwd_rot_matrrrsrtruZ inv_rot_matr_m_pr/img_tZ transform_tr$rrmatrzrzr{rs0   zRotate.inverse_transform)NNNNN)rrrrrJrrr9rr:rrr1rxrrrrzrzrzr{r\ds"5c @seZdZdZejgZeje j de j ddfdddddd d d d d d Z dddddddddddZdddddZdddddZdS)r]a: 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. NTFr2rorrrpr)r&rrrsrtrur4rvrc Ks<tj||d||_||_||_||_||_||_||_dSr ) r(rxr&rrrsrtrur4kwargs) ryr&rrrsrtrur4rvrCrzrzr{rxs z Zoom.__init__r|rr5c Cst|td}t|j|jd}|dkr.|jn|}|p:|j} |dkrJ|jn|} t|p^|j p^|j t j } |dkrt|j n|} t|||j || | | | |d S)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. r rNr)r@rrBr&rrrrsrtrNrurrrvr4r) ryrrrrsrtrurv_zoomr&r6r'r(rrzrzr{r#s$  z Zoom.__call__rcCs||}|||Srr)r*rzrzr{rVs z Zoom.inversec Cs|tjdrj|tj}t|dd}|tjd}tj|tjdtj<tj|tjdtj<|||}|tjd}|tjd}|tjd }t|tjd } | d $| |||tjkrdn||d } W5QRX| S) NZ do_padcropedge)rrrZpadcroppad_info crop_inforrrtrur;F)rrrtru) rIrrrrIDrr[r) ryrrr.Z pad_or_cropZ padcrop_xformrrrtrurrrzrzr{rZs&    zZoom.inverse_transform)NNNNN)rrrrrJrrr;r0r<EDGErr1rxrrrrzrzrzr{r]s"$3c@sbeZdZdZejgZdddddd d d Zdd dd dddZd d dddZ d d dddZ d S)r^aE 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. rrrFrtuple[int, int]rpr)r spatial_axesrvrcCsNtj||dd|dd|_t|}t|dkrDtd|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 rwrzBspatial_axes must be 2 numbers to define the plane to rotate, got rN)r(rxrrArrrL)ryrrLrv spatial_axes_rzrzr{rx|s  zRotate90.__init__Nr|rr cCsFt|td}t|j|j}|dkr*|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. r Nr) r@rr2rrLrvr$rr)ryrrvaxesrrzrzr{rszRotate90.__call__rcCs||}|||Srr)r*rzrzr{rs zRotate90.inversec Cs^|tjd}|tjd}d|d}t||d}|d||W5QRSQRXdS)NrOrr)rrLF)rIrr^r)ryrrrOrZinv_kr/rzrzr{rs    zRotate90.inverse_transform)rrJF)N) rrrrrJrrrxrrrrzrzrzr{r^ps   csneZdZdZejZddddd d d d d Zddd dfdd Zddd dddddZdddddZ Z S)r_z 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. 皙?rJFr>rrKrpr)probmax_krLrvrcCs0t||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 rwrN)r*rxr(rSrL_rand_k)ryrRrSrLrvrzrzr{rxs zRandRotate90.__init__N Any | Nonercs.td|jsdS|j|jd|_dSNr)r randomize _do_transformrrandintrSrTrrrzr{rWs zRandRotate90.randomizeTr|rrrWrvrcCsb|r ||dkr|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. Nrwr Treplacerv) rWrvrXr^rTrLr@rpush_transform)ryrrWrvrr/rrzrzr{rs  zRandRotate90.__call__cCs0||}|tjs|S|tj}t||Sr)rrI DO_TRANSFORMrr^r)ryr xform_infoZ rotate_xformrzrzr{rs    zRandRotate90.inverse)rPrQrJF)N)TN) rrrrr^rrxrWrrrrzrzrr{r_sc seZdZdZejZdddddejej de j df dddddd d dd dd d d dZ ddd dfdd Z dddddd dddddZdddddZZS)r`a 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 rPTFtuple[float, float] | floatr>rprorr) range_xrange_yrange_zrRr4rrrsrtrurvrc Cst||tj|| dt||_t|jdkrRtt|jd |jdg|_t||_t|jdkrtt|jd |jdg|_t||_ t|j dkrtt|j d |j dg|_ ||_ ||_ ||_ ||_ | |_d|_d|_d|_dS)Nrwrrra)r*rxr(rArcrr!sortedrdrer4rrrsrtruxyz) ryrcrdrerRr4rrrsrtrurvrzrzr{rxs&       zRandRotate.__init__NrUrcsttd|jsdS|jj|jd|jdd|_|jj|jd|jdd|_|jj|j d|j dd|_ dS)Nrrlowhigh) rrWrXruniformrcrgrdrhrerirrrzr{rW1s  zRandRotate.randomizer|rr)rrrrsrtrurWrvc Cs|r ||dkr|jn|}|jrtt|tr8|n |jdd} t| dkrX|j n|j |j |j f|j |pr|j |pz|j|dkr|jn||p|jp|j|d} | |} nt|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. NrrM)r3r4rrrsrtrurvr ruTr\)rWrvrXrrrrrr\rgrhrir4rrrsrtrur@rrr1r^) ryrrrrsrtrurWrvrrZrotatorrrzrzr{r9s$$ zRandRotate.__call__cCs.||}|tjs|Std||tjS)Nr)rrIr_r\rrryrr`rzrzr{rks  zRandRotate.inverse)N)NNNNTN)rrrrr\rr9rr:rrr1rxrWrrrrzrzrr{r`s, $# 2c@sheZdZdZejZdddddd d d Zejj dd d dZddddddddZ dddddZ dS)raa) 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 rPNFr>rrpr)rRr rvrcCs,t||tj||dt||d|_dS)Nrw)r rv)r*rxr(rVr)ryrRr rvrzrzr{rxs zRandFlip.__init__rcCs||j_||_dSrrrvrrrzrzr{rvsz RandFlip.lazyTr|rrZcCsZ|r|d|dkr|jn|}|jr4|j||dn|}t|td}|j|d|d|Sr[)rWrvrXrr@rr^ryrrWrvrrrzrzr{rs  zRandFlip.__call__rcCs6||}|tjs|S|j|tj|j|Sr)rrIr_applied_operationsrrrrr*rzrzr{rs   zRandFlip.inverse)rPNF)TN) rrrrrVrrxr(rvrrrrzrzrzr{rarscs~eZdZdZejZddddddd Zejj dd d d Zd ddfdd Z ddddddddZ dddddZ Z S)rca 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 rPFr>rpr)rRrvrcCs2t||tj||dd|_t|jd|_dS)Nrwr)r*rxr(_axisrVr)ryrRrvrzrzr{rxs zRandAxisFlip.__init__rpcCs||j_||_dSrrqrrzrzr{rvszRandAxisFlip.lazyrrcs.td|jsdS|j|jd|_dSrV)rrWrXrrYrrtrrrzr{rWs zRandAxisFlip.randomizeTNr|rrZcCsd|r|j|d|dkr|jn|}|jrB|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. )rNrwr Tr\) rWrvrXrtrr r@rr^rrrzrzr{rs   zRandAxisFlip.__call__c Cs\||}|tjs|St|tjtjdd}|d||W5QRSQRXdS)NrOrF)rrIr_rVrr)ryrrrrzrzr{rs    zRandAxisFlip.inverse)rPF)TN)rrrrrVrrxr(rvrrWrrrrzrzrr{rcsc seZdZdZejZdddejej de j ddf dd d d d d d d d dd ddZ dddfdd Z ddddd d d d ddddZdddddZZS)rda 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. rPg?g?NTFr>r2rorrrpr) rRmin_zoommax_zoomrrrsrtrur4rvrc Kst||tj|| dt||_t||_t|jt|jkrdtdt|jdt|jd||_||_ ||_ ||_ ||_ | |_ dg|_dS)Nrwz1min_zoom and max_zoom must have same length, got z and r?)r*rxr(rArurvrrrrrsrtrur4rCrD) ryrRrurvrrrsrtrur4rvrCrzrzr{rxs   zRandZoom.__init__r)rrcstdjsdSfddtjjD_tjdkr\tjd|j d_n>tjdkr|j dkrtjd|j dt jd_dS)Ncsg|]\}}j||qSrz)rrm)rlhryrzr{ 5sz&RandZoom.randomize..rrrMrQr) rrWrXrrurvrDrrBrrA)ryrrrzr{rW1s zRandZoom.randomizer|r)rrrrsrtrurWrvrc Cs|r|j|d|dkr|jn|}|js` 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 NFrtorch.device | Noner rpNdarrayOrTensor | Noner) rotate_params shear_paramstranslate_params scale_paramsdevicerurtrrvrc Csftj|| d||_||_||_||_||_t|tj } | tj tj dfkrN| ntj |_ ||_||_dSr )r(rxr~rrrrrNrrfloat16rr1rurtr) ryr~rrrrrurtrrvr(rzrzr{rxs  zAffineGrid.__init__Sequence[int] | Noner}rz(tuple[torch.Tensor | None, torch.Tensor])rgridrvrc Cs|dkr|jn|}|sz|dkrD|dkr.tdt||jd|jd}n|}|jpR|j}t||td}|j}t|jd}n|j}t|}t j } |j dkr"t j |d|d} |jr| t||j|| d} |jr| t||j|| d} |jr| t||j|| d} |jr(| t||j|| d} n|j } t|| } |r@d| fSt| |j|jd d } |jrt|d d |jddD|| d} t| | d } | | ||jd dfdgt|jdd}n2| ||jd dfdgt|jdd}|| 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)rrru)rur rrrrF)rrur cSs$g|]}t|dt|ddqS)rMr)rrdrzrzr{r{sz'AffineGrid.__call__..rr)rvrr-rrur@rrrrJrrrrr~r.rr0rr1rr/rrtr>viewr) ryrrrvrgrid_r(_device spatial_dims_brscrzrzr{rsP   82zAffineGrid.__call__)NNN) rrrrrJrrrr1rxrrzrzrzr{re{s #"c @seZdZdZejZdddddejdfddddddddd d d Zd!d dddZ d"dddddZ d#ddddddddZ dddd Z dS)$rfz Generate randomised affine grid. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NF RandRanger|r rpr) rotate_range shear_rangetranslate_range scale_rangerrurvrcCsptj||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` rwNrr)r(rxrArrrrr~rrrrrurrrr)ryrrrrrrurvrzrzr{rxs/    zRandAffineGrid.__init__rar>) add_scalarcCszg}|D]l}t|rRt|dkr0td|d||j|d|d|q|dk r||j| ||q|S)NrMzBIf giving range as [min,max], should have 2 elements per dim, got rrr)rErrrrrm)ryZ param_ranger out_paramfrzrzr{_get_rand_param?s "zRandAffineGrid._get_rand_paramrUrcCs>||j|_||j|_||j|_||jd|_dS)Nrw) rrr~rrrrrrrrzrzr{rWJszRandAffineGrid.randomizeTrr}rr|)rrrWrvrc Csl|r ||dkr|jn|}t|j|j|j|j|j|j|d}|rX|||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)r~rrrrrurvr) rWrvrer~rrrrrur)ryrrrWrvr affine_gridZ_gridrzrzr{rPs" zRandAffineGrid.__call__r})rcCs|jS)z3Get the most recently applied transformation matrixrrzrzrzr{get_transformation_matrixvsz(RandAffineGrid.get_transformation_matrix)ra)N)NNTN) rrrrrerrr1rxrrWrrrzrzrzr{rfs$> &c@sNeZdZdZejgZdddddddd Zd dd d d Zd ddddZ dS)rgz+ Generate random deformation grid. Nr2tuple[float, float]r|r)spacingmagnitude_rangerrcCs ||_||_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. rwN)r magnituderand_magr)ryrrrrzrzr{rxs zRandDeformGrid.__init__ Sequence[int] grid_sizercCsJ|jjt|gt|djtjdd|_|j|j d|j d|_ dS)N)rFrrr) rnormalrrastyperr1 random_offsetrmrrryrrzrzr{rWs*zRandDeformGrid.randomizer|rrcCspt|jdt||_t||j|jdd}||jddt|j|j |^}}|dt||7<|S)zK Args: spatial_size: spatial size of the grid. rwrrrN) rDrrr,rrWrr>rr)ryrZ control_grid_offsetrrzrzr{rs zRandDeformGrid.__call__)N) rrrrrJrrrxrWrrzrzrzr{rg{s c @sbeZdZejejgZeje j ddde j fddddddd d d d Z dd dddddd dddZdS)rhTNFrnrorpr|r r)rrrs norm_coordsrrtrurcCs(||_||_||_||_||_||_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)rrrsrrrtru)ryrrrsrrrtrurzrzr{rxs +zResample.__init__r|r}r~rr)rrrrrsrurtrcst|td}|dkr|St|tjr,|jn|j}|p@|jp@|j}|dkrP|jn|} t|tj||d^} } t t t| t r| n | j ddd} t|dkr|jn||dkr|jn|dtd\} } ts| tjkrt|d| | |jdd^}} t|tjr$||kr$|jtjd }t| j dd| D]z\}}td |}|dd }|jr| r~|d||||n |||||<n"| r:|d|||d ||<q:tr| tjkrt|d d}t| d |d | ddd }n| tjkrh| j }|rt!nt"| dd}t|||jdd^} |rFt#nt$j%|rVt&nt'(fdd|D}t|| d }nt|t)t*| dddd d}t|| ddd d }t|tjr||kr|jtjd }|jr6t| j | dd dD]*\}}|d d|fd td |9<q tj+j,j-| d || t.j/kr\dn| 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` r N)rurrrQ)r use_compiledT)ru wrap_sequence) memory_formatrM@?rr)bound extrapolate interpolation)rcsg|]}|dqS))orderrrrz)rc _interp_modeZ _map_coordr6Zgrid_nprzr{r{/sz%Resample.__call__...)rrrsrtr<)1r@rrrrrrurtrMrrrrrr3rrrsr rJrr>data_ptrclonecontiguous_formatrrrrr8rr=tois_cudar=r?cupy_ndinp_ndimap_coordinatesrQrstackrr,nn functional grid_samplerIrr1)ryrrrrrsrurtrr(r'rArrrZgrid_tidim_dimtrrimg_npZout_valrzrr{rs~)*   0      $zResample.__call__)NNNNN)rrrrJrrrr9rr:rrrrxrrzrzrzr{rhs 5c@seZdZdZeeejeej@Zdddddde j e j dde jdddfddddddddd d d d d d d d ddZejjd d dddZd dddddddddZeddZdddddZdS)!ria/ 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}rrnrorpr|r r)r~rrrrrrrrsr9rrurt image_onlyrvrc 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 rw) r~rrrrrurtrrv)rrrurtN) r(rxrerrZ norm_coordrh resamplerrrrrs)ryr~rrrrrrrrsr9rrurtrrvrzrzr{rxPs$I zAffine.__init__rcCs||j_||_dSr)rrvrrrzrzr{rvsz Affine.lazyr|r~rrz3torch.Tensor | tuple[torch.Tensor, NdarrayOrTensor])rrrrrsrvrc Cst|td}t|tr |n |jdd}t|dkr>|jn||}|dkrT|jn|}|dk rd|n|j } |dk rv|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. r rNrrvTr)r@rrrrrrDrrvrrrsrrrrr) ryrrrrrsrvr%r$rr&r6rrrzrzr{rs(  zAffine.__call__cCsft|}t||}t|dd|d|D}t|dd|d|D}|t|tjd|}|S)NcSsg|]}t|ddqSrrMr>rrzrzr{r{sz+Affine.compute_w_affine..cSsg|]}t|d dqSrrrrzrzr{r{sr)rrr1rMrr)cls spatial_rankrBr%r$rZshift_1Zshift_2rzrzr{compute_w_affines  zAffine.compute_w_affinercCs||}|tj}|tjd}|tjd}|tjd}|tjd}tt|}t|||jdd}t||d} | |\} } |j || |||d} t | t st | } |j | _ t | tjd} ttt| d ||jd d|| ^}} | j|_| S) Nrrrrsrtrr)rrt)rtr)rrIrrr7r?r>rurerrrrrMrrrrirrrr)ryrrr. fwd_affinerrrsrt inv_affinerrrrrr/rzrzr{rs*       zAffine.inverse)NNNN)rrrrrsetrerrhr9rr: REFLECTIONrr1rxr(rvrr classmethodrrrzrzrzr{riEs6,\6 cseZdZdZejZddddddejej dddf dddddddd d d d d d ddZ e j j d d dddZ d dddZdd dddZd-ddddfdd Zd.dd d fd!d" Zd/d$dd%d&d d'd$d(d)d*Zd$d$d d+d,ZZS)0rja 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. rPNFr>rrrnrorpr|r) rRrrrrrrrrs cache_gridrrvrc 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. rwrrrrrrvrN) r*rxr(rfrand_affine_gridrhrrr_init_identity_cache _cached_gridrrrs) ryrRrrrrrrrrsrrrvrzrzr{rx s F   zRandAffine.__init__rcCs||_||j_dSr)rrrvrrzrzr{rvm szRandAffine.lazyrwcCs|rdS|jdkr&|jr"tddSt|j}t|}|t|dg|ks`|t|dg|kr~|jrztd|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'.rrMzNcache_grid=True is not compatible with the dynamic spatial_size 'spatial_size=z!', please specify 'spatial_size'.rrrr) rrrrrArrDr-rr)ryrvZ_sp_size_ndimrzrzr{rr s"  ( zRandAffine._init_identity_cacherrcCsj|rdSt|}|t|dg|ks8|t|dg|krHtd|d|jdkrdt||jjddS|jS)z Return a cached or new identity grid depends on the availability. Args: spatial_size: non-dynamic spatial size NrrMz(spatial_size should not be dynamic, got rrr)rrDrrr-rr)ryrrvrrzrzr{get_identity_grid szRandAffine.get_identity_grid int | Nonenp.random.RandomState | Noneseedstatercs |j||t|||Srrset_random_staterryrrrrzr{r szRandAffine.set_random_staterUrcs$td|jsdS|jdSr)rrWrXrrrrzr{rW s zRandAffine.randomizeTr|r~rr)rrrrrsrWrvrc CsJ|r |t|tr|n |jdd}t|dkr<|jn||} |jpT| t|k} |dk rb|n|j } |dk rt|n|j } |dkr|j n|} t |t d}| r|jr|dkr|j| |dd|j}n$ttt| d||jjdd}n8|dkr|| | }|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. rNr T)rWrvrr)rrWrvr)rWrrrrrDrrXrArrrsrvr@rrrr>rrrrurrrr)ryrrrrrsrWrrvZori_sizer$ do_resamplingr&r6rrrzrzr{r sB$  &   zRandAffine.__call__cCs||}|tjds|S|tj}t||jdd}|tjd}|tjd}|tjd}tt|}t|||j dd}t |d}||\} } | || ||} t | t st | } |j| _t| tjd} ttt| d||jdd|| ^} } | j| _| S) Nrrrrrrsrrr)rrIrrrDrr7r?r>rurerrrrrMrrrrirrr)ryrrr.rrrrsrrrrrrr/rzrzr{r s.       zRandAffine.inverse)NN)N)NNNTNN)rrrrrirr9rr:rrxr(rvrrrrrWrrrrzrzrr{rj s8&X JcseZdZdZejZddddddejej df ddddddddd d d d d ddZ d#ddddfdd Z ddZ dd dfdd Z d$ddddddd d!d"ZZS)%rkz 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. rPNrbrr>rztuple[int, int] | int | Nonernror|r) rrrRrrrrrrrrsrrc 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*rxrg deform_gridrfrrhrrrrrrs) ryrrrRrrrrrrrrsrrzrzr{rx sB  zRand2DElastic.__init__rrrcs.|j|||j||t|||Sr)rrrrrrrzr{rl szRand2DElastic.set_random_statecCs"||j_||j_||j_||_dSr)rrrrryrrzrzr{ set_devicer szRand2DElastic.set_devicerrcs0td|jsdS|j||jdSr)rrWrXrr)ryrrrzr{rWx s   zRand2DElastic.randomizeTr|r~rrprrrrrsrWrc Cst|dkr|jn||jdd}|r2|j|d|jr|j|d}|j|d}tjj j d| dt t |jjtjjdd}t|d |d}n.t|tjr|jn|j}ttjt||d d }|j|||dk r|n|j|dk r|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. Nrr;rTrF)recompute_scale_factorinput scale_factorrrrt)roi_sizerrrrrs)rDrrrWrXrrrrr interpolater=rrArr;BICUBICvaluerrrrr r-rrrrs) ryrrrrrsrWr$rrrrzrzr{r s."   zRand2DElastic.__call__)NN)NNNTrrrrrhrr9rr:rrxrrrWrrrzrzrr{rk s(&S cseZdZdZejZddddddejej df dddddddddd d d d d dZ d"ddddfdd Z ddZ dd dfdd Z d#dddddddd d!ZZS)$rlz 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. rPNrr>rz!tuple[int, int, int] | int | Nonernror|r) sigma_rangerrRrrrrrrrrsrrc 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. FrrrwN)r*rxrfrrhrrrrrrrsrrsigma) ryrrrRrrrrrrrrsrrzrzr{rx s&E  zRand3DElastic.__init__rrrcs |j||t|||Srrrrrzr{r szRand3DElastic.set_random_statecCs||j_||j_||_dSr)rrrrrzrzr{r szRand3DElastic.set_devicerrcstd|jsdS|jdddgt|jtjdd|_ |j|j d|j d|_ |j|j d|j d|_ |jdS)NgrwrQFrrr)rrWrXrrmrrrr1 rand_offsetrrrrrrrrzr{rW$ s (zRand3DElastic.randomizeTr|r~rrprc Cst|dkr|jn||jdd}|r2|j|dt|tjrD|jn|j}t||dd}|j r|j dkrpt dt d|j dj|d } tj|j |d d } |dd| | d |j7<|j|d }|j|||dk r|n|j|dk r|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.rQg@rrrr)rDrrrWrrrrr-rXrrrrrrr=rrrrrrs) ryrrrrrsrWr$rrgaussianrrrzrzr{r- s&"  " zRand3DElastic.__call__)NN)NNNTrrzrzrr{rl s(&[ c@sPeZdZejgZejej dfdddddddd d Z dd d d d d dddZ dS)rWNtuple[int] | intzSequence[Sequence[float]]rnror|r) num_cells distort_stepsrrrsrrcCs&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. )rrrsrN)rhrrrr)ryrrrrrsrrzrzr{rxb s zGridDistortion.__init__r|zSequence[Sequence] | Noner)rrrrrsrcCs`|dkr|jn|}t|jt|dkr0tdg}t|jt|jd}t|trd|jrdt dt |jddD]\}}||} t j |t jd} |||} d} t||dD]X} t| | }|| }||kr|}|}n| | | | }t | |||| ||<|} q| |dd} || qvt|}t |t |df}|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.rrrwr)rrrrs)rrrrrBrrrpending_operationsrrrrzerosr1r,rlinspacerrr ones_liker)ryrrrrrs all_rangesrZdim_idxdim_sizeZdim_distort_stepsranges cell_sizeprevrstartendcurcoordsrrzrzr{r s4    zGridDistortion.__call__)NNN) rrrrJrrr9rr:rrxrrzrzrzr{rW_ s(c speZdZejgZdddejej dfddddd d d d d dZ dd dfdd Z dddddddddZ Z S)rbrP)gQgQ?Nrr>rbrnror|r)rrR distort_limitrrrsrrcCsnt||||_t|ttfrrrr rrWgrid_distortion)ryrrRr rrrsrrzrzr{rx s" zRandGridDistortion.__init__r)rrcs>tdjsdStfddtjt|D_dS)Nc3s8|]0}tdjjjdjd|ddVqdS)rwrr)rkrlrN)r!rrmr )rZn_cellsrzrzr{r sz/RandGridDistortion.randomize..)rrWrXr!rBrrr)ryrrrzr{rW s   zRandGridDistortion.randomizeTr|rrp)rrrrsrWrcCsZ|r2t|tr|jrtd||jdd|jsFt|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. rrNr )rrrrs) rrrrrrWrrXr@rrr)ryrrrrsrWrzrzr{r s zRandGridDistortion.__call__)NNT)rrrrJrrr9rr:rrxrWrrrzrzrr{rb s- c@sTeZdZdZejejgZddddddZdd d d d d dZ ddddddZ dS)rXa 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. rMrMNrKzint | tuple[int, int] | None)rrcCs(||_|dkrdnt|t|j|_dSr)rrBrr)ryrrrzrzr{rx, szGridSplit.__init__rz)int | tuple[int, int] | np.ndarray | Nonezlist[NdarrayOrTensor])imagerrcCs^|dkr|jnt|t|j}|jdkr6|dkr6|gSt|trP|jrPtd| |j dd|\}}t|t j rt j }|\}}} n8t|tjrtjjj }|j\}}} ntdt|d|\} } |j d} |||j| |d|df|| | | ||| f} | jd | j dd} t|t j r>d d | D}nt|tjrZd d | D}|S) N)rrrrz Input type [z] is not supported.rrrMcSsg|] }|qSrz) contiguousrprzrzr{r{S sz&GridSplit.__call__..cSsg|]}t|qSrz)rascontiguousarrayrrzrzr{r{U s)r)rrBrrrrrrr _get_paramsrrr as_stridedstriderrlib stride_tricksstridesrtyper )ryrr input_size split_sizestepsZas_strided_funcZc_stridex_strideZy_strideZx_stepy_step n_channelsZ strided_imagepatchesrzrzr{r3 s4     zGridSplit.__call__zSequence[int] | np.ndarrayz!Sequence[int] | np.ndarray | None image_sizercsdkr*tfddttjDtfddttjDrbtdddtfddttjD}|fS) z Calculate the size and step required for splitting the image Args: The size of the input image Nc3s |]}|j|VqdSrrrr)r$ryrzr{ra sz(GridSplit._get_params..c3s|]}||kVqdSrrzr%r#rzr{rc szThe image size (z+)is smaller than the requested split size ()c3sB|]:}j|dkr2||j|dn|VqdS)rNrr%r$ryrrzr{rf s)r!r,rranyr)ryr$rrrzr'r{rY s"" zGridSplit._get_params)rN)N)N) rrrrrJrrrrxrrrzrzrzr{rX s  &c @sleZdZdZejejgZddddddd dd d d Zd dddddZ d dddddZ d ddddZ dS)rYa 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) Nrarrrr2r float | None patch_sizer num_patchesoverlapsort_fn thresholdpad_modec KsZt||_|rt|n dt|j|_||_||_||_||_|rJ|nd|_ ||_ dS)Nr) rAr+rrr0 pad_kwargsr-r,lowerr.r/) ryr+rr,r-r.r/r0r2rzrzr{rx s zGridPatch.__init__r np.ndarray"tuple[NdarrayOrTensor, np.ndarray]image_np locationsrcCsNt|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) rrr6sumr!r,r/r rMrrryr7r8n_dimsridx_nprzrzr{filter_threshold s $zGridPatch.filter_thresholdcCs|jdkr(|d|j}|d|j}n|jdk rt|j}|jtjkrbt|tt d|}n:|jtj krt|tt d| }nt 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)r.r,rrrGMINr5r9r!r,MAXrrMrrr:rzrzr{ filter_count s     zGridPatch.filter_countr)rrc Cst|fd|jd|j|jd|jd|j}tt|}t|t j rTt |dn t |d}t |ddddddf}|j dk r|||\}}|jrz|||\}}|j dkrz|jt|}|dkrz|jdd}|ft|jdd}t|t j r2t j|||jd } t j|| gdd }n,t 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. rr1F)r+ start_posr- copy_backrrrrNconstant_valuesr)axis)rulayoutr)r)rDrr)rgrT)%rr+rr-r0r2rrrrrrrr/r=r,rArrrfullru concatenaterFrcatpadrrget_default_metaTrHLOCATIONCOUNTtileris_batch) ryrZpatch_iteratorr"Z patched_imager8paddingrDZ padding_shapeZconstant_paddingmetadataoutputrzrzr{r sV  (     "  zGridPatch.__call__)NNraNNN) rrrrrJrrrrxr=rArrzrzrzr{rYn s( c sveZdZdZejejgZdddddddd dd fd d Zd dZ ddddfdd Z ddddfdd Z Z S)rZa 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) Nrarrrr2rr))r+ min_offset max_offsetr,r-r.r/r0c s>tjf|d|||||d| ||_||_||_||_dS)Nrzr*)rrxrTrUr,r.) ryr+rTrUr,r-r.r/r0r2rrzr{rxH s  zRandGridPatch.__init__csjdkrdtj}ntjtj}jdkr\tddt|jddjD}ntjtj}tfddt||D_dS)Nr1css|]\}}||VqdSrrz)rrrrzrzr{ri sz*RandGridPatch.randomize..rc3s&|]\}}jj||ddVqdS)rrjN)rrY)rrkrlrzrzr{rm s) rTrr+rBrUr!rrr)ryrrTrUrzrzr{rWc s  &zRandGridPatch.randomizerr4r5r6cs|jtjkrT|j|jd}|d|j}t|tj d}||}||}||fS|jdtj tj fkrzt d|jdt ||S)Nrz;`sort_fn` should be either "min", "max", "random" or None! r>)r.rGRANDOMr permutationrr,rMrrr?r@rrrA)ryr7r8rr<rrzr{rAo s zRandGridPatch.filter_countTrp)rrWcs|r||t|Sr)rWrr)ryrrWrrzr{r{ s zRandGridPatch.__call__)NNNraNNN)T) rrrrrJrrrrxrWrArrrzrzrr{rZ s, "  csneZdZdZejZdejejdddfddddd d d d d Z ddd dfdd Z dddddddZ Z S)rma 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. rP)rrwFNr>zInterpolateMode | strzSequence[float]r|r)rRdownsample_mode upsample_mode zoom_rangerrcCs4t||||_||_||_||_||_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. rwN)r*rxrXrYrZrtr zoom_factor)ryrRrXrYrZrtrrzrzr{rx s z"RandSimulateLowResolution.__init__rUrcs6td|j|jd|jd|_|js2dSdS)Nrr)rrWrrmrZr[rXrrrzr{rW s z#RandSimulateLowResolution.randomizeTr|rp)rrWrc Cs|r ||jr|jdd}tt||jtj}t |d|j dd}t |d|j d|j d}t }td||}||} t|t| } | || S|SdS)z Args: img: shape must be (num_channels, H, W[, D]), randomize: whether to execute `randomize()` function first, defaults to True. rNrF)rrrrr)rrrrrrt)rWrXrrrrr[rint_r[rXrYrtrrrcopy_meta_from) ryrrWr# target_shapeZresize_tfm_downsampleZresize_tfm_upsampleZoriginal_tack_meta_valueZimg_downsampledZ img_upsampledrzrzr{r s6  z"RandSimulateLowResolution.__call__)N)T) rrrrrirr;NEAREST TRILINEARrxrWrrrzrzrr{rm s)r __future__rrcollections.abcrrr itertoolsrtypingrrrr r r numpyrr monai.configr r monai.config.type_definitionsrmonai.data.meta_objrrmonai.data.meta_tensorrmonai.data.utilsrrrrrrmonai.networks.layersrrrmonai.networks.utilsrZmonai.transforms.croppad.arrayrrmonai.transforms.inverserZ#monai.transforms.spatial.functionalrr r!r"r#r$r%r&monai.transforms.traitsr'monai.transforms.transformr(r)r*r+monai.transforms.utilsr,r-r.r/r0r1r2r3r40monai.transforms.utils_pytorch_numpy_unificationr5r6r7r8 monai.utilsr9r:r;r<r=r>r?r@rArBrCrDrErFmonai.utils.enumsrGrHrIrJmonai.utils.miscrKrmonai.utils.modulerLmonai.utils.type_conversionrMrNrOrZhas_nibrQrrr__all__r>rrRrSrTrUrVr[r\r]r^r_r`rarcrdrerfrgrhrirjrkrlrWrbrXrYrZrmrzrzrzr{ s          ( , @      $RTt-" 7D5@|,F'*cVV,h