-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathdictionary.py
1417 lines (1226 loc) · 67.8 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 box operations
defined in :py:class:`monai.apps.detection.transforms.array`.
Class names are ended with 'd' to denote dictionary-based transforms.
"""
from __future__ import annotations
from collections.abc import Hashable, Mapping, Sequence
from copy import deepcopy
from typing import Any
import numpy as np
import torch
from monai.apps.detection.transforms.array import (
AffineBox,
BoxToMask,
ClipBoxToImage,
ConvertBoxMode,
ConvertBoxToStandardMode,
FlipBox,
MaskToBox,
RotateBox90,
SpatialCropBox,
StandardizeEmptyBox,
ZoomBox,
)
from monai.apps.detection.transforms.box_ops import convert_box_to_mask
from monai.config import KeysCollection, SequenceStr
from monai.config.type_definitions import DtypeLike, NdarrayOrTensor
from monai.data.box_utils import COMPUTE_DTYPE, BoxMode, clip_boxes_to_image
from monai.data.meta_obj import get_meta_dict_name
from monai.data.meta_tensor import MetaTensor, get_track_meta
from monai.data.utils import orientation_ras_lps
from monai.transforms import Flip, RandFlip, RandZoom, Rotate90, SpatialCrop, Zoom
from monai.transforms.inverse import InvertibleTransform
from monai.transforms.transform import MapTransform, Randomizable, RandomizableTransform
from monai.transforms.utils import generate_pos_neg_label_crop_centers, map_binary_to_indices
from monai.utils import InterpolateMode, NumpyPadMode, ensure_tuple, ensure_tuple_rep, fall_back_tuple
from monai.utils.enums import PostFix, TraceKeys
from monai.utils.type_conversion import convert_data_type, convert_to_tensor
__all__ = [
"StandardizeEmptyBoxd",
"StandardizeEmptyBoxD",
"StandardizeEmptyBoxDict",
"ConvertBoxModed",
"ConvertBoxModeD",
"ConvertBoxModeDict",
"ConvertBoxToStandardModed",
"ConvertBoxToStandardModeD",
"ConvertBoxToStandardModeDict",
"AffineBoxToImageCoordinated",
"AffineBoxToImageCoordinateD",
"AffineBoxToImageCoordinateDict",
"ZoomBoxd",
"ZoomBoxD",
"ZoomBoxDict",
"RandZoomBoxd",
"RandZoomBoxD",
"RandZoomBoxDict",
"FlipBoxd",
"FlipBoxD",
"FlipBoxDict",
"RandFlipBoxd",
"RandFlipBoxD",
"RandFlipBoxDict",
"ClipBoxToImaged",
"ClipBoxToImageD",
"ClipBoxToImageDict",
"BoxToMaskd",
"BoxToMaskD",
"BoxToMaskDict",
"MaskToBoxd",
"MaskToBoxD",
"MaskToBoxDict",
"RandCropBoxByPosNegLabeld",
"RandCropBoxByPosNegLabelD",
"RandCropBoxByPosNegLabelDict",
"RotateBox90d",
"RotateBox90D",
"RotateBox90Dict",
"RandRotateBox90d",
"RandRotateBox90D",
"RandRotateBox90Dict",
]
DEFAULT_POST_FIX = PostFix.meta()
class StandardizeEmptyBoxd(MapTransform, InvertibleTransform):
"""
Dictionary-based wrapper of :py:class:`monai.apps.detection.transforms.array.StandardizeEmptyBox`.
When boxes are empty, this transform standardize it to shape of (0,4) or (0,6).
Example:
.. code-block:: python
data = {"boxes": torch.ones(0,), "image": torch.ones(1, 128, 128, 128)}
box_converter = StandardizeEmptyBoxd(box_keys=["boxes"], box_ref_image_keys="image")
box_converter(data)
"""
def __init__(self, box_keys: KeysCollection, box_ref_image_keys: str, allow_missing_keys: bool = False) -> None:
"""
Args:
box_keys: Keys to pick data for transformation.
box_ref_image_keys: The single key that represents the reference image to which ``box_keys`` are attached.
allow_missing_keys: don't raise exception if key is missing.
See also :py:class:`monai.apps.detection,transforms.array.ConvertBoxToStandardMode`
"""
super().__init__(box_keys, allow_missing_keys)
box_ref_image_keys_tuple = ensure_tuple(box_ref_image_keys)
if len(box_ref_image_keys_tuple) > 1:
raise ValueError(
"Please provide a single key for box_ref_image_keys.\
All boxes of box_keys are attached to box_ref_image_keys."
)
self.box_ref_image_keys = box_ref_image_keys
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
spatial_dims = len(d[self.box_ref_image_keys].shape) - 1
self.converter = StandardizeEmptyBox(spatial_dims=spatial_dims)
for key in self.key_iterator(d):
d[key] = self.converter(d[key])
return d
def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
return dict(data)
class ConvertBoxModed(MapTransform, InvertibleTransform):
"""
Dictionary-based wrapper of :py:class:`monai.apps.detection.transforms.array.ConvertBoxMode`.
This transform converts the boxes in src_mode to the dst_mode.
Example:
.. code-block:: python
data = {"boxes": torch.ones(10,4)}
# convert boxes with format [xmin, ymin, xmax, ymax] to [xcenter, ycenter, xsize, ysize].
box_converter = ConvertBoxModed(box_keys=["boxes"], src_mode="xyxy", dst_mode="ccwh")
box_converter(data)
"""
def __init__(
self,
box_keys: KeysCollection,
src_mode: str | BoxMode | type[BoxMode] | None = None,
dst_mode: str | BoxMode | type[BoxMode] | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
box_keys: Keys to pick data for transformation.
src_mode: source box mode. If it is not given, this func will assume it is ``StandardMode()``.
It follows the same format with ``src_mode`` in :class:`~monai.apps.detection.transforms.array.ConvertBoxMode` .
dst_mode: target box mode. If it is not given, this func will assume it is ``StandardMode()``.
It follows the same format with ``src_mode`` in :class:`~monai.apps.detection.transforms.array.ConvertBoxMode` .
allow_missing_keys: don't raise exception if key is missing.
See also :py:class:`monai.apps.detection,transforms.array.ConvertBoxMode`
"""
super().__init__(box_keys, allow_missing_keys)
self.converter = ConvertBoxMode(src_mode=src_mode, dst_mode=dst_mode)
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, extra_info={"src": self.converter.src_mode, "dst": self.converter.dst_mode})
return d
def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
tr = self.get_most_recent_transform(d, key)
src_mode, dst_mode = tr[TraceKeys.EXTRA_INFO]["src"], tr[TraceKeys.EXTRA_INFO]["dst"]
inverse_converter = ConvertBoxMode(src_mode=dst_mode, dst_mode=src_mode)
# Inverse is same as forward
d[key] = inverse_converter(d[key])
# Remove the applied transform
self.pop_transform(d, key)
return d
class ConvertBoxToStandardModed(MapTransform, InvertibleTransform):
"""
Dictionary-based wrapper of :py:class:`monai.apps.detection.transforms.array.ConvertBoxToStandardMode`.
Convert given boxes to standard mode.
Standard mode is "xyxy" or "xyzxyz",
representing box format of [xmin, ymin, xmax, ymax] or [xmin, ymin, zmin, xmax, ymax, zmax].
Example:
.. code-block:: python
data = {"boxes": torch.ones(10,6)}
# convert boxes with format [xmin, xmax, ymin, ymax, zmin, zmax] to [xmin, ymin, zmin, xmax, ymax, zmax]
box_converter = ConvertBoxToStandardModed(box_keys=["boxes"], mode="xxyyzz")
box_converter(data)
"""
def __init__(
self,
box_keys: KeysCollection,
mode: str | BoxMode | type[BoxMode] | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
box_keys: Keys to pick data for transformation.
mode: source box mode. If it is not given, this func will assume it is ``StandardMode()``.
It follows the same format with ``src_mode`` in :class:`~monai.apps.detection.transforms.array.ConvertBoxMode` .
allow_missing_keys: don't raise exception if key is missing.
See also :py:class:`monai.apps.detection,transforms.array.ConvertBoxToStandardMode`
"""
super().__init__(box_keys, allow_missing_keys)
self.converter = ConvertBoxToStandardMode(mode=mode)
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, extra_info={"mode": self.converter.mode})
return d
def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
tr = self.get_most_recent_transform(d, key)
original_mode = tr[TraceKeys.EXTRA_INFO]["mode"]
inverse_converter = ConvertBoxMode(src_mode=None, dst_mode=original_mode)
# Inverse is same as forward
d[key] = inverse_converter(d[key])
# Remove the applied transform
self.pop_transform(d, key)
return d
class AffineBoxToImageCoordinated(MapTransform, InvertibleTransform):
"""
Dictionary-based transform that converts box in world coordinate to image coordinate.
Args:
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_ref_image_keys: The single key that represents the reference image to which ``box_keys`` are attached.
remove_empty: whether to remove the boxes that are actually empty
allow_missing_keys: don't raise exception if key is missing.
image_meta_key: explicitly indicate the key of the corresponding metadata dictionary.
for example, for data with key `image`, the metadata by default is in `image_meta_dict`.
the metadata is a dictionary object which contains: filename, affine, original_shape, etc.
it is a string, map to the `box_ref_image_key`.
if None, will try to construct meta_keys by `box_ref_image_key_{meta_key_postfix}`.
image_meta_key_postfix: if image_meta_keys=None, use `box_ref_image_key_{postfix}` to fetch the metadata according
to the key data, default is `meta_dict`, the metadata is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
affine_lps_to_ras: default ``False``. Yet if 1) the image is read by ITKReader,
and 2) the ITKReader has affine_lps_to_ras=True, and 3) the box is in world coordinate,
then set ``affine_lps_to_ras=True``.
"""
def __init__(
self,
box_keys: KeysCollection,
box_ref_image_keys: str,
allow_missing_keys: bool = False,
image_meta_key: str | None = None,
image_meta_key_postfix: str | None = DEFAULT_POST_FIX,
affine_lps_to_ras: bool = False,
) -> None:
super().__init__(box_keys, allow_missing_keys)
box_ref_image_keys_tuple = ensure_tuple(box_ref_image_keys)
if len(box_ref_image_keys_tuple) > 1:
raise ValueError(
"Please provide a single key for box_ref_image_keys.\
All boxes of box_keys are attached to box_ref_image_keys."
)
self.box_ref_image_keys = box_ref_image_keys
self.image_meta_key = image_meta_key or f"{box_ref_image_keys}_{image_meta_key_postfix}"
self.converter_to_image_coordinate = AffineBox()
self.affine_lps_to_ras = affine_lps_to_ras
def extract_affine(self, data: Mapping[Hashable, torch.Tensor]) -> tuple[NdarrayOrTensor, torch.Tensor]:
d = dict(data)
meta_key = self.image_meta_key
# extract affine matrix from metadata
if isinstance(d[self.box_ref_image_keys], MetaTensor):
meta_dict = d[self.box_ref_image_keys].meta # type: ignore
elif meta_key in d:
meta_dict = d[meta_key]
else:
meta_key = get_meta_dict_name(self.box_ref_image_keys, d)
if meta_key not in d:
raise ValueError(f"{self.image_meta_key} is not found. Please check whether it is the correct the image meta key.")
if "affine" not in meta_dict:
raise ValueError(
f"'affine' is not found in {meta_key}. \
Please check whether it is the correct the image meta key."
)
affine: NdarrayOrTensor = meta_dict["affine"]
if self.affine_lps_to_ras: # RAS affine
affine = orientation_ras_lps(affine)
# when convert boxes from world coordinate to image coordinate,
# we apply inverse affine transform
affine_t, *_ = convert_data_type(affine, torch.Tensor)
# torch.inverse should not run in half precision
inv_affine_t = torch.inverse(affine_t.to(COMPUTE_DTYPE))
return affine, inv_affine_t
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
affine, inv_affine_t = self.extract_affine(data) # type: ignore
for key in self.key_iterator(d):
d[key] = self.converter_to_image_coordinate(d[key], affine=inv_affine_t)
self.push_transform(d, key, extra_info={"affine": affine})
return d
def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
transform = self.get_most_recent_transform(d, key)
affine = transform["extra_info"]["affine"]
d[key] = AffineBox()(d[key], affine=affine)
self.pop_transform(d, key)
return d
class AffineBoxToWorldCoordinated(AffineBoxToImageCoordinated):
"""
Dictionary-based transform that converts box in image coordinate to world coordinate.
Args:
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_ref_image_keys: The single key that represents the reference image to which ``box_keys`` are attached.
remove_empty: whether to remove the boxes that are actually empty
allow_missing_keys: don't raise exception if key is missing.
image_meta_key: explicitly indicate the key of the corresponding metadata dictionary.
for example, for data with key `image`, the metadata by default is in `image_meta_dict`.
the metadata is a dictionary object which contains: filename, affine, original_shape, etc.
it is a string, map to the `box_ref_image_key`.
if None, will try to construct meta_keys by `box_ref_image_key_{meta_key_postfix}`.
image_meta_key_postfix: if image_meta_keys=None, use `box_ref_image_key_{postfix}` to fetch the metadata according
to the key data, default is `meta_dict`, the metadata is a dictionary object.
For example, to handle key `image`, read/write affine matrices from the
metadata `image_meta_dict` dictionary's `affine` field.
affine_lps_to_ras: default ``False``. Yet if 1) the image is read by ITKReader,
and 2) the ITKReader has affine_lps_to_ras=True, and 3) the box is in world coordinate,
then set ``affine_lps_to_ras=True``.
"""
def __init__(
self,
box_keys: KeysCollection,
box_ref_image_keys: str,
allow_missing_keys: bool = False,
image_meta_key: str | None = None,
image_meta_key_postfix: str | None = DEFAULT_POST_FIX,
affine_lps_to_ras: bool = False,
) -> None:
super().__init__(
box_keys, box_ref_image_keys, allow_missing_keys, image_meta_key, image_meta_key_postfix, affine_lps_to_ras
)
self.converter_to_world_coordinate = AffineBox()
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
affine, inv_affine_t = self.extract_affine(data) # type: ignore
for key in self.key_iterator(d):
d[key] = self.converter_to_world_coordinate(d[key], affine=affine)
self.push_transform(d, key, extra_info={"affine": inv_affine_t})
return d
class ZoomBoxd(MapTransform, InvertibleTransform):
"""
Dictionary-based transform that zooms input boxes and images with the given zoom scale.
Args:
image_keys: Keys to pick image data for transformation.
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_ref_image_keys: Keys that represent the reference images to which ``box_keys`` are attached.
zoom: The zoom factor along the spatial axes.
If a float, zoom is the same for each spatial axis.
If a sequence, zoom should contain one value for each spatial axis.
mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}
The interpolation mode. Defaults to ``"area"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``,
``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``}
available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}.
One of the listed string values or a user supplied function. Defaults to ``"constant"``.
The mode to pad data after zooming.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
align_corners: This only has an effect when mode is
'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of bool or None, each element corresponds to a key in ``keys``.
keep_size: Should keep original size (pad if needed), default is True.
allow_missing_keys: don't raise exception if key is missing.
kwargs: other arguments for the `np.pad` or `torch.pad` function.
note that `np.pad` treats channel dimension as the first dimension.
"""
def __init__(
self,
image_keys: KeysCollection,
box_keys: KeysCollection,
box_ref_image_keys: KeysCollection,
zoom: Sequence[float] | float,
mode: SequenceStr = InterpolateMode.AREA,
padding_mode: SequenceStr = NumpyPadMode.EDGE,
align_corners: Sequence[bool | None] | bool | None = None,
keep_size: bool = True,
allow_missing_keys: bool = False,
**kwargs: Any,
) -> None:
self.image_keys = ensure_tuple(image_keys)
self.box_keys = ensure_tuple(box_keys)
super().__init__(self.image_keys + self.box_keys, allow_missing_keys)
self.box_ref_image_keys = ensure_tuple_rep(box_ref_image_keys, len(self.box_keys))
self.mode = ensure_tuple_rep(mode, len(self.image_keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.image_keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.image_keys))
self.zoomer = Zoom(zoom=zoom, keep_size=keep_size, **kwargs)
self.keep_size = keep_size
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d: dict[Hashable, torch.Tensor] = dict(data)
# zoom box
for box_key, box_ref_image_key in zip(self.box_keys, self.box_ref_image_keys):
src_spatial_size = d[box_ref_image_key].shape[1:]
dst_spatial_size = [int(round(z * ss)) for z, ss in zip(self.zoomer.zoom, src_spatial_size)] # type: ignore
self.zoomer.zoom = [ds / float(ss) for ss, ds in zip(src_spatial_size, dst_spatial_size)]
d[box_key] = ZoomBox(zoom=self.zoomer.zoom, keep_size=self.keep_size)(
d[box_key], src_spatial_size=src_spatial_size
)
self.push_transform(
d,
box_key,
extra_info={"zoom": self.zoomer.zoom, "src_spatial_size": src_spatial_size, "type": "box_key"},
)
# zoom image
for key, mode, padding_mode, align_corners in zip(
self.image_keys, self.mode, self.padding_mode, self.align_corners
):
d[key] = self.zoomer(d[key], mode=mode, padding_mode=padding_mode, align_corners=align_corners)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d: dict[Hashable, torch.Tensor] = dict(data)
for key in self.key_iterator(d):
transform = self.get_most_recent_transform(d, key, check=False)
key_type = transform[TraceKeys.EXTRA_INFO].get("type", "image_key")
# zoom image, copied from monai.transforms.spatial.dictionary.Zoomd
if key_type == "image_key":
d[key] = self.zoomer.inverse(d[key])
# zoom boxes
if key_type == "box_key":
zoom = np.array(transform[TraceKeys.EXTRA_INFO]["zoom"])
src_spatial_size = transform[TraceKeys.EXTRA_INFO]["src_spatial_size"]
box_inverse_transform = ZoomBox(zoom=(1 / zoom).tolist(), keep_size=self.zoomer.keep_size)
d[key] = box_inverse_transform(d[key], src_spatial_size=src_spatial_size)
# Remove the applied transform
self.pop_transform(d, key)
return d
class RandZoomBoxd(RandomizableTransform, MapTransform, InvertibleTransform):
"""
Dictionary-based transform that randomly zooms input boxes and images with given probability within given zoom range.
Args:
image_keys: Keys to pick image data for transformation.
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_ref_image_keys: Keys that represent the reference images to which ``box_keys`` are attached.
prob: Probability of zooming.
min_zoom: Min zoom factor. Can be float or sequence same size as image.
If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims
to keep the original spatial shape ratio.
If a sequence, min_zoom should contain one value for each spatial axis.
If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio.
max_zoom: Max zoom factor. Can be float or sequence same size as image.
If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims
to keep the original spatial shape ratio.
If a sequence, max_zoom should contain one value for each spatial axis.
If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio.
mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}
The interpolation mode. Defaults to ``"area"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``,
``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``}
available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}.
One of the listed string values or a user supplied function. Defaults to ``"constant"``.
The mode to pad data after zooming.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
align_corners: This only has an effect when mode is
'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of bool or None, each element corresponds to a key in ``keys``.
keep_size: Should keep original size (pad if needed), default is True.
allow_missing_keys: don't raise exception if key is missing.
kwargs: other args for `np.pad` API, note that `np.pad` treats channel dimension as the first dimension.
more details: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
"""
backend = RandZoom.backend
def __init__(
self,
image_keys: KeysCollection,
box_keys: KeysCollection,
box_ref_image_keys: KeysCollection,
prob: float = 0.1,
min_zoom: Sequence[float] | float = 0.9,
max_zoom: Sequence[float] | float = 1.1,
mode: SequenceStr = InterpolateMode.AREA,
padding_mode: SequenceStr = NumpyPadMode.EDGE,
align_corners: Sequence[bool | None] | bool | None = None,
keep_size: bool = True,
allow_missing_keys: bool = False,
**kwargs: Any,
) -> None:
self.image_keys = ensure_tuple(image_keys)
self.box_keys = ensure_tuple(box_keys)
MapTransform.__init__(self, self.image_keys + self.box_keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
self.box_ref_image_keys = ensure_tuple_rep(box_ref_image_keys, len(self.box_keys))
self.rand_zoom = RandZoom(prob=1.0, min_zoom=min_zoom, max_zoom=max_zoom, keep_size=keep_size, **kwargs)
self.mode = ensure_tuple_rep(mode, len(self.image_keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.image_keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.image_keys))
self.keep_size = keep_size
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandZoomBoxd:
super().set_random_state(seed, state)
self.rand_zoom.set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
first_key: Hashable = self.first_key(d)
if first_key == ():
return d
self.randomize(None)
# all the keys share the same random zoom factor
self.rand_zoom.randomize(d[first_key])
# zoom box
for box_key, box_ref_image_key in zip(self.box_keys, self.box_ref_image_keys):
if self._do_transform:
src_spatial_size = d[box_ref_image_key].shape[1:]
dst_spatial_size = [int(round(z * ss)) for z, ss in zip(self.rand_zoom._zoom, src_spatial_size)]
self.rand_zoom._zoom = [ds / float(ss) for ss, ds in zip(src_spatial_size, dst_spatial_size)]
d[box_key] = ZoomBox(zoom=self.rand_zoom._zoom, keep_size=self.keep_size)(
d[box_key], src_spatial_size=src_spatial_size
)
self.push_transform(
d,
box_key,
extra_info={"zoom": self.rand_zoom._zoom, "src_spatial_size": src_spatial_size, "type": "box_key"},
)
# zoom image, copied from monai.transforms.spatial.dictionary.RandZoomd
for key, mode, padding_mode, align_corners in zip(
self.image_keys, self.mode, self.padding_mode, self.align_corners
):
if self._do_transform:
d[key] = self.rand_zoom(
d[key], mode=mode, padding_mode=padding_mode, align_corners=align_corners, randomize=False
)
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta())
if get_track_meta():
xform = self.pop_transform(d[key], check=False) if self._do_transform else {}
self.push_transform(d[key], extra_info=xform)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
transform = self.get_most_recent_transform(d, key, check=False)
key_type = transform[TraceKeys.EXTRA_INFO].get("type", "image_key")
# Check if random transform was actually performed (based on `prob`)
if transform[TraceKeys.DO_TRANSFORM]:
# zoom image, copied from monai.transforms.spatial.dictionary.Zoomd
if key_type == "image_key":
xform = self.pop_transform(d[key])
d[key].applied_operations.append(xform[TraceKeys.EXTRA_INFO]) # type: ignore
d[key] = self.rand_zoom.inverse(d[key])
# zoom boxes
if key_type == "box_key":
# Create inverse transform
zoom = np.array(transform[TraceKeys.EXTRA_INFO]["zoom"])
src_spatial_size = transform[TraceKeys.EXTRA_INFO]["src_spatial_size"]
box_inverse_transform = ZoomBox(zoom=(1.0 / zoom).tolist(), keep_size=self.rand_zoom.keep_size)
d[key] = box_inverse_transform(d[key], src_spatial_size=src_spatial_size)
# Remove the applied transform
self.pop_transform(d, key)
return d
class FlipBoxd(MapTransform, InvertibleTransform):
"""
Dictionary-based transform that flip boxes and images.
Args:
image_keys: Keys to pick image data for transformation.
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_ref_image_keys: Keys that represent the reference images to which ``box_keys`` are attached.
spatial_axis: Spatial axes along which to flip over. Default is None.
allow_missing_keys: don't raise exception if key is missing.
"""
backend = Flip.backend
def __init__(
self,
image_keys: KeysCollection,
box_keys: KeysCollection,
box_ref_image_keys: KeysCollection,
spatial_axis: Sequence[int] | int | None = None,
allow_missing_keys: bool = False,
) -> None:
self.image_keys = ensure_tuple(image_keys)
self.box_keys = ensure_tuple(box_keys)
super().__init__(self.image_keys + self.box_keys, allow_missing_keys)
self.box_ref_image_keys = ensure_tuple_rep(box_ref_image_keys, len(self.box_keys))
self.flipper = Flip(spatial_axis=spatial_axis)
self.box_flipper = FlipBox(spatial_axis=self.flipper.spatial_axis)
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.image_keys:
d[key] = self.flipper(d[key])
for box_key, box_ref_image_key in zip(self.box_keys, self.box_ref_image_keys):
spatial_size = d[box_ref_image_key].shape[1:]
d[box_key] = self.box_flipper(d[box_key], spatial_size)
self.push_transform(d, box_key, extra_info={"spatial_size": spatial_size, "type": "box_key"})
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
transform = self.get_most_recent_transform(d, key, check=False)
key_type = transform.get(TraceKeys.EXTRA_INFO, {}).get("type", "image_key")
# flip image, copied from monai.transforms.spatial.dictionary.Flipd
if key_type == "image_key":
d[key] = self.flipper.inverse(d[key])
# flip boxes
if key_type == "box_key":
spatial_size = transform[TraceKeys.EXTRA_INFO]["spatial_size"]
d[key] = self.box_flipper(d[key], spatial_size)
# Remove the applied transform
self.pop_transform(d, key)
return d
class RandFlipBoxd(RandomizableTransform, MapTransform, InvertibleTransform):
"""
Dictionary-based transform that randomly flip boxes and images with the given probabilities.
Args:
image_keys: Keys to pick image data for transformation.
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_ref_image_keys: Keys that represent the reference images to which ``box_keys`` are attached.
prob: Probability of flipping.
spatial_axis: Spatial axes along which to flip over. Default is None.
allow_missing_keys: don't raise exception if key is missing.
"""
backend = RandFlip.backend
def __init__(
self,
image_keys: KeysCollection,
box_keys: KeysCollection,
box_ref_image_keys: KeysCollection,
prob: float = 0.1,
spatial_axis: Sequence[int] | int | None = None,
allow_missing_keys: bool = False,
) -> None:
self.image_keys = ensure_tuple(image_keys)
self.box_keys = ensure_tuple(box_keys)
MapTransform.__init__(self, self.image_keys + self.box_keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
self.box_ref_image_keys = ensure_tuple_rep(box_ref_image_keys, len(self.box_keys))
self.flipper = Flip(spatial_axis=spatial_axis)
self.box_flipper = FlipBox(spatial_axis=spatial_axis)
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandFlipBoxd:
super().set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
self.randomize(None)
for key in self.image_keys:
if self._do_transform:
d[key] = self.flipper(d[key])
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta())
if get_track_meta():
xform_info = self.pop_transform(d[key], check=False) if self._do_transform else {}
self.push_transform(d[key], extra_info=xform_info)
for box_key, box_ref_image_key in zip(self.box_keys, self.box_ref_image_keys):
spatial_size = d[box_ref_image_key].shape[1:]
if self._do_transform:
d[box_key] = self.box_flipper(d[box_key], spatial_size)
self.push_transform(d, box_key, extra_info={"spatial_size": spatial_size, "type": "box_key"})
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
transform = self.get_most_recent_transform(d, key, check=False)
key_type = transform[TraceKeys.EXTRA_INFO].get("type", "image_key")
# Check if random transform was actually performed (based on `prob`)
if transform[TraceKeys.DO_TRANSFORM]:
# flip image, copied from monai.transforms.spatial.dictionary.RandFlipd
if key_type == "image_key":
with self.flipper.trace_transform(False):
d[key] = self.flipper(d[key])
# flip boxes
if key_type == "box_key":
spatial_size = transform[TraceKeys.EXTRA_INFO]["spatial_size"]
d[key] = self.box_flipper(d[key], spatial_size)
# Remove the applied transform
self.pop_transform(d, key, check=False)
return d
class ClipBoxToImaged(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.apps.detection.transforms.array.ClipBoxToImage`.
Clip the bounding boxes and the associated labels/scores to makes sure they are within the image.
There might be multiple keys of labels/scores associated with one key of boxes.
Args:
box_keys: The single key to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
label_keys: Keys that represent the labels corresponding to the ``box_keys``. Multiple keys are allowed.
box_ref_image_keys: The single key that represents the reference image
to which ``box_keys`` and ``label_keys`` are attached.
remove_empty: whether to remove the boxes that are actually empty
allow_missing_keys: don't raise exception if key is missing.
Example:
.. code-block:: python
ClipBoxToImaged(
box_keys="boxes", box_ref_image_keys="image", label_keys=["labels", "scores"], remove_empty=True
)
"""
def __init__(
self,
box_keys: KeysCollection,
label_keys: KeysCollection,
box_ref_image_keys: KeysCollection,
remove_empty: bool = True,
allow_missing_keys: bool = False,
) -> None:
box_keys_tuple = ensure_tuple(box_keys)
if len(box_keys_tuple) != 1:
raise ValueError(
"Please provide a single key for box_keys.\
All label_keys are attached to this box_keys."
)
box_ref_image_keys_tuple = ensure_tuple(box_ref_image_keys)
if len(box_ref_image_keys_tuple) != 1:
raise ValueError(
"Please provide a single key for box_ref_image_keys.\
All box_keys and label_keys are attached to this box_ref_image_keys."
)
self.label_keys = ensure_tuple(label_keys)
super().__init__(box_keys_tuple, allow_missing_keys)
self.box_keys = box_keys_tuple[0]
self.box_ref_image_keys = box_ref_image_keys_tuple[0]
self.clipper = ClipBoxToImage(remove_empty=remove_empty)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
spatial_size = d[self.box_ref_image_keys].shape[1:]
labels = [d[label_key] for label_key in self.label_keys] # could be multiple arrays
d[self.box_keys], clipped_labels = self.clipper(d[self.box_keys], labels, spatial_size)
for label_key, clipped_labels_i in zip(self.label_keys, clipped_labels):
d[label_key] = clipped_labels_i
return d
class BoxToMaskd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.apps.detection.transforms.array.BoxToMask`.
Pairs with :py:class:`monai.apps.detection.transforms.dictionary.MaskToBoxd` .
Please make sure the same ``min_fg_label`` is used when using the two transforms in pairs.
The output ``d[box_mask_key]`` will have background intensity 0, since the following operations
may pad 0 on the border.
This is the general solution for transforms that need to be applied on images and boxes simultaneously.
It is performed with the following steps.
1) use ``BoxToMaskd`` to covert boxes and labels to box_masks;
2) do transforms, e.g., rotation or cropping, on images and box_masks together;
3) use ``MaskToBoxd`` to convert box_masks back to boxes and labels.
Args:
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_mask_keys: Keys to store output box mask results for transformation. Same length with ``box_keys``.
label_keys: Keys that represent the labels corresponding to the ``box_keys``. Same length with ``box_keys``.
box_ref_image_keys: Keys that represent the reference images to which ``box_keys`` are attached.
min_fg_label: min foreground box label.
ellipse_mask: bool.
- If True, it assumes the object shape is close to ellipse or ellipsoid.
- If False, it assumes the object shape is close to rectangle or cube and well occupies the bounding box.
- If the users are going to apply random rotation as data augmentation, we suggest setting ellipse_mask=True
See also Kalra et al. "Towards Rotation Invariance in Object Detection", ICCV 2021.
allow_missing_keys: don't raise exception if key is missing.
Example:
.. code-block:: python
# This code snippet creates transforms (random rotation and cropping) on boxes, labels, and image together.
import numpy as np
from monai.transforms import Compose, RandRotated, RandSpatialCropd, DeleteItemsd
transforms = Compose(
[
BoxToMaskd(
box_keys="boxes", label_keys="labels",
box_mask_keys="box_mask", box_ref_image_keys="image",
min_fg_label=0, ellipse_mask=True
),
RandRotated(keys=["image","box_mask"],mode=["nearest","nearest"],
prob=0.2,range_x=np.pi/6,range_y=np.pi/6,range_z=np.pi/6,
keep_size=True,padding_mode="zeros"
),
RandSpatialCropd(keys=["image","box_mask"],roi_size=128, random_size=False),
MaskToBoxd(
box_mask_keys="box_mask", box_keys="boxes",
label_keys="labels", min_fg_label=0
)
DeleteItemsd(keys=["box_mask"]),
]
)
"""
def __init__(
self,
box_keys: KeysCollection,
box_mask_keys: KeysCollection,
label_keys: KeysCollection,
box_ref_image_keys: KeysCollection,
min_fg_label: int,
ellipse_mask: bool = False,
allow_missing_keys: bool = False,
) -> None:
super().__init__(box_keys, allow_missing_keys)
self.box_keys = ensure_tuple(box_keys)
self.label_keys = ensure_tuple(label_keys)
self.box_mask_keys = ensure_tuple(box_mask_keys)
if not len(self.label_keys) == len(self.box_keys) == len(self.box_mask_keys):
raise ValueError("Please make sure len(label_keys)==len(box_keys)==len(box_mask_keys)!")
self.box_ref_image_keys = ensure_tuple_rep(box_ref_image_keys, len(self.box_keys))
self.bg_label = min_fg_label - 1 # make sure background label is always smaller than fg labels.
self.converter = BoxToMask(bg_label=self.bg_label, ellipse_mask=ellipse_mask)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for box_key, label_key, box_mask_key, box_ref_image_key in zip(
self.box_keys, self.label_keys, self.box_mask_keys, self.box_ref_image_keys
):
spatial_size = d[box_ref_image_key].shape[1:]
d[box_mask_key] = self.converter(d[box_key], d[label_key], spatial_size)
# make box mask background intensity to be 0, since the following operations may pad 0 on the border.
d[box_mask_key] -= self.bg_label
return d
class MaskToBoxd(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.apps.detection.transforms.array.MaskToBox`.
Pairs with :py:class:`monai.apps.detection.transforms.dictionary.BoxToMaskd` .
Please make sure the same ``min_fg_label`` is used when using the two transforms in pairs.
This is the general solution for transforms that need to be applied on images and boxes simultaneously.
It is performed with the following steps.
1) use ``BoxToMaskd`` to covert boxes and labels to box_masks;
2) do transforms, e.g., rotation or cropping, on images and box_masks together;
3) use ``MaskToBoxd`` to convert box_masks back to boxes and labels.
Args:
box_keys: Keys to pick box data for transformation. The box mode is assumed to be ``StandardMode``.
box_mask_keys: Keys to store output box mask results for transformation. Same length with ``box_keys``.
label_keys: Keys that represent the labels corresponding to the ``box_keys``. Same length with ``box_keys``.
min_fg_label: min foreground box label.
box_dtype: output dtype for box_keys
label_dtype: output dtype for label_keys
allow_missing_keys: don't raise exception if key is missing.
Example:
.. code-block:: python
# This code snippet creates transforms (random rotation and cropping) on boxes, labels, and images together.
import numpy as np
from monai.transforms import Compose, RandRotated, RandSpatialCropd, DeleteItemsd
transforms = Compose(
[
BoxToMaskd(
box_keys="boxes", label_keys="labels",
box_mask_keys="box_mask", box_ref_image_keys="image",
min_fg_label=0, ellipse_mask=True
),
RandRotated(keys=["image","box_mask"],mode=["nearest","nearest"],
prob=0.2,range_x=np.pi/6,range_y=np.pi/6,range_z=np.pi/6,
keep_size=True,padding_mode="zeros"
),
RandSpatialCropd(keys=["image","box_mask"],roi_size=128, random_size=False),
MaskToBoxd(
box_mask_keys="box_mask", box_keys="boxes",
label_keys="labels", min_fg_label=0
)
DeleteItemsd(keys=["box_mask"]),
]
)
"""
def __init__(
self,
box_keys: KeysCollection,
box_mask_keys: KeysCollection,
label_keys: KeysCollection,
min_fg_label: int,
box_dtype: DtypeLike | torch.dtype = torch.float32,
label_dtype: DtypeLike | torch.dtype = torch.long,
allow_missing_keys: bool = False,
) -> None:
super().__init__(box_keys, allow_missing_keys)
self.box_keys = ensure_tuple(box_keys)
self.label_keys = ensure_tuple(label_keys)