-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
dictionary.py
1782 lines (1514 loc) · 71.4 KB
/
dictionary.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 dictionary-based wrappers around the "vanilla" transforms for utility functions
defined in :py:class:`monai.transforms.utility.array`.
Class names are ended with 'd' to denote dictionary-based transforms.
"""
from __future__ import annotations
import re
from collections.abc import Callable, Hashable, Mapping
from copy import deepcopy
from typing import Any, Sequence, cast
import numpy as np
import torch
from monai.config import DtypeLike, KeysCollection
from monai.config.type_definitions import NdarrayOrTensor
from monai.data.meta_tensor import MetaObj, MetaTensor
from monai.data.utils import no_collation
from monai.transforms.inverse import InvertibleTransform
from monai.transforms.traits import MultiSampleTrait, RandomizableTrait
from monai.transforms.transform import MapTransform, Randomizable, RandomizableTransform
from monai.transforms.utility.array import (
AddCoordinateChannels,
AddExtremePointsChannel,
AsChannelLast,
CastToType,
ClassesToIndices,
ConvertToMultiChannelBasedOnBratsClasses,
CuCIM,
DataStats,
EnsureChannelFirst,
EnsureType,
FgBgToIndices,
Identity,
ImageFilter,
IntensityStats,
LabelToMask,
Lambda,
MapLabelValue,
RemoveRepeatedChannel,
RepeatChannel,
SimulateDelay,
SplitDim,
SqueezeDim,
ToCupy,
ToDevice,
ToNumpy,
ToPIL,
TorchVision,
ToTensor,
Transpose,
)
from monai.transforms.utils import extreme_points_to_image, get_extreme_points
from monai.transforms.utils_pytorch_numpy_unification import concatenate
from monai.utils import ensure_tuple, ensure_tuple_rep
from monai.utils.enums import PostFix, TraceKeys, TransformBackends
from monai.utils.type_conversion import convert_to_dst_type
__all__ = [
"AddCoordinateChannelsD",
"AddCoordinateChannelsDict",
"AddCoordinateChannelsd",
"AddExtremePointsChannelD",
"AddExtremePointsChannelDict",
"AddExtremePointsChanneld",
"AsChannelLastD",
"AsChannelLastDict",
"AsChannelLastd",
"CastToTypeD",
"CastToTypeDict",
"CastToTyped",
"ConcatItemsD",
"ConcatItemsDict",
"ConcatItemsd",
"ConvertToMultiChannelBasedOnBratsClassesD",
"ConvertToMultiChannelBasedOnBratsClassesDict",
"ConvertToMultiChannelBasedOnBratsClassesd",
"CopyItemsD",
"CopyItemsDict",
"CopyItemsd",
"CuCIMd",
"CuCIMD",
"CuCIMDict",
"DataStatsD",
"DataStatsDict",
"DataStatsd",
"DeleteItemsD",
"DeleteItemsDict",
"DeleteItemsd",
"EnsureChannelFirstD",
"EnsureChannelFirstDict",
"EnsureChannelFirstd",
"EnsureTypeD",
"EnsureTypeDict",
"EnsureTyped",
"FgBgToIndicesD",
"FgBgToIndicesDict",
"FgBgToIndicesd",
"IdentityD",
"IdentityDict",
"Identityd",
"IntensityStatsd",
"IntensityStatsD",
"IntensityStatsDict",
"ImageFilterd",
"LabelToMaskD",
"LabelToMaskDict",
"LabelToMaskd",
"LambdaD",
"LambdaDict",
"Lambdad",
"MapLabelValueD",
"MapLabelValueDict",
"MapLabelValued",
"FlattenSubKeysd",
"FlattenSubKeysD",
"FlattenSubKeysDict",
"RandCuCIMd",
"RandCuCIMD",
"RandCuCIMDict",
"RandImageFilterd",
"RandLambdaD",
"RandLambdaDict",
"RandLambdad",
"RandTorchVisionD",
"RandTorchVisionDict",
"RandTorchVisiond",
"RemoveRepeatedChannelD",
"RemoveRepeatedChannelDict",
"RemoveRepeatedChanneld",
"RepeatChannelD",
"RepeatChannelDict",
"RepeatChanneld",
"SelectItemsD",
"SelectItemsDict",
"SelectItemsd",
"SimulateDelayD",
"SimulateDelayDict",
"SimulateDelayd",
"SplitDimD",
"SplitDimDict",
"SplitDimd",
"SqueezeDimD",
"SqueezeDimDict",
"SqueezeDimd",
"ToCupyD",
"ToCupyDict",
"ToCupyd",
"ToDeviced",
"ToDeviceD",
"ToDeviceDict",
"ToNumpyD",
"ToNumpyDict",
"ToNumpyd",
"ToPILD",
"ToPILDict",
"ToPILd",
"ToTensorD",
"ToTensorDict",
"ToTensord",
"TorchVisionD",
"TorchVisionDict",
"TorchVisiond",
"Transposed",
"TransposeDict",
"TransposeD",
"ClassesToIndicesd",
"ClassesToIndicesD",
"ClassesToIndicesDict",
]
DEFAULT_POST_FIX = PostFix.meta()
class Identityd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Identity`.
"""
backend = Identity.backend
def __init__(self, keys: KeysCollection, allow_missing_keys: bool = False) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.identity = Identity()
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.identity(d[key])
return d
class AsChannelLastd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.AsChannelLast`.
"""
backend = AsChannelLast.backend
def __init__(self, keys: KeysCollection, channel_dim: int = 0, allow_missing_keys: bool = False) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
channel_dim: which dimension of input image is the channel, default is the first dimension.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.converter = AsChannelLast(channel_dim=channel_dim)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.converter(d[key])
return d
class EnsureChannelFirstd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.EnsureChannelFirst`.
"""
backend = EnsureChannelFirst.backend
def __init__(
self, keys: KeysCollection, strict_check: bool = True, allow_missing_keys: bool = False, channel_dim=None
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
strict_check: whether to raise an error when the meta information is insufficient.
allow_missing_keys: don't raise exception if key is missing.
channel_dim: This argument can be used to specify the original channel dimension (integer) of the input array.
It overrides the `original_channel_dim` from provided MetaTensor input.
If the input array doesn't have a channel dim, this value should be ``'no_channel'``.
If this is set to `None`, this class relies on `img` or `meta_dict` to provide the channel dimension.
"""
super().__init__(keys, allow_missing_keys)
self.adjuster = EnsureChannelFirst(strict_check=strict_check, channel_dim=channel_dim)
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
meta_dict = d[key].meta if isinstance(d[key], MetaTensor) else None # type: ignore[attr-defined]
d[key] = self.adjuster(d[key], meta_dict)
return d
class RepeatChanneld(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.RepeatChannel`.
"""
backend = RepeatChannel.backend
def __init__(self, keys: KeysCollection, repeats: int, allow_missing_keys: bool = False) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
repeats: the number of repetitions for each element.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.repeater = RepeatChannel(repeats)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.repeater(d[key])
return d
class RemoveRepeatedChanneld(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.RemoveRepeatedChannel`.
"""
backend = RemoveRepeatedChannel.backend
def __init__(self, keys: KeysCollection, repeats: int, allow_missing_keys: bool = False) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
repeats: the number of repetitions for each element.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.repeater = RemoveRepeatedChannel(repeats)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.repeater(d[key])
return d
class SplitDimd(MapTransform, MultiSampleTrait):
backend = SplitDim.backend
def __init__(
self,
keys: KeysCollection,
output_postfixes: Sequence[str] | None = None,
dim: int = 0,
keepdim: bool = True,
update_meta: bool = True,
list_output: bool = False,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
output_postfixes: the postfixes to construct keys to store split data.
for example: if the key of input data is `pred` and split 2 classes, the output
data keys will be: pred_(output_postfixes[0]), pred_(output_postfixes[1])
if None, using the index number: `pred_0`, `pred_1`, ... `pred_N`.
dim: which dimension of input image is the channel, default to 0.
keepdim: if `True`, output will have singleton in the split dimension. If `False`, this
dimension will be squeezed.
update_meta: if `True`, copy `[key]_meta_dict` for each output and update affine to
reflect the cropped image
list_output: it `True`, the output will be a list of dictionaries with the same keys as original.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.output_postfixes = output_postfixes
self.splitter = SplitDim(dim, keepdim, update_meta)
self.list_output = list_output
if self.list_output is None and self.output_postfixes is not None:
raise ValueError("`output_postfixes` should not be provided when `list_output` is `True`.")
def __call__(
self, data: Mapping[Hashable, torch.Tensor]
) -> dict[Hashable, torch.Tensor] | list[dict[Hashable, torch.Tensor]]:
d = dict(data)
all_keys = list(set(self.key_iterator(d)))
if self.list_output:
output = []
results = [self.splitter(d[key]) for key in all_keys]
for row in zip(*results):
new_dict = dict(zip(all_keys, row))
# fill in the extra keys with unmodified data
for k in set(d.keys()).difference(set(all_keys)):
new_dict[k] = deepcopy(d[k])
output.append(new_dict)
return output
for key in all_keys:
rets = self.splitter(d[key])
postfixes: Sequence = list(range(len(rets))) if self.output_postfixes is None else self.output_postfixes
if len(postfixes) != len(rets):
raise ValueError(f"count of splits must match output_postfixes, {len(postfixes)} != {len(rets)}.")
for i, r in enumerate(rets):
split_key = f"{key}_{postfixes[i]}"
if split_key in d:
raise RuntimeError(f"input data already contains key {split_key}.")
d[split_key] = r
return d
class CastToTyped(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.CastToType`.
"""
backend = CastToType.backend
def __init__(
self,
keys: KeysCollection,
dtype: Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtype = np.float32,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dtype: convert image to this data type, default is `np.float32`.
it also can be a sequence of dtypes or torch.dtype,
each element corresponds to a key in ``keys``.
allow_missing_keys: don't raise exception if key is missing.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
self.converter = CastToType()
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key, dtype in self.key_iterator(d, self.dtype):
d[key] = self.converter(d[key], dtype=dtype)
return d
class ToTensord(MapTransform, InvertibleTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.ToTensor`.
"""
backend = ToTensor.backend
def __init__(
self,
keys: KeysCollection,
dtype: torch.dtype | None = None,
device: torch.device | str | None = None,
wrap_sequence: bool = True,
track_meta: bool | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dtype: target data content type to convert, for example: torch.float, etc.
device: specify the target device to put the Tensor data.
wrap_sequence: if `False`, then lists will recursively call this function, default to `True`.
E.g., if `False`, `[1, 2]` -> `[tensor(1), tensor(2)]`, if `True`, then `[1, 2]` -> `tensor([1, 2])`.
track_meta: if `True` convert to ``MetaTensor``, otherwise to Pytorch ``Tensor``,
if ``None`` behave according to return value of py:func:`monai.data.meta_obj.get_track_meta`.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.converter = ToTensor(dtype=dtype, device=device, wrap_sequence=wrap_sequence, track_meta=track_meta)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.converter(d[key])
self.push_transform(d, key)
return d
def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
# Remove the applied transform
self.pop_transform(d, key)
# Create inverse transform
inverse_transform = ToNumpy()
# Apply inverse
d[key] = inverse_transform(d[key])
return d
class EnsureTyped(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.EnsureType`.
Ensure the input data to be a PyTorch Tensor or numpy array, support: `numpy array`, `PyTorch Tensor`,
`float`, `int`, `bool`, `string` and `object` keep the original.
If passing a dictionary, list or tuple, still return dictionary, list or tuple and recursively convert
every item to the expected data type if `wrap_sequence=False`.
Note: Currently, we only convert tensor data to numpy array or scalar number in the inverse operation.
"""
backend = EnsureType.backend
def __init__(
self,
keys: KeysCollection,
data_type: str = "tensor",
dtype: Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtype = None,
device: torch.device | None = None,
wrap_sequence: bool = True,
track_meta: bool | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
data_type: target data type to convert, should be "tensor" or "numpy".
dtype: target data content type to convert, for example: np.float32, torch.float, etc.
It also can be a sequence of dtype, each element corresponds to a key in ``keys``.
device: for Tensor data type, specify the target device.
wrap_sequence: if `False`, then lists will recursively call this function, default to `True`.
E.g., if `False`, `[1, 2]` -> `[tensor(1), tensor(2)]`, if `True`, then `[1, 2]` -> `tensor([1, 2])`.
track_meta: whether to convert to `MetaTensor` when `data_type` is "tensor".
If False, the output data type will be `torch.Tensor`. Default to the return value of `get_track_meta`.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
self.converter = EnsureType(
data_type=data_type, device=device, wrap_sequence=wrap_sequence, track_meta=track_meta
)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key, dtype in self.key_iterator(d, self.dtype):
d[key] = self.converter(d[key], dtype)
return d
class ToNumpyd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.ToNumpy`.
"""
backend = ToNumpy.backend
def __init__(
self,
keys: KeysCollection,
dtype: DtypeLike = None,
wrap_sequence: bool = True,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dtype: target data type when converting to numpy array.
wrap_sequence: if `False`, then lists will recursively call this function, default to `True`.
E.g., if `False`, `[1, 2]` -> `[array(1), array(2)]`, if `True`, then `[1, 2]` -> `array([1, 2])`.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.converter = ToNumpy(dtype=dtype, wrap_sequence=wrap_sequence)
def __call__(self, data: Mapping[Hashable, Any]) -> dict[Hashable, Any]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.converter(d[key])
return d
class ToCupyd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.ToCupy`.
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dtype: data type specifier. It is inferred from the input by default.
if not None, must be an argument of `numpy.dtype`, for more details:
https://docs.cupy.dev/en/stable/reference/generated/cupy.array.html.
wrap_sequence: if `False`, then lists will recursively call this function, default to `True`.
E.g., if `False`, `[1, 2]` -> `[array(1), array(2)]`, if `True`, then `[1, 2]` -> `array([1, 2])`.
allow_missing_keys: don't raise exception if key is missing.
"""
backend = ToCupy.backend
def __init__(
self,
keys: KeysCollection,
dtype: np.dtype | None = None,
wrap_sequence: bool = True,
allow_missing_keys: bool = False,
) -> None:
super().__init__(keys, allow_missing_keys)
self.converter = ToCupy(dtype=dtype, wrap_sequence=wrap_sequence)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.converter(d[key])
return d
class ToPILd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.ToNumpy`.
"""
backend = ToPIL.backend
def __init__(self, keys: KeysCollection, allow_missing_keys: bool = False) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.converter = ToPIL()
def __call__(self, data: Mapping[Hashable, Any]) -> dict[Hashable, Any]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.converter(d[key])
return d
class Transposed(MapTransform, InvertibleTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Transpose`.
"""
backend = Transpose.backend
def __init__(self, keys: KeysCollection, indices: Sequence[int] | None, allow_missing_keys: bool = False) -> None:
super().__init__(keys, allow_missing_keys)
self.transform = Transpose(indices)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.transform(d[key])
# if None was supplied then numpy uses range(a.ndim)[::-1]
indices = self.transform.indices or range(d[key].ndim)[::-1]
self.push_transform(d, key, extra_info={"indices": indices})
return d
def inverse(self, data: Mapping[Hashable, Any]) -> dict[Hashable, Any]:
d = dict(data)
for key in self.key_iterator(d):
transform = self.get_most_recent_transform(d, key)
# Create inverse transform
fwd_indices = np.array(transform[TraceKeys.EXTRA_INFO]["indices"])
inv_indices = np.argsort(fwd_indices)
inverse_transform = Transpose(inv_indices.tolist())
# Apply inverse
d[key] = inverse_transform(d[key])
# Remove the applied transform
self.pop_transform(d, key)
return d
class DeleteItemsd(MapTransform):
"""
Delete specified items from data dictionary to release memory.
It will remove the key-values and copy the others to construct a new dictionary.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(self, keys: KeysCollection, sep: str = ".", use_re: Sequence[bool] | bool = False) -> None:
"""
Args:
keys: keys of the corresponding items to delete, can be "A{sep}B{sep}C"
to delete key `C` in nested dictionary, `C` can be regular expression.
See also: :py:class:`monai.transforms.compose.MapTransform`
sep: the separator tag to define nested dictionary keys, default to ".".
use_re: whether the specified key is a regular expression, it also can be
a list of bool values, mapping them to `keys`.
"""
super().__init__(keys)
self.sep = sep
self.use_re = ensure_tuple_rep(use_re, len(self.keys))
def __call__(self, data):
def _delete_item(keys, d, use_re: bool = False):
key = keys[0]
if len(keys) > 1:
d[key] = _delete_item(keys[1:], d[key], use_re)
return d
return {k: v for k, v in d.items() if (use_re and not re.search(key, f"{k}")) or (not use_re and k != key)}
d = dict(data)
for key, use_re in zip(cast(Sequence[str], self.keys), self.use_re):
d = _delete_item(key.split(self.sep), d, use_re)
return d
class SelectItemsd(MapTransform):
"""
Select only specified items from data dictionary to release memory.
It will copy the selected key-values and construct a new dictionary.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __call__(self, data):
return {key: data[key] for key in self.key_iterator(data)}
class FlattenSubKeysd(MapTransform):
"""
If an item is dictionary, it flatten the item by moving the sub-items (defined by sub-keys) to the top level.
{"pred": {"a": ..., "b", ... }} --> {"a": ..., "b", ... }
Args:
keys: keys of the corresponding items to be flatten
sub_keys: the sub-keys of items to be flatten. If not provided all the sub-keys are flattened.
delete_keys: whether to delete the key of the items that their sub-keys are flattened. Default to True.
prefix: optional prefix to be added to the sub-keys when moving to the top level.
By default no prefix will be added.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
keys: KeysCollection,
sub_keys: KeysCollection | None = None,
delete_keys: bool = True,
prefix: str | None = None,
) -> None:
super().__init__(keys)
self.sub_keys = sub_keys
self.delete_keys = delete_keys
self.prefix = prefix
def __call__(self, data):
d = dict(data)
for key in self.key_iterator(d):
# set the sub-keys for the specified key
sub_keys = d[key].keys() if self.sub_keys is None else self.sub_keys
# move all the sub-keys to the top level
for sk in sub_keys:
# set the top-level key for the sub-key
sk_top = f"{self.prefix}_{sk}" if self.prefix else sk
if sk_top in d:
raise ValueError(
f"'{sk_top}' already exists in the top-level keys. Please change `prefix` to avoid duplicity."
)
d[sk_top] = d[key][sk]
# delete top level key that is flattened
if self.delete_keys:
del d[key]
return d
class SqueezeDimd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.SqueezeDim`.
"""
backend = SqueezeDim.backend
def __init__(
self, keys: KeysCollection, dim: int = 0, update_meta: bool = True, allow_missing_keys: bool = False
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dim: dimension to be squeezed. Default: 0 (the first dimension)
update_meta: whether to update the meta info if the input is a metatensor. Default is ``True``.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.converter = SqueezeDim(dim=dim, update_meta=update_meta)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.converter(d[key])
return d
class DataStatsd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.DataStats`.
"""
backend = DataStats.backend
def __init__(
self,
keys: KeysCollection,
prefix: Sequence[str] | str = "Data",
data_type: Sequence[bool] | bool = True,
data_shape: Sequence[bool] | bool = True,
value_range: Sequence[bool] | bool = True,
data_value: Sequence[bool] | bool = False,
additional_info: Sequence[Callable] | Callable | None = None,
name: str = "DataStats",
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
prefix: will be printed in format: "{prefix} statistics".
it also can be a sequence of string, each element corresponds to a key in ``keys``.
data_type: whether to show the type of input data.
it also can be a sequence of bool, each element corresponds to a key in ``keys``.
data_shape: whether to show the shape of input data.
it also can be a sequence of bool, each element corresponds to a key in ``keys``.
value_range: whether to show the value range of input data.
it also can be a sequence of bool, each element corresponds to a key in ``keys``.
data_value: whether to show the raw value of input data.
it also can be a sequence of bool, each element corresponds to a key in ``keys``.
a typical example is to print some properties of Nifti image: affine, pixdim, etc.
additional_info: user can define callable function to extract
additional info from input data. it also can be a sequence of string, each element
corresponds to a key in ``keys``.
name: identifier of `logging.logger` to use, defaulting to "DataStats".
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.prefix = ensure_tuple_rep(prefix, len(self.keys))
self.data_type = ensure_tuple_rep(data_type, len(self.keys))
self.data_shape = ensure_tuple_rep(data_shape, len(self.keys))
self.value_range = ensure_tuple_rep(value_range, len(self.keys))
self.data_value = ensure_tuple_rep(data_value, len(self.keys))
self.additional_info = ensure_tuple_rep(additional_info, len(self.keys))
self.printer = DataStats(name=name)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key, prefix, data_type, data_shape, value_range, data_value, additional_info in self.key_iterator(
d, self.prefix, self.data_type, self.data_shape, self.value_range, self.data_value, self.additional_info
):
d[key] = self.printer(d[key], prefix, data_type, data_shape, value_range, data_value, additional_info)
return d
class SimulateDelayd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.SimulateDelay`.
"""
backend = SimulateDelay.backend
def __init__(
self, keys: KeysCollection, delay_time: Sequence[float] | float = 0.0, allow_missing_keys: bool = False
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
delay_time: The minimum amount of time, in fractions of seconds, to accomplish this identity task.
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.
"""
super().__init__(keys, allow_missing_keys)
self.delay_time = ensure_tuple_rep(delay_time, len(self.keys))
self.delayer = SimulateDelay()
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key, delay_time in self.key_iterator(d, self.delay_time):
d[key] = self.delayer(d[key], delay_time=delay_time)
return d
class CopyItemsd(MapTransform):
"""
Copy specified items from data dictionary and save with different key names.
It can copy several items together and copy several times.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
keys: KeysCollection,
times: int = 1,
names: KeysCollection | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
times: expected copy times, for example, if keys is "img", times is 3,
it will add 3 copies of "img" data to the dictionary, default to 1.
names: the names corresponding to the newly copied data,
the length should match `len(keys) x times`. for example, if keys is ["img", "seg"]
and times is 2, names can be: ["img_1", "seg_1", "img_2", "seg_2"].
if None, use "{key}_{index}" as key for copy times `N`, index from `0` to `N-1`.
allow_missing_keys: don't raise exception if key is missing.
Raises:
ValueError: When ``times`` is nonpositive.
ValueError: When ``len(names)`` is not ``len(keys) * times``. Incompatible values.
"""
super().__init__(keys, allow_missing_keys)
if times < 1:
raise ValueError(f"times must be positive, got {times}.")
self.times = times
names = [f"{k}_{i}" for k in self.keys for i in range(self.times)] if names is None else ensure_tuple(names)
if len(names) != (len(self.keys) * times):
raise ValueError(
"len(names) must match len(keys) * times, "
f"got len(names)={len(names)} len(keys) * times={len(self.keys) * times}."
)
self.names = names
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
"""
Raises:
KeyError: When a key in ``self.names`` already exists in ``data``.
"""
d = dict(data)
key_len = len(self.keys)
for i in range(self.times):
for key, new_key in self.key_iterator(d, self.names[i * key_len : (i + 1) * key_len]):
if new_key in d:
raise KeyError(f"Key {new_key} already exists in data.")
val = d[key]
d[new_key] = MetaObj.copy_items(val) if isinstance(val, (torch.Tensor, np.ndarray)) else deepcopy(val)
return d
class ConcatItemsd(MapTransform):
"""
Concatenate specified items from data dictionary together on the first dim to construct a big array.
Expect all the items are numpy array or PyTorch Tensor or MetaTensor.
Return the first input's meta information when items are MetaTensor.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(self, keys: KeysCollection, name: str, dim: int = 0, allow_missing_keys: bool = False) -> None:
"""
Args:
keys: keys of the corresponding items to be concatenated together.
See also: :py:class:`monai.transforms.compose.MapTransform`
name: the name corresponding to the key to store the concatenated data.
dim: on which dimension to concatenate the items, default is 0.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.name = name
self.dim = dim
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
"""
Raises:
TypeError: When items in ``data`` differ in type.
TypeError: When the item type is not in ``Union[numpy.ndarray, torch.Tensor, MetaTensor]``.
"""
d = dict(data)
output = []
data_type = None
for key in self.key_iterator(d):
if data_type is None:
data_type = type(d[key])
elif not isinstance(d[key], data_type):
raise TypeError("All items in data must have the same type.")
output.append(d[key])
if len(output) == 0:
return d
if data_type is np.ndarray:
d[self.name] = np.concatenate(output, axis=self.dim)
elif issubclass(data_type, torch.Tensor): # type: ignore
d[self.name] = torch.cat(output, dim=self.dim) # type: ignore
else:
raise TypeError(
f"Unsupported data type: {data_type}, available options are (numpy.ndarray, torch.Tensor, MetaTensor)."
)
return d
class Lambdad(MapTransform, InvertibleTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Lambda`.
For example:
.. code-block:: python
:emphasize-lines: 2
input_data={'image': np.zeros((10, 2, 2)), 'label': np.ones((10, 2, 2))}
lambd = Lambdad(keys='label', func=lambda x: x[:4, :, :])
print(lambd(input_data)['label'].shape)
(4, 2, 2)
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
func: Lambda/function to be applied. It also can be a sequence of Callable,
each element corresponds to a key in ``keys``.
inv_func: Lambda/function of inverse operation if want to invert transforms, default to `lambda x: x`.