-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy patharray.py
3257 lines (2906 loc) · 164 KB
/
array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A collection of "vanilla" transforms for spatial operations
https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design
"""
from __future__ import annotations
import warnings
from collections.abc import Callable
from copy import deepcopy
from itertools import zip_longest
from typing import Any, Optional, Sequence, Tuple, Union, cast
import numpy as np
import torch
from monai.config import USE_COMPILED, DtypeLike
from monai.config.type_definitions import NdarrayOrTensor
from monai.data.meta_obj import get_track_meta
from monai.data.meta_tensor import MetaTensor
from monai.data.utils import AFFINE_TOL, affine_to_spacing, compute_shape_offset, iter_patch, to_affine_nd, zoom_affine
from monai.networks.layers import AffineTransform, GaussianFilter, grid_pull
from monai.networks.utils import meshgrid_ij
from monai.transforms.croppad.array import CenterSpatialCrop, ResizeWithPadOrCrop
from monai.transforms.intensity.array import GaussianSmooth
from monai.transforms.inverse import InvertibleTransform
from monai.transforms.spatial.functional import spatial_resample
from monai.transforms.traits import MultiSampleTrait
from monai.transforms.transform import LazyTransform, Randomizable, RandomizableTransform, Transform
from monai.transforms.utils import (
convert_pad_mode,
create_control_grid,
create_grid,
create_rotate,
create_scale,
create_shear,
create_translate,
map_spatial_axes,
scale_affine,
)
from monai.transforms.utils_pytorch_numpy_unification import linalg_inv, moveaxis, where
from monai.utils import (
GridSampleMode,
GridSamplePadMode,
InterpolateMode,
NdimageMode,
NumpyPadMode,
SplineMode,
convert_to_cupy,
convert_to_dst_type,
convert_to_numpy,
convert_to_tensor,
ensure_tuple,
ensure_tuple_rep,
ensure_tuple_size,
fall_back_tuple,
issequenceiterable,
optional_import,
)
from monai.utils.deprecate_utils import deprecated_arg
from monai.utils.enums import GridPatchSort, PatchKeys, PytorchPadMode, TraceKeys, TransformBackends
from monai.utils.misc import ImageMetaKey as Key
from monai.utils.module import look_up_option
from monai.utils.type_conversion import convert_data_type, get_equivalent_dtype, get_torch_dtype_from_string
nib, has_nib = optional_import("nibabel")
cupy, _ = optional_import("cupy")
cupy_ndi, _ = optional_import("cupyx.scipy.ndimage")
np_ndi, _ = optional_import("scipy.ndimage")
__all__ = [
"SpatialResample",
"ResampleToMatch",
"Spacing",
"Orientation",
"Flip",
"GridDistortion",
"GridSplit",
"GridPatch",
"RandGridPatch",
"Resize",
"Rotate",
"Zoom",
"Rotate90",
"RandRotate90",
"RandRotate",
"RandFlip",
"RandGridDistortion",
"RandAxisFlip",
"RandZoom",
"AffineGrid",
"RandAffineGrid",
"RandDeformGrid",
"Resample",
"Affine",
"RandAffine",
"Rand2DElastic",
"Rand3DElastic",
]
RandRange = Optional[Union[Sequence[Union[Tuple[float, float], float]], float]]
class SpatialResample(InvertibleTransform, LazyTransform):
"""
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``.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY, TransformBackends.CUPY]
def __init__(
self,
mode: str | int = GridSampleMode.BILINEAR,
padding_mode: str = GridSamplePadMode.BORDER,
align_corners: bool = False,
dtype: DtypeLike = np.float64,
):
"""
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``.
"""
self.mode = mode
self.padding_mode = padding_mode
self.align_corners = align_corners
self.dtype = dtype
def __call__(
self,
img: torch.Tensor,
dst_affine: torch.Tensor | None = None,
spatial_size: Sequence[int] | torch.Tensor | int | None = None,
mode: str | int | None = None,
padding_mode: str | None = None,
align_corners: bool | None = None,
dtype: DtypeLike = None,
) -> torch.Tensor:
"""
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`.
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.
"""
# get dtype as torch (e.g., torch.float64)
dtype_pt = get_equivalent_dtype(dtype or self.dtype or img.dtype, torch.Tensor)
align_corners = align_corners if align_corners is not None else self.align_corners
mode = mode if mode is not None else self.mode
padding_mode = padding_mode if padding_mode is not None else self.padding_mode
return spatial_resample(
img, dst_affine, spatial_size, mode, padding_mode, align_corners, dtype_pt, self.get_transform_info()
)
def inverse(self, data: torch.Tensor) -> torch.Tensor:
transform = self.pop_transform(data)
# Create inverse transform
kw_args = transform[TraceKeys.EXTRA_INFO]
# need to convert dtype from string back to torch.dtype
kw_args["dtype"] = get_torch_dtype_from_string(kw_args["dtype"])
# source becomes destination
kw_args["dst_affine"] = kw_args.pop("src_affine")
kw_args["spatial_size"] = transform[TraceKeys.ORIG_SIZE]
if kw_args.get("align_corners") == TraceKeys.NONE:
kw_args["align_corners"] = False
with self.trace_transform(False):
# we can't use `self.__call__` in case a child class calls this inverse.
out: torch.Tensor = SpatialResample.__call__(self, data, **kw_args)
return out
class ResampleToMatch(SpatialResample):
"""Resample an image to match given metadata. The affine matrix will be aligned,
and the size of the output image will match."""
def __call__( # type: ignore
self,
img: torch.Tensor,
img_dst: torch.Tensor,
mode: str | int | None = None,
padding_mode: str | None = None,
align_corners: bool | None = None,
dtype: DtypeLike = None,
) -> torch.Tensor:
"""
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`.
Raises:
ValueError: When the affine matrix of the source image is not invertible.
Returns:
Resampled input tensor or MetaTensor.
"""
if img_dst is None:
raise RuntimeError("`img_dst` is missing.")
dst_affine = img_dst.affine if isinstance(img_dst, MetaTensor) else torch.eye(4)
img = super().__call__(
img=img,
dst_affine=dst_affine,
spatial_size=img_dst.shape[1:], # skip channel
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
dtype=dtype,
)
if isinstance(img, MetaTensor):
img.affine = dst_affine
if isinstance(img_dst, MetaTensor):
original_fname = img.meta.get(Key.FILENAME_OR_OBJ, "resample_to_match_source")
img.meta = deepcopy(img_dst.meta)
img.meta[Key.FILENAME_OR_OBJ] = original_fname # keep the original name, the others are overwritten
return img
class Spacing(InvertibleTransform):
"""
Resample input image into the specified `pixdim`.
"""
backend = SpatialResample.backend
def __init__(
self,
pixdim: Sequence[float] | float | np.ndarray,
diagonal: bool = False,
mode: str | int = GridSampleMode.BILINEAR,
padding_mode: str = GridSamplePadMode.BORDER,
align_corners: bool = False,
dtype: DtypeLike = np.float64,
scale_extent: bool = False,
recompute_affine: bool = False,
min_pixdim: Sequence[float] | float | np.ndarray | None = None,
max_pixdim: Sequence[float] | float | np.ndarray | None = None,
) -> None:
"""
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`.
"""
self.pixdim = np.array(ensure_tuple(pixdim), dtype=np.float64)
self.min_pixdim = np.array(ensure_tuple(min_pixdim), dtype=np.float64)
self.max_pixdim = np.array(ensure_tuple(max_pixdim), dtype=np.float64)
self.diagonal = diagonal
self.scale_extent = scale_extent
self.recompute_affine = recompute_affine
for mn, mx in zip(self.min_pixdim, self.max_pixdim):
if (not np.isnan(mn)) and (not np.isnan(mx)) and ((mx < mn) or (mn < 0)):
raise ValueError(f"min_pixdim {self.min_pixdim} must be positive, smaller than max {self.max_pixdim}.")
self.sp_resample = SpatialResample(
mode=mode, padding_mode=padding_mode, align_corners=align_corners, dtype=dtype
)
@deprecated_arg(name="affine", since="0.9", msg_suffix="Not needed, input should be `MetaTensor`.")
def __call__(
self,
data_array: torch.Tensor,
affine: NdarrayOrTensor | None = None,
mode: str | int | None = None,
padding_mode: str | None = None,
align_corners: bool | None = None,
dtype: DtypeLike = None,
scale_extent: bool | None = None,
output_spatial_shape: Sequence[int] | np.ndarray | int | None = None,
) -> torch.Tensor:
"""
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.
Raises:
ValueError: When ``data_array`` has no spatial dimensions.
ValueError: When ``pixdim`` is nonpositive.
Returns:
data tensor or MetaTensor (resampled into `self.pixdim`).
"""
original_spatial_shape = data_array.shape[1:]
sr = len(original_spatial_shape)
if sr <= 0:
raise ValueError("data_array must have at least one spatial dimension.")
affine_: np.ndarray
if affine is not None:
warnings.warn("arg `affine` is deprecated, the affine of MetaTensor in data_array has higher priority.")
input_affine = data_array.affine if isinstance(data_array, MetaTensor) else affine
if input_affine is None:
warnings.warn("`data_array` is not of type MetaTensor, assuming affine to be identity.")
# default to identity
input_affine = np.eye(sr + 1, dtype=np.float64)
affine_ = to_affine_nd(sr, convert_data_type(input_affine, np.ndarray)[0])
out_d = self.pixdim[:sr].copy()
if out_d.size < sr:
out_d = np.append(out_d, [out_d[-1]] * (sr - out_d.size))
orig_d = affine_to_spacing(affine_, sr, out_d.dtype)
for idx, (_d, mn, mx) in enumerate(
zip_longest(orig_d, self.min_pixdim[:sr], self.max_pixdim[:sr], fillvalue=np.nan)
):
target = out_d[idx]
mn = target if np.isnan(mn) else min(mn, target)
mx = target if np.isnan(mx) else max(mx, target)
if mn > mx:
raise ValueError(f"min_pixdim is larger than max_pixdim at dim {idx}: min {mn} max {mx} out {target}.")
out_d[idx] = _d if (mn - AFFINE_TOL) <= _d <= (mx + AFFINE_TOL) else target
if not align_corners and scale_extent:
warnings.warn("align_corners=False is not compatible with scale_extent=True.")
# compute output affine, shape and offset
new_affine = zoom_affine(affine_, out_d, diagonal=self.diagonal)
scale_extent = self.scale_extent if scale_extent is None else scale_extent
output_shape, offset = compute_shape_offset(data_array.shape[1:], affine_, new_affine, scale_extent)
new_affine[:sr, -1] = offset[:sr]
# convert to MetaTensor if necessary
data_array = convert_to_tensor(data_array, track_meta=get_track_meta())
if isinstance(data_array, MetaTensor):
data_array.affine = torch.as_tensor(affine_)
# we don't want to track the nested transform otherwise two will be appended
actual_shape = list(output_shape) if output_spatial_shape is None else output_spatial_shape
data_array = self.sp_resample(
data_array,
dst_affine=torch.as_tensor(new_affine),
spatial_size=actual_shape, # type: ignore
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
dtype=dtype,
)
if self.recompute_affine and isinstance(data_array, MetaTensor):
data_array.affine = scale_affine(affine_, original_spatial_shape, actual_shape)
return data_array
def inverse(self, data: torch.Tensor) -> torch.Tensor:
return self.sp_resample.inverse(data)
class Orientation(InvertibleTransform):
"""
Change the input image's orientation into the specified based on `axcodes`.
"""
backend = [TransformBackends.NUMPY, TransformBackends.TORCH]
def __init__(
self,
axcodes: str | None = None,
as_closest_canonical: bool = False,
labels: Sequence[tuple[str, str]] | None = (("L", "R"), ("P", "A"), ("I", "S")),
) -> None:
"""
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'))``.
Raises:
ValueError: When ``axcodes=None`` and ``as_closest_canonical=True``. Incompatible values.
See Also: `nibabel.orientations.ornt2axcodes`.
"""
if axcodes is None and not as_closest_canonical:
raise ValueError("Incompatible values: axcodes=None and as_closest_canonical=True.")
if axcodes is not None and as_closest_canonical:
warnings.warn("using as_closest_canonical=True, axcodes ignored.")
self.axcodes = axcodes
self.as_closest_canonical = as_closest_canonical
self.labels = labels
def __call__(self, data_array: torch.Tensor) -> torch.Tensor:
"""
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, ...]).
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`.
"""
spatial_shape = data_array.shape[1:]
sr = len(spatial_shape)
if sr <= 0:
raise ValueError("data_array must have at least one spatial dimension.")
affine_: np.ndarray
affine_np: np.ndarray
if isinstance(data_array, MetaTensor):
affine_np, *_ = convert_data_type(data_array.affine, np.ndarray)
affine_ = to_affine_nd(sr, affine_np)
else:
warnings.warn("`data_array` is not of type `MetaTensor, assuming affine to be identity.")
# default to identity
affine_np = np.eye(sr + 1, dtype=np.float64)
affine_ = np.eye(sr + 1, dtype=np.float64)
src = nib.io_orientation(affine_)
if self.as_closest_canonical:
spatial_ornt = src
else:
if self.axcodes is None:
raise ValueError("Incompatible values: axcodes=None and as_closest_canonical=True.")
if sr < len(self.axcodes):
warnings.warn(
f"axcodes ('{self.axcodes}') length is smaller than the number of input spatial dimensions D={sr}.\n"
f"{self.__class__.__name__}: input spatial shape is {spatial_shape}, num. channels is {data_array.shape[0]},"
"please make sure the input is in the channel-first format."
)
dst = nib.orientations.axcodes2ornt(self.axcodes[:sr], labels=self.labels)
if len(dst) < sr:
raise ValueError(
f"axcodes must match data_array spatially, got axcodes={len(self.axcodes)}D data_array={sr}D"
)
spatial_ornt = nib.orientations.ornt_transform(src, dst)
new_affine = affine_ @ nib.orientations.inv_ornt_aff(spatial_ornt, spatial_shape)
# convert to MetaTensor if necessary
data_array = convert_to_tensor(data_array, track_meta=get_track_meta())
spatial_ornt[:, 0] += 1 # skip channel dim
spatial_ornt = np.concatenate([np.array([[0, 1]]), spatial_ornt])
axes = [ax for ax, flip in enumerate(spatial_ornt[:, 1]) if flip == -1]
if axes:
data_array = torch.flip(data_array, dims=axes)
full_transpose = np.arange(len(data_array.shape))
full_transpose[: len(spatial_ornt)] = np.argsort(spatial_ornt[:, 0])
if not np.all(full_transpose == np.arange(len(data_array.shape))):
data_array = data_array.permute(full_transpose.tolist())
new_affine = to_affine_nd(affine_np, new_affine)
new_affine, *_ = convert_data_type(new_affine, torch.Tensor, dtype=torch.float32, device=data_array.device)
if get_track_meta():
self.update_meta(data_array, new_affine)
self.push_transform(data_array, extra_info={"original_affine": affine_np})
return data_array
def update_meta(self, img, new_affine):
img.affine = new_affine
def inverse(self, data: torch.Tensor) -> torch.Tensor:
transform = self.pop_transform(data)
# Create inverse transform
orig_affine = transform[TraceKeys.EXTRA_INFO]["original_affine"]
orig_axcodes = nib.orientations.aff2axcodes(orig_affine)
inverse_transform = Orientation(axcodes=orig_axcodes, as_closest_canonical=False, labels=self.labels)
# Apply inverse
with inverse_transform.trace_transform(False):
data = inverse_transform(data)
return data
class Flip(InvertibleTransform):
"""
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
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.
"""
backend = [TransformBackends.TORCH]
def __init__(self, spatial_axis: Sequence[int] | int | None = None) -> None:
self.spatial_axis = spatial_axis
def update_meta(self, img, shape, axes):
# shape and axes include the channel dim
affine = img.affine
mat = convert_to_dst_type(torch.eye(len(affine)), affine)[0]
for axis in axes:
sp = axis - 1
mat[sp, sp], mat[sp, -1] = mat[sp, sp] * -1, shape[axis] - 1
img.affine = affine @ mat
def forward_image(self, img, axes) -> torch.Tensor:
return torch.flip(img, axes)
def __call__(self, img: torch.Tensor) -> torch.Tensor:
"""
Args:
img: channel first array, must have shape: (num_channels, H[, W, ..., ])
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
axes = map_spatial_axes(img.ndim, self.spatial_axis)
out = self.forward_image(img, axes)
if get_track_meta():
self.update_meta(out, out.shape, axes)
self.push_transform(out)
return out
def inverse(self, data: torch.Tensor) -> torch.Tensor:
self.pop_transform(data)
flipper = Flip(spatial_axis=self.spatial_axis)
with flipper.trace_transform(False):
return flipper(data)
class Resize(InvertibleTransform):
"""
Resize the input image to given spatial size (with scaling, not cropping/padding).
Implemented using :py:class:`torch.nn.functional.interpolate`.
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.
"""
backend = [TransformBackends.TORCH]
def __init__(
self,
spatial_size: Sequence[int] | int,
size_mode: str = "all",
mode: str = InterpolateMode.AREA,
align_corners: bool | None = None,
anti_aliasing: bool = False,
anti_aliasing_sigma: Sequence[float] | float | None = None,
) -> None:
self.size_mode = look_up_option(size_mode, ["all", "longest"])
self.spatial_size = spatial_size
self.mode: InterpolateMode = look_up_option(mode, InterpolateMode)
self.align_corners = align_corners
self.anti_aliasing = anti_aliasing
self.anti_aliasing_sigma = anti_aliasing_sigma
def __call__(
self,
img: torch.Tensor,
mode: str | None = None,
align_corners: bool | None = None,
anti_aliasing: bool | None = None,
anti_aliasing_sigma: Sequence[float] | float | None = None,
) -> torch.Tensor:
"""
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.
Raises:
ValueError: When ``self.spatial_size`` length is less than ``img`` spatial dimensions.
"""
anti_aliasing = self.anti_aliasing if anti_aliasing is None else anti_aliasing
anti_aliasing_sigma = self.anti_aliasing_sigma if anti_aliasing_sigma is None else anti_aliasing_sigma
input_ndim = img.ndim - 1 # spatial ndim
if self.size_mode == "all":
output_ndim = len(ensure_tuple(self.spatial_size))
if output_ndim > input_ndim:
input_shape = ensure_tuple_size(img.shape, output_ndim + 1, 1)
img = img.reshape(input_shape)
elif output_ndim < input_ndim:
raise ValueError(
"len(spatial_size) must be greater or equal to img spatial dimensions, "
f"got spatial_size={output_ndim} img={input_ndim}."
)
spatial_size_ = fall_back_tuple(self.spatial_size, img.shape[1:])
else: # for the "longest" mode
img_size = img.shape[1:]
if not isinstance(self.spatial_size, int):
raise ValueError("spatial_size must be an int number if size_mode is 'longest'.")
scale = self.spatial_size / max(img_size)
spatial_size_ = tuple(int(round(s * scale)) for s in img_size)
original_sp_size = img.shape[1:]
_mode = look_up_option(self.mode if mode is None else mode, InterpolateMode)
_align_corners = self.align_corners if align_corners is None else align_corners
if tuple(img.shape[1:]) == spatial_size_: # spatial shape is already the desired
img = convert_to_tensor(img, track_meta=get_track_meta())
return self._post_process(img, original_sp_size, spatial_size_, _mode, _align_corners, input_ndim)
img_ = convert_to_tensor(img, dtype=torch.float, track_meta=False)
if anti_aliasing and any(x < y for x, y in zip(spatial_size_, img_.shape[1:])):
factors = torch.div(torch.Tensor(list(img_.shape[1:])), torch.Tensor(spatial_size_))
if anti_aliasing_sigma is None:
# if sigma is not given, use the default sigma in skimage.transform.resize
anti_aliasing_sigma = torch.maximum(torch.zeros(factors.shape), (factors - 1) / 2).tolist()
else:
# if sigma is given, use the given value for downsampling axis
anti_aliasing_sigma = list(ensure_tuple_rep(anti_aliasing_sigma, len(spatial_size_)))
for axis in range(len(spatial_size_)):
anti_aliasing_sigma[axis] = anti_aliasing_sigma[axis] * int(factors[axis] > 1)
anti_aliasing_filter = GaussianSmooth(sigma=anti_aliasing_sigma)
img_ = convert_to_tensor(anti_aliasing_filter(img_), track_meta=False)
img = convert_to_tensor(img, track_meta=get_track_meta())
resized = torch.nn.functional.interpolate(
input=img_.unsqueeze(0), size=spatial_size_, mode=_mode, align_corners=_align_corners
)
out, *_ = convert_to_dst_type(resized.squeeze(0), img)
return self._post_process(out, original_sp_size, spatial_size_, _mode, _align_corners, input_ndim)
def _post_process(self, img: torch.Tensor, orig_size, sp_size, mode, align_corners, ndim) -> torch.Tensor:
if get_track_meta():
self.update_meta(img, orig_size, sp_size)
self.push_transform(
img,
orig_size=orig_size,
extra_info={
"mode": mode,
"align_corners": align_corners if align_corners is not None else TraceKeys.NONE,
"new_dim": len(orig_size) - ndim, # additional dims appended
},
)
return img
def update_meta(self, img, spatial_size, new_spatial_size):
affine = convert_to_tensor(img.affine, track_meta=False)
img.affine = scale_affine(affine, spatial_size, new_spatial_size)
def inverse(self, data: torch.Tensor) -> torch.Tensor:
transform = self.pop_transform(data)
return self.inverse_transform(data, transform)
def inverse_transform(self, data: torch.Tensor, transform) -> torch.Tensor:
orig_size = transform[TraceKeys.ORIG_SIZE]
mode = transform[TraceKeys.EXTRA_INFO]["mode"]
align_corners = transform[TraceKeys.EXTRA_INFO]["align_corners"]
xform = Resize(
spatial_size=orig_size, mode=mode, align_corners=None if align_corners == TraceKeys.NONE else align_corners
)
with xform.trace_transform(False):
data = xform(data)
for _ in range(transform[TraceKeys.EXTRA_INFO]["new_dim"]):
data = data.squeeze(-1) # remove the additional dims
return data
class Rotate(InvertibleTransform):
"""
Rotates an input image by given angle using :py:class:`monai.networks.layers.AffineTransform`.
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``.
"""
backend = [TransformBackends.TORCH]
def __init__(
self,
angle: Sequence[float] | float,
keep_size: bool = True,
mode: str = GridSampleMode.BILINEAR,
padding_mode: str = GridSamplePadMode.BORDER,
align_corners: bool = False,
dtype: DtypeLike | torch.dtype = torch.float32,
) -> None:
self.angle = angle
self.keep_size = keep_size
self.mode: str = look_up_option(mode, GridSampleMode)
self.padding_mode: str = look_up_option(padding_mode, GridSamplePadMode)
self.align_corners = align_corners
self.dtype = dtype
def __call__(
self,
img: torch.Tensor,
mode: str | None = None,
padding_mode: str | None = None,
align_corners: bool | None = None,
dtype: DtypeLike | torch.dtype = None,
) -> torch.Tensor:
"""
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``.
Raises:
ValueError: When ``img`` spatially is not one of [2D, 3D].
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
_dtype = get_equivalent_dtype(dtype or self.dtype or img.dtype, torch.Tensor)
im_shape = np.asarray(img.shape[1:]) # spatial dimensions
input_ndim = len(im_shape)
if input_ndim not in (2, 3):
raise ValueError(f"Unsupported image dimension: {input_ndim}, available options are [2, 3].")
_angle = ensure_tuple_rep(self.angle, 1 if input_ndim == 2 else 3)
transform = create_rotate(input_ndim, _angle)
shift = create_translate(input_ndim, ((im_shape - 1) / 2).tolist())
if self.keep_size:
output_shape = im_shape
else:
corners = np.asarray(np.meshgrid(*[(0, dim) for dim in im_shape], indexing="ij")).reshape(
(len(im_shape), -1)
)
corners = transform[:-1, :-1] @ corners # type: ignore
output_shape = np.asarray(corners.ptp(axis=1) + 0.5, dtype=int)
shift_1 = create_translate(input_ndim, (-(output_shape - 1) / 2).tolist())
transform = shift @ transform @ shift_1
img_t = img.to(_dtype)
transform_t, *_ = convert_to_dst_type(transform, img_t)
_mode = look_up_option(mode or self.mode, GridSampleMode)
_padding_mode = look_up_option(padding_mode or self.padding_mode, GridSamplePadMode)
_align_corners = self.align_corners if align_corners is None else align_corners
xform = AffineTransform(
normalized=False,
mode=_mode,
padding_mode=_padding_mode,
align_corners=_align_corners,
reverse_indexing=True,
)
output: torch.Tensor = xform(img_t.unsqueeze(0), transform_t, spatial_size=output_shape).float().squeeze(0)
out, *_ = convert_to_dst_type(output, dst=img, dtype=output.dtype)
if get_track_meta():
self.update_meta(out, transform_t)
self.push_transform(
out,
orig_size=img_t.shape[1:],
extra_info={
"rot_mat": transform,
"mode": _mode,
"padding_mode": _padding_mode,
"align_corners": _align_corners if _align_corners is not None else TraceKeys.NONE,
"dtype": str(_dtype)[6:], # dtype as string; remove "torch": torch.float32 -> float32
},
)
return out
def update_meta(self, img, rotate_mat):
affine = convert_to_tensor(img.affine, track_meta=False)
mat = to_affine_nd(len(affine) - 1, rotate_mat)
img.affine = affine @ convert_to_dst_type(mat, affine)[0]
def inverse(self, data: torch.Tensor) -> torch.Tensor:
transform = self.pop_transform(data)
return self.inverse_transform(data, transform)
def inverse_transform(self, data: torch.Tensor, transform) -> torch.Tensor:
fwd_rot_mat = transform[TraceKeys.EXTRA_INFO]["rot_mat"]
mode = transform[TraceKeys.EXTRA_INFO]["mode"]
padding_mode = transform[TraceKeys.EXTRA_INFO]["padding_mode"]
align_corners = transform[TraceKeys.EXTRA_INFO]["align_corners"]
dtype = transform[TraceKeys.EXTRA_INFO]["dtype"]
inv_rot_mat = linalg_inv(convert_to_numpy(fwd_rot_mat))
xform = AffineTransform(
normalized=False,
mode=mode,
padding_mode=padding_mode,
align_corners=False if align_corners == TraceKeys.NONE else align_corners,
reverse_indexing=True,
)
img_t: torch.Tensor = convert_data_type(data, MetaTensor, dtype=dtype)[0]
transform_t, *_ = convert_to_dst_type(inv_rot_mat, img_t)
sp_size = transform[TraceKeys.ORIG_SIZE]
out: torch.Tensor = xform(img_t.unsqueeze(0), transform_t, spatial_size=sp_size).float().squeeze(0)
out = convert_to_dst_type(out, dst=data, dtype=out.dtype)[0]
if isinstance(data, MetaTensor):
self.update_meta(out, transform_t)
return out
class Zoom(InvertibleTransform):
"""
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.
Args:
zoom: The zoom factor along the spatial axes.
If a float, zoom is the same for each spatial axis.