-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathdictionary.py
More file actions
1390 lines (1211 loc) · 64.7 KB
/
dictionary.py
File metadata and controls
1390 lines (1211 loc) · 64.7 KB
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 dictionary-based wrappers around the "vanilla" transforms for crop and pad operations
defined in :py:class:`monai.transforms.croppad.array`.
Class names are ended with 'd' to denote dictionary-based transforms.
"""
from __future__ import annotations
from collections.abc import Callable, Hashable, Mapping, Sequence
from copy import deepcopy
from typing import Any
import numpy as np
import torch
from monai.config import IndexSelection, KeysCollection, SequenceStr
from monai.config.type_definitions import NdarrayOrTensor
from monai.data.meta_tensor import MetaTensor
from monai.transforms.croppad.array import (
BorderPad,
BoundingRect,
CenterScaleCrop,
CenterSpatialCrop,
Crop,
CropForeground,
DivisiblePad,
Pad,
RandCropByLabelClasses,
RandCropByPosNegLabel,
RandScaleCrop,
RandSpatialCrop,
RandSpatialCropSamples,
RandWeightedCrop,
ResizeWithPadOrCrop,
SpatialCrop,
SpatialPad,
)
from monai.transforms.inverse import InvertibleTransform
from monai.transforms.traits import LazyTrait, MultiSampleTrait
from monai.transforms.transform import LazyTransform, MapTransform, Randomizable
from monai.transforms.utils import is_positive
from monai.utils import MAX_SEED, Method, PytorchPadMode, TraceKeys, ensure_tuple_rep
__all__ = [
"Padd",
"SpatialPadd",
"BorderPadd",
"DivisiblePadd",
"Cropd",
"RandCropd",
"SpatialCropd",
"CenterSpatialCropd",
"CenterScaleCropd",
"RandScaleCropd",
"RandSpatialCropd",
"RandSpatialCropSamplesd",
"CropForegroundd",
"RandWeightedCropd",
"RandCropByPosNegLabeld",
"ResizeWithPadOrCropd",
"BoundingRectd",
"RandCropByLabelClassesd",
"PadD",
"PadDict",
"SpatialPadD",
"SpatialPadDict",
"BorderPadD",
"BorderPadDict",
"DivisiblePadD",
"DivisiblePadDict",
"CropD",
"CropDict",
"RandCropD",
"RandCropDict",
"SpatialCropD",
"SpatialCropDict",
"CenterSpatialCropD",
"CenterSpatialCropDict",
"CenterScaleCropD",
"CenterScaleCropDict",
"RandScaleCropD",
"RandScaleCropDict",
"RandSpatialCropD",
"RandSpatialCropDict",
"RandSpatialCropSamplesD",
"RandSpatialCropSamplesDict",
"CropForegroundD",
"CropForegroundDict",
"RandWeightedCropD",
"RandWeightedCropDict",
"RandCropByPosNegLabelD",
"RandCropByPosNegLabelDict",
"ResizeWithPadOrCropD",
"ResizeWithPadOrCropDict",
"BoundingRectD",
"BoundingRectDict",
"RandCropByLabelClassesD",
"RandCropByLabelClassesDict",
]
class Padd(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Pad`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = Pad.backend
def __init__(
self,
keys: KeysCollection,
padder: Pad,
mode: SequenceStr = PytorchPadMode.CONSTANT,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
padder: pad transform for the input image.
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"``.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy)
if lazy is True and not isinstance(padder, LazyTrait):
raise ValueError("'padder' must inherit LazyTrait if lazy is True " f"'padder' is of type({type(padder)})")
self.padder = padder
self.mode = ensure_tuple_rep(mode, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, value: bool) -> None:
self._lazy = value
if isinstance(self.padder, LazyTransform):
self.padder.lazy = value
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
d = dict(data)
lazy_ = self.lazy if lazy is None else lazy
if lazy_ is True and not isinstance(self.padder, LazyTrait):
raise ValueError(
"'self.padder' must inherit LazyTrait if lazy is True " f"'self.padder' is of type({type(self.padder)}"
)
for key, m in self.key_iterator(d, self.mode):
if isinstance(self.padder, LazyTrait):
d[key] = self.padder(d[key], mode=m, lazy=lazy_)
else:
d[key] = self.padder(d[key], mode=m)
return d
def inverse(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.padder.inverse(d[key])
return d
class SpatialPadd(Padd):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.SpatialPad`.
Performs padding to the data, symmetric for all sides or all on one side for each dimension.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
def __init__(
self,
keys: KeysCollection,
spatial_size: Sequence[int] | int,
method: str = Method.SYMMETRIC,
mode: SequenceStr = PytorchPadMode.CONSTANT,
allow_missing_keys: bool = False,
lazy: bool = False,
**kwargs,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
spatial_size: the spatial size of output data after padding, if a dimension of the input
data size is larger than the pad size, will not pad that dimension.
If its components have non-positive values, the corresponding size of input image will be used.
for example: if the spatial size of input data is [30, 30, 30] and `spatial_size=[32, 25, -1]`,
the spatial size of output data will be [32, 30, 30].
method: {``"symmetric"``, ``"end"``}
Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``.
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"``.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
allow_missing_keys: don't raise exception if key is missing.
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.
"""
padder = SpatialPad(spatial_size, method, lazy=lazy, **kwargs)
Padd.__init__(self, keys, padder=padder, mode=mode, allow_missing_keys=allow_missing_keys, lazy=lazy)
class BorderPadd(Padd):
"""
Pad the input data by adding specified borders to every dimension.
Dictionary-based wrapper of :py:class:`monai.transforms.BorderPad`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = BorderPad.backend
def __init__(
self,
keys: KeysCollection,
spatial_border: Sequence[int] | int,
mode: SequenceStr = PytorchPadMode.CONSTANT,
allow_missing_keys: bool = False,
lazy: bool = False,
**kwargs,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
spatial_border: specified size for every spatial border. it can be 3 shapes:
- single int number, pad all the borders with the same size.
- length equals the length of image shape, pad every spatial dimension separately.
for example, image shape(CHW) is [1, 4, 4], spatial_border is [2, 1],
pad every border of H dim with 2, pad every border of W dim with 1, result shape is [1, 8, 6].
- length equals 2 x (length of image shape), pad every border of every dimension separately.
for example, image shape(CHW) is [1, 4, 4], spatial_border is [1, 2, 3, 4], pad top of H dim with 1,
pad bottom of H dim with 2, pad left of W dim with 3, pad right of W dim with 4.
the result shape is [1, 7, 11].
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"``.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
allow_missing_keys: don't raise exception if key is missing.
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.
"""
padder = BorderPad(spatial_border=spatial_border, lazy=lazy, **kwargs)
Padd.__init__(self, keys, padder=padder, mode=mode, allow_missing_keys=allow_missing_keys, lazy=lazy)
class DivisiblePadd(Padd):
"""
Pad the input data, so that the spatial sizes are divisible by `k`.
Dictionary-based wrapper of :py:class:`monai.transforms.DivisiblePad`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = DivisiblePad.backend
def __init__(
self,
keys: KeysCollection,
k: Sequence[int] | int,
mode: SequenceStr = PytorchPadMode.CONSTANT,
method: str = Method.SYMMETRIC,
allow_missing_keys: bool = False,
lazy: bool = False,
**kwargs,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
k: the target k for each spatial dimension.
if `k` is negative or 0, the original size is preserved.
if `k` is an int, the same `k` be applied to all the input spatial dimensions.
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"``.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
method: {``"symmetric"``, ``"end"``}
Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``.
allow_missing_keys: don't raise exception if key is missing.
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.
See also :py:class:`monai.transforms.SpatialPad`
"""
padder = DivisiblePad(k=k, method=method, lazy=lazy, **kwargs)
Padd.__init__(self, keys, padder=padder, mode=mode, allow_missing_keys=allow_missing_keys, lazy=lazy)
class Cropd(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of abstract class :py:class:`monai.transforms.Crop`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
cropper: crop transform for the input image.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
backend = Crop.backend
def __init__(self, keys: KeysCollection, cropper: Crop, allow_missing_keys: bool = False, lazy: bool = False):
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy)
self.cropper = cropper
@LazyTransform.lazy.setter # type: ignore
def lazy(self, value: bool) -> None:
self._lazy = value
if isinstance(self.cropper, LazyTransform):
self.cropper.lazy = value
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
d = dict(data)
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(d):
d[key] = self.cropper(d[key], lazy=lazy_) # type: ignore
return d
def inverse(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.cropper.inverse(d[key])
return d
class RandCropd(Cropd, Randomizable):
"""
Base class for random crop transform.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
cropper: random crop transform for the input image.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
backend = Crop.backend
def __init__(self, keys: KeysCollection, cropper: Crop, allow_missing_keys: bool = False, lazy: bool = False):
super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy)
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandCropd:
super().set_random_state(seed, state)
if isinstance(self.cropper, Randomizable):
self.cropper.set_random_state(seed, state)
return self
def randomize(self, img_size: Sequence[int]) -> None:
if isinstance(self.cropper, Randomizable):
self.cropper.randomize(img_size)
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
d = dict(data)
# the first key must exist to execute random operations
first_item = d[self.first_key(d)]
self.randomize(first_item.peek_pending_shape() if isinstance(first_item, MetaTensor) else first_item.shape[1:])
lazy_ = self.lazy if lazy is None else lazy
if lazy_ is True and not isinstance(self.cropper, LazyTrait):
raise ValueError(
"'self.cropper' must inherit LazyTrait if lazy is True "
f"'self.cropper' is of type({type(self.cropper)}"
)
for key in self.key_iterator(d):
kwargs = {"randomize": False} if isinstance(self.cropper, Randomizable) else {}
if isinstance(self.cropper, LazyTrait):
kwargs["lazy"] = lazy_
d[key] = self.cropper(d[key], **kwargs) # type: ignore
return d
class SpatialCropd(Cropd):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.SpatialCrop`.
General purpose cropper to produce sub-volume region of interest (ROI).
If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension.
So the cropped result may be smaller than the expected ROI, and the cropped results of several images may
not have exactly the same shape.
It can support to crop ND spatial (channel-first) data.
The cropped region can be parameterised in various ways:
- a list of slices for each spatial dimension (allows for use of -ve indexing and `None`)
- a spatial center and size
- the start and end coordinates of the ROI
ROI parameters (``roi_center``, ``roi_size``, ``roi_start``, ``roi_end``) can also be specified as
string dictionary keys. When a string is provided, the actual coordinate values are read from the
data dictionary at call time. This enables pipelines where coordinates are computed by earlier
transforms (e.g., :py:class:`monai.transforms.TransformPointsWorldToImaged`) and stored in the
data dictionary under the given key.
Example::
from monai.transforms import Compose, TransformPointsWorldToImaged, SpatialCropd
pipeline = Compose([
TransformPointsWorldToImaged(keys="roi_start", refer_keys="image"),
TransformPointsWorldToImaged(keys="roi_end", refer_keys="image"),
SpatialCropd(keys="image", roi_start="roi_start", roi_end="roi_end"),
])
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
def __init__(
self,
keys: KeysCollection,
roi_center: Sequence[int] | int | str | None = None,
roi_size: Sequence[int] | int | str | None = None,
roi_start: Sequence[int] | int | str | None = None,
roi_end: Sequence[int] | int | str | None = None,
roi_slices: Sequence[slice] | None = None,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
roi_center: voxel coordinates for center of the crop ROI, or a string key to look up
the coordinates from the data dictionary.
roi_size: size of the crop ROI, if a dimension of ROI size is larger than image size,
will not crop that dimension of the image. Can also be a string key.
roi_start: voxel coordinates for start of the crop ROI, or a string key to look up
the coordinates from the data dictionary.
roi_end: voxel coordinates for end of the crop ROI, if a coordinate is out of image,
use the end coordinate of image. Can also be a string key.
roi_slices: list of slices for each of the spatial dimensions.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
self._roi_center = roi_center
self._roi_size = roi_size
self._roi_start = roi_start
self._roi_end = roi_end
self._roi_slices = roi_slices
self._has_str_roi = any(isinstance(v, str) for v in [roi_center, roi_size, roi_start, roi_end])
if not self._has_str_roi:
cropper = SpatialCrop(roi_center, roi_size, roi_start, roi_end, roi_slices, lazy=lazy)
else:
# Placeholder cropper for the string-key path. Replaced on self.cropper at
# __call__ time once string keys are resolved from the data dictionary.
cropper = SpatialCrop(roi_start=[0], roi_end=[1], lazy=lazy)
super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy)
@staticmethod
def _resolve_roi_param(val, d):
"""Resolve an ROI parameter from the data dictionary if it is a string key.
Args:
val: the ROI parameter value. If a string, it is used as a key to look up
the actual value from ``d``. Otherwise returned as-is.
d: the data dictionary.
Returns:
The resolved ROI parameter. Tensors and numpy arrays are flattened to 1-D
and rounded to int64 so they can be consumed by ``Crop.compute_slices``.
Raises:
KeyError: if ``val`` is a string key that does not exist in ``d``.
"""
if not isinstance(val, str):
return val
if val not in d:
raise KeyError(f"ROI key '{val}' not found in the data dictionary.")
resolved = d[val]
# ApplyTransformToPoints outputs tensors of shape (C, N, dims).
# A single coordinate like [142.5, -67.3, 301.8] becomes shape (1, 1, 3).
# Flatten to 1-D and round to integers for compute_slices.
# Uses banker's rounding (torch.round) to avoid systematic bias in spatial coordinates.
if isinstance(resolved, np.ndarray):
resolved = torch.from_numpy(resolved)
if isinstance(resolved, torch.Tensor):
resolved = torch.round(resolved.flatten()).to(torch.int64)
return resolved
@property
def requires_current_data(self):
"""bool: Whether this transform requires the current data dictionary to resolve ROI parameters."""
return self._has_str_roi
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: dictionary of data items to be transformed.
lazy: whether to execute lazily. If ``None``, uses the instance default.
Returns:
Dictionary with cropped data for each key.
"""
if not self._has_str_roi:
return super().__call__(data, lazy=lazy)
d = dict(data)
roi_center = self._resolve_roi_param(self._roi_center, d)
roi_size = self._resolve_roi_param(self._roi_size, d)
roi_start = self._resolve_roi_param(self._roi_start, d)
roi_end = self._resolve_roi_param(self._roi_end, d)
lazy_ = self.lazy if lazy is None else lazy
self.cropper = SpatialCrop(
roi_center=roi_center,
roi_size=roi_size,
roi_start=roi_start,
roi_end=roi_end,
roi_slices=self._roi_slices,
lazy=lazy_,
)
for key in self.key_iterator(d):
d[key] = self.cropper(d[key], lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTensor]:
"""
Inverse of the crop transform, restoring the original spatial dimensions via padding.
For the string-key path, ``self.cropper`` is recreated on each ``__call__``, so its
``id()`` won't match the one stored in the MetaTensor's transform stack. This override
bypasses the ID check and applies the inverse directly using the crop info stored in the
MetaTensor.
Args:
data: dictionary of cropped ``MetaTensor`` items.
Returns:
Dictionary with inverse-transformed (padded) data for each key.
"""
if not self._has_str_roi:
return super().inverse(data)
d = dict(data)
for key in self.key_iterator(d):
transform = self.cropper.pop_transform(d[key], check=False)
cropped = transform[TraceKeys.EXTRA_INFO]["cropped"]
inverse_transform = BorderPad(cropped)
with inverse_transform.trace_transform(False):
d[key] = inverse_transform(d[key])
return d
class CenterSpatialCropd(Cropd):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.CenterSpatialCrop`.
If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension.
So the cropped result may be smaller than the expected ROI, and the cropped results of several images may
not have exactly the same shape.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: monai.transforms.MapTransform
roi_size: the size of the crop region e.g. [224,224,128]
if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
If its components have non-positive values, the corresponding size of input image will be used.
for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`,
the spatial size of output data will be [32, 40, 40].
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
def __init__(
self, keys: KeysCollection, roi_size: Sequence[int] | int, allow_missing_keys: bool = False, lazy: bool = False
) -> None:
cropper = CenterSpatialCrop(roi_size, lazy=lazy)
super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy)
class CenterScaleCropd(Cropd):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.CenterScaleCrop`.
Note: as using the same scaled ROI to crop, all the input data specified by `keys` should have
the same spatial shape.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: monai.transforms.MapTransform
roi_scale: specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5] or a number for all dims.
If its components have non-positive values, will use `1.0` instead, which means the input image size.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
def __init__(
self,
keys: KeysCollection,
roi_scale: Sequence[float] | float,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
cropper = CenterScaleCrop(roi_scale, lazy=lazy)
super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy)
class RandSpatialCropd(RandCropd):
"""
Dictionary-based version :py:class:`monai.transforms.RandSpatialCrop`.
Crop image with random size or specific size ROI. It can crop at a random position as
center or at the image center. And allows to set the minimum and maximum size to limit the randomly
generated ROI. Suppose all the expected fields specified by `keys` have same shape.
Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size,
will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped
results of several images may not have exactly the same shape.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: monai.transforms.MapTransform
roi_size: if `random_size` is True, it specifies the minimum crop region.
if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128]
if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
If its components have non-positive values, the corresponding size of input image will be used.
for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`,
the spatial size of output data will be [32, 40, 40].
max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size`
can specify the max crop region size. if None, defaults to the input image size.
if its components have non-positive values, the corresponding size of input image will be used.
random_center: crop at random position as center or the image center.
random_size: crop with random size or specific size ROI.
if True, the actual size is sampled from:
`randint(roi_scale * image spatial size, max_roi_scale * image spatial size + 1)`.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
def __init__(
self,
keys: KeysCollection,
roi_size: Sequence[int] | int,
max_roi_size: Sequence[int] | int | None = None,
random_center: bool = True,
random_size: bool = False,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
cropper = RandSpatialCrop(roi_size, max_roi_size, random_center, random_size, lazy=lazy)
super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy)
class RandScaleCropd(RandCropd):
"""
Dictionary-based version :py:class:`monai.transforms.RandScaleCrop`.
Crop image with random size or specific size ROI.
It can crop at a random position as center or at the image center.
And allows to set the minimum and maximum scale of image size to limit the randomly generated ROI.
Suppose all the expected fields specified by `keys` have same shape.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: monai.transforms.MapTransform
roi_scale: if `random_size` is True, it specifies the minimum crop size: `roi_scale * image spatial size`.
if `random_size` is False, it specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5].
If its components have non-positive values, will use `1.0` instead, which means the input image size.
max_roi_scale: if `random_size` is True and `roi_scale` specifies the min crop region size, `max_roi_scale`
can specify the max crop region size: `max_roi_scale * image spatial size`.
if None, defaults to the input image size. if its components have non-positive values,
will use `1.0` instead, which means the input image size.
random_center: crop at random position as center or the image center.
random_size: crop with random size or specified size ROI by `roi_scale * image spatial size`.
if True, the actual size is sampled from:
`randint(roi_scale * image spatial size, max_roi_scale * image spatial size + 1)`.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
"""
def __init__(
self,
keys: KeysCollection,
roi_scale: Sequence[float] | float,
max_roi_scale: Sequence[float] | float | None = None,
random_center: bool = True,
random_size: bool = False,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
cropper = RandScaleCrop(roi_scale, max_roi_scale, random_center, random_size, lazy=lazy)
super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy)
class RandSpatialCropSamplesd(Randomizable, MapTransform, LazyTransform, MultiSampleTrait):
"""
Dictionary-based version :py:class:`monai.transforms.RandSpatialCropSamples`.
Crop image with random size or specific size ROI to generate a list of N samples.
It can crop at a random position as center or at the image center. And allows to set
the minimum size to limit the randomly generated ROI. Suppose all the expected fields
specified by `keys` have same shape, and add `patch_index` to the corresponding metadata.
It will return a list of dictionaries for all the cropped images.
Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size,
will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped
results of several images may not have exactly the same shape.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: monai.transforms.MapTransform
roi_size: if `random_size` is True, it specifies the minimum crop region.
if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128]
if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
If its components have non-positive values, the corresponding size of input image will be used.
for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`,
the spatial size of output data will be [32, 40, 40].
num_samples: number of samples (crop regions) to take in the returned list.
max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size`
can specify the max crop region size. if None, defaults to the input image size.
if its components have non-positive values, the corresponding size of input image will be used.
random_center: crop at random position as center or the image center.
random_size: crop with random size or specific size ROI.
The actual size is sampled from `randint(roi_size, img_size)`.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
Raises:
ValueError: When ``num_samples`` is nonpositive.
"""
backend = RandSpatialCropSamples.backend
def __init__(
self,
keys: KeysCollection,
roi_size: Sequence[int] | int,
num_samples: int,
max_roi_size: Sequence[int] | int | None = None,
random_center: bool = True,
random_size: bool = False,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy)
self.cropper = RandSpatialCropSamples(
roi_size, num_samples, max_roi_size, random_center, random_size, lazy=lazy
)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, value: bool) -> None:
self._lazy = value
self.cropper.lazy = value
def randomize(self, data: Any | None = None) -> None:
self.sub_seed = self.R.randint(MAX_SEED, dtype="uint32")
def __call__(
self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None
) -> list[dict[Hashable, torch.Tensor]]:
ret: list[dict[Hashable, torch.Tensor]] = [dict(data) for _ in range(self.cropper.num_samples)]
# deep copy all the unmodified data
for i in range(self.cropper.num_samples):
for key in set(data.keys()).difference(set(self.keys)):
ret[i][key] = deepcopy(data[key])
# for each key we reset the random state to ensure crops are the same
self.randomize()
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(dict(data)):
self.cropper.set_random_state(seed=int(self.sub_seed))
for i, im in enumerate(self.cropper(data[key], lazy=lazy_)):
ret[i][key] = im
return ret
class CropForegroundd(Cropd):
"""
Dictionary-based version :py:class:`monai.transforms.CropForeground`.
Crop only the foreground object of the expected images.
The typical usage is to help training and evaluation if the valid part is small in the whole medical image.
The valid part can be determined by any field in the data with `source_key`, for example:
- Select values > 0 in image field as the foreground and crop on all fields specified by `keys`.
- Select label = 3 in label field as the foreground to crop on all fields specified by `keys`.
- Select label > 0 in the third channel of a One-Hot label field as the foreground to crop all `keys` fields.
Users can define arbitrary function to select expected foreground from the whole source image or specified
channels. And it can also add margin to every dim of the bounding box of foreground object.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
def __init__(
self,
keys: KeysCollection,
source_key: str,
select_fn: Callable = is_positive,
channel_indices: IndexSelection | None = None,
margin: Sequence[int] | int = 0,
allow_smaller: bool = False,
k_divisible: Sequence[int] | int = 1,
mode: SequenceStr = PytorchPadMode.CONSTANT,
start_coord_key: str | None = "foreground_start_coord",
end_coord_key: str | None = "foreground_end_coord",
allow_missing_keys: bool = False,
lazy: bool = False,
**pad_kwargs,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
source_key: data source to generate the bounding box of foreground, can be image or label, etc.
select_fn: function to select expected foreground, default is to select values > 0.
channel_indices: if defined, select foreground only on the specified channels
of image. if None, select foreground on the whole image.
margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims.
allow_smaller: when computing box size with `margin`, whether to allow the image edges to be smaller than the
final box edges. If `False`, part of a padded output box might be outside of the original image, if `True`,
the image edges will be used as the box edges. Default to `False`.
The default value is changed from `True` to `False` in v1.5.0.
k_divisible: make each spatial dimension to be divisible by k, default to 1.
if `k_divisible` is an int, the same `k` be applied to all the input spatial dimensions.
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"``.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
it also can be a sequence of string, each element corresponds to a key in ``keys``.
start_coord_key: key to record the start coordinate of spatial bounding box for foreground.
end_coord_key: key to record the end coordinate of spatial bounding box for foreground.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
pad_kwargs: other arguments for the `np.pad` or `torch.pad` function.
note that `np.pad` treats channel dimension as the first dimension.
"""
self.source_key = source_key
self.start_coord_key = start_coord_key
self.end_coord_key = end_coord_key
cropper = CropForeground(
select_fn=select_fn,
channel_indices=channel_indices,
margin=margin,
allow_smaller=allow_smaller,
k_divisible=k_divisible,
lazy=lazy,
**pad_kwargs,
)
super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy)
self.mode = ensure_tuple_rep(mode, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, value: bool) -> None:
self._lazy = value
self.cropper.lazy = value
@property
def requires_current_data(self):
return True
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
d = dict(data)
self.cropper: CropForeground
box_start, box_end = self.cropper.compute_bounding_box(img=d[self.source_key])
if self.start_coord_key is not None:
d[self.start_coord_key] = box_start # type: ignore
if self.end_coord_key is not None:
d[self.end_coord_key] = box_end # type: ignore
lazy_ = self.lazy if lazy is None else lazy
for key, m in self.key_iterator(d, self.mode):
d[key] = self.cropper.crop_pad(img=d[key], box_start=box_start, box_end=box_end, mode=m, lazy=lazy_)
return d
class RandWeightedCropd(Randomizable, MapTransform, LazyTransform, MultiSampleTrait):
"""
Samples a list of `num_samples` image patches according to the provided `weight_map`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
w_key: key for the weight map. The corresponding value will be used as the sampling weights,
it should be a single-channel array in size, for example, `(1, spatial_dim_0, spatial_dim_1, ...)`
spatial_size: the spatial size of the image patch e.g. [224, 224, 128].
If its components have non-positive values, the corresponding size of `img` will be used.
num_samples: number of samples (image patches) to take in the returned list.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
See Also:
:py:class:`monai.transforms.RandWeightedCrop`
"""
backend = SpatialCrop.backend
def __init__(
self,
keys: KeysCollection,
w_key: str,
spatial_size: Sequence[int] | int,
num_samples: int = 1,
allow_missing_keys: bool = False,
lazy: bool = False,
):
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy)
self.w_key = w_key
self.cropper = RandWeightedCrop(spatial_size, num_samples, lazy=lazy)
def set_random_state(
self, seed: int | None = None, state: np.random.RandomState | None = None
) -> RandWeightedCropd:
super().set_random_state(seed, state)
self.cropper.set_random_state(seed, state)
return self
def randomize(self, weight_map: NdarrayOrTensor) -> None:
self.cropper.randomize(weight_map)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, value: bool) -> None:
self._lazy = value
self.cropper.lazy = value
def __call__(
self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None
) -> list[dict[Hashable, torch.Tensor]]:
# output starts as empty list of dictionaries
ret: list = [dict(data) for _ in range(self.cropper.num_samples)]
# deep copy all the unmodified data
for i in range(self.cropper.num_samples):
for key in set(data.keys()).difference(set(self.keys)):
ret[i][key] = deepcopy(data[key])
self.randomize(weight_map=data[self.w_key])
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(data):
for i, im in enumerate(self.cropper(data[key], randomize=False, lazy=lazy_)):
ret[i][key] = im
return ret
class RandCropByPosNegLabeld(Randomizable, MapTransform, LazyTransform, MultiSampleTrait):
"""
Dictionary-based version :py:class:`monai.transforms.RandCropByPosNegLabel`.